aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/case_insensitive_string/case_insensitive_char_traits.h
blob: fdf5f3a6c0865a636852af72f0d1df9a01287eb0 (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
#pragma once

#include <contrib/libs/libc_compat/string.h>

#include <util/string/ascii.h>

#include <string>

namespace NPrivate {
    template <typename TImpl>
    struct TCommonCaseInsensitiveCharTraits : private std::char_traits<char> {
        static bool eq(char c1, char c2) {
            return TImpl::ToCommonCase(c1) == TImpl::ToCommonCase(c2);
        }

        static bool lt(char c1, char c2) {
            return TImpl::ToCommonCase(c1) < TImpl::ToCommonCase(c2);
        }

        static const char* find(const char* s, std::size_t n, char a);

        using std::char_traits<char>::assign;
        using std::char_traits<char>::char_type;
        using std::char_traits<char>::copy;
        using std::char_traits<char>::length;
        using std::char_traits<char>::move;
    };
} // namespace NPrivate

struct TCaseInsensitiveCharTraits : public ::NPrivate::TCommonCaseInsensitiveCharTraits<TCaseInsensitiveCharTraits> {
    static int compare(const char* s1, const char* s2, std::size_t n);

private:
    friend ::NPrivate::TCommonCaseInsensitiveCharTraits<TCaseInsensitiveCharTraits>;

    // XXX return unsigned char. Current impl depends on char signedness, and if char is signed,
    // TCaseInsensitiveCharTraits::compare returns different result from std::char_traits<char>::compare for non-ascii strings.
    static char ToCommonCase(char ch) {
        return std::toupper((unsigned char)ch);
    }
};

struct TCaseInsensitiveAsciiCharTraits : public ::NPrivate::TCommonCaseInsensitiveCharTraits<TCaseInsensitiveCharTraits> {
    // WARN: does not work with null bytes (`compare("ab\0c", "ab\0d", 4)` returns 0).
    static int compare(const char* s1, const char* s2, std::size_t n) {
        return ::strncasecmp(s1, s2, n);
    }

private:
    friend ::NPrivate::TCommonCaseInsensitiveCharTraits<TCaseInsensitiveAsciiCharTraits>;

    static unsigned char ToCommonCase(char ch) {
        return AsciiToLower(ch);
    }
};