1 /*
2  * Copyright 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <cinttypes>
20 #include <optional>
21 #include <string_view>
22 
23 #include <ftl/details/hash.h>
24 
25 namespace android::ftl {
26 
27 // Non-cryptographic hash function (namely CityHash64) for strings with at most 64 characters.
28 // Unlike std::hash, which returns std::size_t and is only required to produce the same result
29 // for the same input within a single execution of a program, this hash is stable.
stable_hash(std::string_view view)30 inline std::optional<std::uint64_t> stable_hash(std::string_view view) {
31   const auto length = view.length();
32   if (length <= 16) {
33     return details::hash_length_0_to_16(view.data(), length);
34   }
35   if (length <= 32) {
36     return details::hash_length_17_to_32(view.data(), length);
37   }
38   if (length <= 64) {
39     return details::hash_length_33_to_64(view.data(), length);
40   }
41   return {};
42 }
43 
44 }  // namespace android::ftl
45