41c4c741f4d3c76119687f72f013918af7578c9b
[folly.git] / folly / experimental / wangle / acceptor / DomainNameMisc.h
1 /*
2  *  Copyright (c) 2014, Facebook, Inc.
3  *  All rights reserved.
4  *
5  *  This source code is licensed under the BSD-style license found in the
6  *  LICENSE file in the root directory of this source tree. An additional grant
7  *  of patent rights can be found in the PATENTS file in the same directory.
8  *
9  */
10 #pragma once
11
12 #include <string>
13
14 namespace folly {
15
16 struct dn_char_traits : public std::char_traits<char> {
17   static bool eq(char c1, char c2) {
18     return ::tolower(c1) == ::tolower(c2);
19   }
20
21   static bool ne(char c1, char c2) {
22     return ::tolower(c1) != ::tolower(c2);
23   }
24
25   static bool lt(char c1, char c2) {
26     return ::tolower(c1) < ::tolower(c2);
27   }
28
29   static int compare(const char* s1, const char* s2, size_t n) {
30     while (n--) {
31       if(::tolower(*s1) < ::tolower(*s2) ) {
32         return -1;
33       }
34       if(::tolower(*s1) > ::tolower(*s2) ) {
35         return 1;
36       }
37       ++s1;
38       ++s2;
39     }
40     return 0;
41   }
42
43   static const char* find(const char* s, size_t n, char a) {
44     char la = ::tolower(a);
45     while (n--) {
46       if(::tolower(*s) == la) {
47         return s;
48       } else {
49         ++s;
50       }
51     }
52     return nullptr;
53   }
54 };
55
56 // Case insensitive string
57 typedef std::basic_string<char, dn_char_traits> DNString;
58
59 struct DNStringHash : public std::hash<std::string> {
60   size_t operator()(const DNString& s) const noexcept {
61     size_t h = static_cast<size_t>(0xc70f6907UL);
62     const char* d = s.data();
63     for (size_t i = 0; i < s.length(); ++i) {
64       char a = ::tolower(*d++);
65       h = std::_Hash_impl::hash(&a, sizeof(a), h);
66     }
67     return h;
68   }
69 };
70
71 } // namespace