1 // Copyright 2020 The Pigweed Authors
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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
16 #include <string_view>
18 #include "pw_preprocessor/compiler.h"
20 namespace pw::rpc::internal {
22 // This is the hash function pw_rpc uses internally to calculate IDs from
23 // service and method names.
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;
32 // The length is hashed as if it were the first character.
33 uint32_t hash = string.size();
34 uint32_t coefficient = kHashConstant;
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;
47 } // namespace pw::rpc::internal