fnv_hash.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2021-2022, NVIDIA CORPORATION.
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 #pragma once
18 
19 #include <limits.h>
20 
21 #include <cstdint>
22 #include <numeric>
23 
24 // Implements https://tools.ietf.org/html/draft-eastlake-fnv-17.html
25 // Algorithm is public domain, non-cryptographic strength and no patents or rights to patent.
26 // If input elements are not 8-bit, such a computation does not match
27 // the FNV spec.
28 template <typename It>
29 unsigned long long fowler_noll_vo_fingerprint64(It begin, It end)
30 {
31  static_assert(sizeof(*begin) == 1, "FNV deals with byte-sized (octet) input arrays only");
32  return std::accumulate(
33  begin, end, 14695981039346656037ull, [](const unsigned long long& fingerprint, auto x) {
34  return (fingerprint * 0x100000001b3ull) ^ x;
35  });
36 }
37 
38 // xor-folded fingerprint64 to ensure first bits are affected by other input bits
39 // should give a 1% collision probability within a 10'000 hash set
40 template <typename It>
41 uint32_t fowler_noll_vo_fingerprint64_32(It begin, It end)
42 {
43  unsigned long long fp64 = fowler_noll_vo_fingerprint64(begin, end);
44  return (fp64 & UINT_MAX) ^ (fp64 >> 32);
45 }
uint32_t fowler_noll_vo_fingerprint64_32(It begin, It end)
Definition: fnv_hash.h:41
unsigned long long fowler_noll_vo_fingerprint64(It begin, It end)
Definition: fnv_hash.h:29