Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / pigweed / repo / pw_rpc / public / pw_rpc / internal / hash.h
1 // Copyright 2020 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15
16 #include <string_view>
17
18 #include "pw_preprocessor/compiler.h"
19
20 namespace pw::rpc::internal {
21
22 // This is the hash function pw_rpc uses internally to calculate IDs from
23 // service and method names.
24 //
25 // This is the same hash function that is used in pw_tokenizer, with the maximum
26 // length removed. It is chosen due to its simplicity. The tokenizer code is
27 // duplicated here to avoid unnecessary dependencies between modules.
28 constexpr uint32_t Hash(std::string_view string)
29     PW_NO_SANITIZE("unsigned-integer-overflow") {
30   constexpr uint32_t kHashConstant = 65599;
31
32   // The length is hashed as if it were the first character.
33   uint32_t hash = string.size();
34   uint32_t coefficient = kHashConstant;
35
36   // Hash all of the characters in the string as unsigned ints.
37   // The coefficient calculation is done modulo 0x100000000, so the unsigned
38   // integer overflows are intentional.
39   for (uint8_t ch : string) {
40     hash += coefficient * ch;
41     coefficient *= kHashConstant;
42   }
43
44   return hash;
45 }
46
47 }  // namespace pw::rpc::internal