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 <cstdint> 17 #include <string_view> 18 19 #include "pw_preprocessor/compiler.h" 20 21 namespace pw::rpc::internal { 22 23 // This is the hash function pw_rpc uses internally to calculate IDs from 24 // service and method names. 25 // 26 // This is the same hash function that is used in pw_tokenizer, with the maximum 27 // length removed. It is chosen due to its simplicity. The tokenizer code is 28 // duplicated here to avoid unnecessary dependencies between modules. Hash(std::string_view string)29constexpr uint32_t Hash(std::string_view string) 30 PW_NO_SANITIZE("unsigned-integer-overflow") { 31 constexpr uint32_t kHashConstant = 65599; 32 33 // The length is hashed as if it were the first character. 34 uint32_t hash = static_cast<uint32_t>(string.size()); 35 uint32_t coefficient = kHashConstant; 36 37 // Hash all of the characters in the string as unsigned ints. 38 // The coefficient calculation is done modulo 0x100000000, so the unsigned 39 // integer overflows are intentional. 40 for (char ch : string) { 41 hash += coefficient * static_cast<uint8_t>(ch); 42 coefficient *= kHashConstant; 43 } 44 45 return hash; 46 } 47 48 } // namespace pw::rpc::internal 49