aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/misc/compare-inl.h
blob: b9dfb5319f5ca540f61796afebb59aa174455acf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#ifndef COMPARE_INL_H_
#error "Direct inclusion of this file is not allowed, include compare.h"
// For the sake of sane code completion.
#include "compare.h"
#endif

#include "numeric_helpers.h"

#include <util/generic/string.h>

#include <string>
#include <string_view>

namespace NYT {

////////////////////////////////////////////////////////////////////////////////

template <class T>
Y_FORCE_INLINE int TernaryCompare(const T& lhs, const T& rhs)
{
    if (lhs == rhs) {
        return 0;
    } else if (lhs < rhs) {
        return -1;
    } else {
        return +1;
    }
}

//! An optimized version for string types.
template <class T>
    requires
        std::is_same_v<T, TString> ||
        std::is_same_v<T, TStringBuf> ||
        std::is_same_v<T, std::string> ||
        std::is_same_v<T, std::string_view>
Y_FORCE_INLINE int TernaryCompare(const T& lhs, const T& rhs)
{
    return GetSign(std::string_view(lhs).compare(std::string_view(rhs)));
}

template <class T>
Y_FORCE_INLINE int NaNSafeTernaryCompare(const T& lhs, const T& rhs)
{
    return TernaryCompare(lhs, rhs);
}

template <class T>
    requires std::is_floating_point_v<T>
Y_FORCE_INLINE int NaNSafeTernaryCompare(const T& lhs, const T& rhs)
{
    if (lhs < rhs) {
        return -1;
    } else if (lhs > rhs) {
        return +1;
    } else if (std::isnan(lhs)) {
        if (std::isnan(rhs)) {
            return 0;
        } else {
            return +1;
        }
    } else if (std::isnan(rhs)) {
        return -1;
    } else {
        return 0;
    }
}

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT