File: uint64_hasher.h

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (60 lines) | stat: -rw-r--r-- 1,874 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Based on "v8/src/base/functional.cc".
// See: Thomas Wang, Integer Hash Functions.
// https://gist.github.com/badboy/6267743
// TODO(pkalinnikov): Consider moving the implementation into base/.

#ifndef COMPONENTS_URL_PATTERN_INDEX_UINT64_HASHER_H_
#define COMPONENTS_URL_PATTERN_INDEX_UINT64_HASHER_H_

#include <stddef.h>
#include <stdint.h>

#include <type_traits>

namespace url_pattern_index {

template <typename T>
  requires(sizeof(T) == 4)
T Uint64Hash(uint64_t v) {
  // "64 bit to 32 bit Hash Functions"
  v = ~v + (v << 18);  // v = (v << 18) - v - 1;
  v = v ^ (v >> 31);
  v = v * 21;  // v = (v + (v << 2)) + (v << 4);
  v = v ^ (v >> 11);
  v = v + (v << 6);
  v = v ^ (v >> 22);
  return static_cast<T>(v);
}

template <typename T>
  requires(sizeof(T) == 8)
T Uint64Hash(uint64_t v) {
  // "64 bit Mix Functions"
  v = ~v + (v << 21);  // v = (v << 21) - v - 1;
  v = v ^ (v >> 24);
  v = (v + (v << 3)) + (v << 8);  // v * 265
  v = v ^ (v >> 14);
  v = (v + (v << 2)) + (v << 4);  // v * 21
  v = v ^ (v >> 28);
  v = v + (v << 31);
  return static_cast<T>(v);
}

// Note: A Uint64ToUint64Hasher variant is currently not needed.
// Note: Be careful about a variant that hashes differently in 32-bit vs. 64-bit
// processes (i.e., using |size_t| where the below uses |uint32_t|). Such a
// variant will break compatibility for tables that are built and accessed in
// processes of differing bitness, which is a real-world concern for users of
// this component (see crbug.com/1174797 for details).
class Uint64ToUint32Hasher {
 public:
  uint32_t operator()(uint64_t v) const { return Uint64Hash<uint32_t>(v); }
};

}  // namespace url_pattern_index

#endif  // COMPONENTS_URL_PATTERN_INDEX_UINT64_HASHER_H_