xref: /aosp_15_r20/external/perfetto/include/perfetto/tracing/internal/fnv1a.h (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
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_FNV1A_H_
18 #define INCLUDE_PERFETTO_TRACING_INTERNAL_FNV1A_H_
19 
20 #include <cstddef>
21 #include <cstdint>
22 
23 namespace perfetto {
24 namespace internal {
25 
26 // Constexpr functions to compute a 64-bit hash of the input data. The algorithm
27 // used is FNV-1a as it is fast and easy to implement and has relatively few
28 // collisions.
29 //
30 // WARNING: This hash function should not be used for any cryptographic purpose.
31 
32 static constexpr uint64_t kFnv1a64OffsetBasis = 0xcbf29ce484222325;
33 static constexpr uint64_t kFnv1a64Prime = 0x100000001b3;
34 
Fnv1a(const char * s)35 static constexpr inline uint64_t Fnv1a(const char* s) {
36   uint64_t ret = kFnv1a64OffsetBasis;
37   for (; *s; s++) {
38     ret = ret ^ static_cast<uint8_t>(*s);
39     ret *= kFnv1a64Prime;
40   }
41   return ret;
42 }
43 
Fnv1a(const void * data,size_t size)44 static constexpr inline uint64_t Fnv1a(const void* data, size_t size) {
45   uint64_t ret = kFnv1a64OffsetBasis;
46   const uint8_t* s = static_cast<const uint8_t*>(data);
47   for (size_t i = 0; i < size; i++) {
48     ret = ret ^ s[i];
49     ret *= kFnv1a64Prime;
50   }
51   return ret;
52 }
53 
54 }  // namespace internal
55 }  // namespace perfetto
56 
57 #endif  // INCLUDE_PERFETTO_TRACING_INTERNAL_FNV1A_H_
58