aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/case_insensitive_string/case_insensitive_string.cpp
blob: 25fedd36eb35b2087d5d794b459335355dbd855d (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
#include "case_insensitive_string.h"

#include <library/cpp/digest/murmur/murmur.h>

#include <util/string/escape.h>

#include <array>

namespace {
    template <auto ToLower>
    struct TCaseInsensitiveHash {
        static size_t HashTail(TMurmurHash2A<size_t>& hash, const char* data, size_t size) noexcept {
            for (size_t i = 0; i < size; ++i) {
                char lower = ToLower(data[i]);
                hash.Update(&lower, 1);
            }
            return hash.Value();
        }

        static size_t ComputeHash(const char* s, size_t n) noexcept {
            TMurmurHash2A<size_t> hash;
            std::array<char, sizeof(size_t)> buf;
            size_t headSize = n - n % buf.size();
            for (size_t i = 0; i < headSize; i += buf.size()) {
                for (size_t j = 0; j < buf.size(); ++j) {
                    buf[j] = ToLower(s[i + j]);
                }
                hash.Update(buf.data(), buf.size());
            }
            return HashTail(hash, s + headSize, n - headSize);
        }
    };
}

size_t CaseInsensitiveStringHash(const char* s, size_t n) noexcept {
    return TCaseInsensitiveHash<static_cast<int(*)(int)>(std::tolower)>::ComputeHash(s, n);
}

size_t CaseInsensitiveAsciiStringHash(const char* s, size_t n) noexcept {
    return TCaseInsensitiveHash<static_cast<char(*)(char)>(AsciiToLower)>::ComputeHash(s, n);
}

#define Y_DEFINE_STRING_OUT(type)                       \
    template <>                                         \
    void Out<type>(IOutputStream& o, const type& p) {   \
        o.Write(p.data(), p.size());                    \
    }

Y_DEFINE_STRING_OUT(TCaseInsensitiveString);
Y_DEFINE_STRING_OUT(TCaseInsensitiveStringBuf);
Y_DEFINE_STRING_OUT(TCaseInsensitiveAsciiString);
Y_DEFINE_STRING_OUT(TCaseInsensitiveAsciiStringBuf);

#undef Y_DEFINE_STRING_OUT

#define Y_DEFINE_STRING_ESCAPE(type)                            \
    type EscapeC(const type& str) {                             \
        const auto result = EscapeC(str.data(), str.size());    \
        return {result.data(), result.size()};                  \
    }

Y_DEFINE_STRING_ESCAPE(TCaseInsensitiveString);
Y_DEFINE_STRING_ESCAPE(TCaseInsensitiveAsciiString);

#undef Y_DEFINE_STRING_ESCAPE