1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 18:27:35 +00:00

AK: Define a traits helper for case-insensitive StringView hashing

Currently, we define a CaseInsensitiveStringTraits structure for String.
Using this structure for StringView involves allocating a String from
that view, and a second string to convert that intermediate string to
lowercase.

This defines CaseInsensitiveStringViewTraits (and the underlying helper
case_insensitive_string_hash) to avoid allocations.
This commit is contained in:
Timothy Flynn 2022-01-10 11:47:23 -05:00 committed by Linus Groh
parent 7d9b6b41c3
commit 3dccaa39d8
3 changed files with 43 additions and 0 deletions

View file

@ -24,6 +24,27 @@ constexpr u32 string_hash(char const* characters, size_t length, u32 seed = 0)
return hash;
}
constexpr u32 case_insensitive_string_hash(char const* characters, size_t length, u32 seed = 0)
{
// AK/CharacterTypes.h cannot be included from here.
auto to_lowercase = [](char ch) -> u32 {
if (ch >= 'A' && ch <= 'Z')
return static_cast<u32>(ch) + 0x20;
return static_cast<u32>(ch);
};
u32 hash = seed;
for (size_t i = 0; i < length; ++i) {
hash += to_lowercase(characters[i]);
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += hash << 3;
hash ^= hash >> 11;
hash += hash << 15;
return hash;
}
}
using AK::string_hash;