• 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_BASE_HASH_H_
18 #define INCLUDE_PERFETTO_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 <typename T,
38             typename std::enable_if<std::is_arithmetic<T>::value>* = nullptr>
Update(T data)39   void Update(T data) {
40     Update(reinterpret_cast<const char*>(&data), sizeof(data));
41   }
42 
43   // Hashes a byte array.
Update(const char * data,size_t size)44   void Update(const char* data, size_t size) {
45     for (size_t i = 0; i < size; i++) {
46       result_ ^= static_cast<uint8_t>(data[i]);
47       result_ *= kFnv1a64Prime;
48     }
49   }
50 
digest()51   uint64_t digest() { return result_; }
52 
53  private:
54   static constexpr uint64_t kFnv1a64OffsetBasis = 0xcbf29ce484222325;
55   static constexpr uint64_t kFnv1a64Prime = 0x100000001b3;
56 
57   uint64_t result_ = kFnv1a64OffsetBasis;
58 };
59 
60 }  // namespace base
61 }  // namespace perfetto
62 
63 #endif  // INCLUDE_PERFETTO_BASE_HASH_H_
64