-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhash.js
More file actions
89 lines (69 loc) · 1.86 KB
/
hash.js
File metadata and controls
89 lines (69 loc) · 1.86 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
var fnv = require('fnv-plus')
var siphash = require('siphash/lib/siphash.js')
var stringify = require('fast-json-stable-stringify')
var unsafeFastHash = fnv.fast1a52
var generateKey = siphash.string16_to_key.bind(siphash)
var hashKey = generateKey('chinochinochino!')
function hash(input) {
return siphash.hash_uint(hashKey, stringify(input))
}
function setKey(key) {
var key16bytes
if (typeof key === 'string') {
key16bytes = key.length === 16 ? key : fnv.fast1a64(key)
hashKey = generateKey(key16bytes)
} else {
hashKey = key
}
}
function hash2(a, b) {
return combine(hash(a), hash(b))
}
function hash3(a, b, c) {
return combine(combine(hash(a), hash(b)), hash(c))
}
hash.hash2 = hash2
hash.hash3 = hash3
hash.setKey = setKey
hash.generateKey = generateKey
hash.sequence = sequence
hash.sequence2 = sequence2
hash.sequence3 = sequence3
hash.sequenceHash = sequenceHash
hash.sequenceNext = splitmix32
hash.unsafeFastHash = unsafeFastHash
hash.combine = combine
function combine(a, b) {
return unsafeFastHash(a.toString() + b.toString())
}
// Adapted from https://github.com/bryc/code/blob/master/jshash/PRNGs.md#splitmix32
function splitmix32(a) {
a |= 0
a = (a + 0x9e3779b9) | 0
var t = a ^ (a >>> 16)
// eslint-disable-next-line es5/no-es6-static-methods
t = Math.imul(t, 0x21f0aaad)
t = t ^ (t >>> 15)
// eslint-disable-next-line es5/no-es6-static-methods
t = Math.imul(t, 0x735a2d97)
return (t = t ^ (t >>> 15)) >>> 0
}
// eslint-disable-next-line es5/no-generators
function* sequenceHash(initial) {
var current = initial
yield initial
while (true) {
current = splitmix32(current)
yield current
}
}
function sequence3(a, b) {
return sequenceHash(hash3(a, b))
}
function sequence2(a, b) {
return sequenceHash(hash2(a, b))
}
function sequence(input) {
return sequenceHash(hash(input))
}
module.exports = hash