• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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_EXT_BASE_HASH_H_
18 #define INCLUDE_PERFETTO_EXT_BASE_HASH_H_
19 
20 #include <stddef.h>
21 #include <stdint.h>
22 #include <type_traits>
23 
24 namespace perfetto {
25 namespace base {
26 
27 // A helper class which computes a 64-bit hash of the input data.
28 // The algorithm used is FNV-1a as it is fast and easy to implement and has
29 // relatively few collisions.
30 // WARNING: This hash function should not be used for any cryptographic purpose.
31 class Hash {
32  public:
33   // Creates an empty hash object
Hash()34   Hash() {}
35 
36   // Hashes a numeric value.
37   template <
38       typename T,
39       typename std::enable_if<std::is_arithmetic<T>::value, bool>::type = true>
Update(T data)40   void Update(T data) {
41     Update(reinterpret_cast<const char*>(&data), sizeof(data));
42   }
43 
44   // Hashes a byte array.
Update(const char * data,size_t size)45   void Update(const char* data, size_t size) {
46     for (size_t i = 0; i < size; i++) {
47       result_ ^= static_cast<uint8_t>(data[i]);
48       result_ *= kFnv1a64Prime;
49     }
50   }
51 
digest()52   uint64_t digest() { return result_; }
53 
54  private:
55   static constexpr uint64_t kFnv1a64OffsetBasis = 0xcbf29ce484222325;
56   static constexpr uint64_t kFnv1a64Prime = 0x100000001b3;
57 
58   uint64_t result_ = kFnv1a64OffsetBasis;
59 };
60 
61 }  // namespace base
62 }  // namespace perfetto
63 
64 #endif  // INCLUDE_PERFETTO_EXT_BASE_HASH_H_
65