1 /* 2 * Copyright (C) 2021 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 #ifndef INCLUDE_PERFETTO_TRACING_INTERNAL_COMPILE_TIME_HASH_H_ 18 #define INCLUDE_PERFETTO_TRACING_INTERNAL_COMPILE_TIME_HASH_H_ 19 20 #include <stddef.h> 21 #include <stdint.h> 22 23 namespace perfetto { 24 namespace internal { 25 26 // A helper class which computes a 64-bit hash of the input data at compile 27 // time. The algorithm used is FNV-1a as it is fast and easy to implement and 28 // has relatively few collisions. 29 // WARNING: This hash function should not be used for any cryptographic purpose. 30 class CompileTimeHash { 31 public: 32 // Creates an empty hash object CompileTimeHash()33 constexpr inline CompileTimeHash() {} 34 35 // Hashes a byte array. Update(const char * data,size_t size)36 constexpr inline CompileTimeHash Update(const char* data, size_t size) const { 37 return CompileTimeHash(HashRecursively(kFnv1a64OffsetBasis, data, size)); 38 } 39 digest()40 constexpr inline uint64_t digest() const { return result_; } 41 42 private: CompileTimeHash(uint64_t result)43 constexpr inline CompileTimeHash(uint64_t result) : result_(result) {} 44 HashRecursively(uint64_t value,const char * data,size_t size)45 static constexpr inline uint64_t HashRecursively(uint64_t value, 46 const char* data, 47 size_t size) { 48 return !size ? value 49 : HashRecursively( 50 (value ^ static_cast<uint8_t>(*data)) * kFnv1a64Prime, 51 data + 1, size - 1); 52 } 53 54 static constexpr uint64_t kFnv1a64OffsetBasis = 0xcbf29ce484222325; 55 static constexpr uint64_t kFnv1a64Prime = 0x100000001b3; 56 57 uint64_t result_ = kFnv1a64OffsetBasis; 58 }; 59 60 } // namespace internal 61 } // namespace perfetto 62 63 #endif // INCLUDE_PERFETTO_TRACING_INTERNAL_COMPILE_TIME_HASH_H_ 64