forked from kblauhut/bloomit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
198 lines (179 loc) · 6.47 KB
/
utils.ts
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
/* file : utils.ts
MIT License
Copyright (c) 2017-2020 Thomas Minier & Arnaud Grall
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use strict';
import XXH from 'xxhashjs';
/**
* Utilitaries functions
* @namespace Utils
* @private
*/
/* JSDOC typedef */
/**
* @typedef {TwoHashes} Two hashes of the same value, as computed by {@link hashTwice}.
* @property {number} first - The result of the first hashing function applied to a value
* @property {number} second - The result of the second hashing function applied to a value
* @memberof Utils
*/
interface TwoHashes {
first: number;
second: number;
}
export type HashableInput = string | ArrayBuffer | Buffer;
export type Bit = 0 | 1;
/**
* Hash a value into two 32-bit values (in hex or integer format)
* @param value - The value to hash
* @param seed the seed used for hashing
* @return The results of the hash functions applied to the value (in hex or integer)
* @memberof Utils
* @author Arnaud Grall & Thomas Minier
*/
export function hashTwice(
value: HashableInput,
seed: number,
): TwoHashes {
const f = XXH.h32(value, seed + 1);
const l = XXH.h32(value, seed + 2);
return {
first: f.toNumber(),
second: l.toNumber(),
};
}
/**
* Apply Double Hashing to produce a n-hash
*
* This implementation used directly the value produced by the two hash functions instead of the functions themselves.
* @see {@link http://citeseer.ist.psu.edu/viewdoc/download;jsessionid=4060353E67A356EF9528D2C57C064F5A?doi=10.1.1.152.579&rep=rep1&type=pdf} for more details about double hashing.
* @param n - The indice of the hash function we want to produce
* @param hashA - The result of the first hash function applied to a value.
* @param hashB - The result of the second hash function applied to a value.
* @param size - The size of the datastructures associated to the hash context (ex: the size of a Bloom Filter)
* @return The result of hash_n applied to a value.
* @memberof Utils
* @author Thomas Minier
*/
export function doubleHashing(
n: number,
hashA: number,
hashB: number,
size: number
): number {
// Cubic term avoids increased-probability-of-collision issue, see
// http://peterd.org/pcd-diss.pdf s.6.5.4
return Math.abs((hashA + n*hashB + Math.floor((n**3 - n)/6)) % size);
}
/**
* Generate a set of distinct indexes on interval [0, size) using the double hashing technique
* @param element - The element to hash
* @param size - the range on which we can generate an index [0, size) = size
* @param number - The number of indexes desired
* @param seed - The seed used
* @param maxIterations - throw if we exceed this without finding a result of the
* requested size; avoids a hard busy loop in the event of an algorithm failure. Defaults
* to size*100
* @return A array of indexes
* @author Arnaud Grall
*/
export function getDistinctIndices(
element: HashableInput,
size: number,
number: number,
seed: number = 0,
maxIterations: number = size * 100
): Array<number> {
let {first, second} = hashTwice(element, seed);
let index, i = 1;
const indices: Array<number> = [];
// Implements enhanced double hashing algorithm from
// http://peterd.org/pcd-diss.pdf s.6.5.4
while(indices.length < number) {
index = first % size;
if(!indices.includes(index)) {
indices.push(index);
}
first = (first + second) % size;
second = (second + i) % size;
i++;
if(i > size) {
// Enhanced double hashing stops cycles of length less than `size` in the case where
// size is coprime with the second hash. But you still get cycles of length `size`.
// So if we reach there and haven't finished, append a prime to the input and
// rehash.
seed++;
({first, second} = hashTwice(element, seed));
}
if(maxIterations && i > maxIterations) {
throw new Error('max iterations exceeded');
}
}
return indices;
}
/**
* Return the amount of bytes needed to fit the input bits
* @return Length of Unit8Array to use
* @param bitCount - amount of bits the filter uses
*/
export function getUint8ArrayLength(bitCount: number): number {
const remainder = bitCount % 8;
const bitFill = 8 - remainder;
return (bitCount + bitFill) / 8;
}
/**
* Return the index of the byte to be edited within the array
* @return Array index of the byte to be edited
* @param bitIndex - index of the bit to be set
* @author Kolja Blauhut
*/
export function getByteIndexInArray(bitIndex: number): number {
return Math.floor(bitIndex / 8);
}
/**
* Return the index of the bit in the byte to edit
* @return Array index of the byte to be edited
* @param bitIndex - index of the bit to be set
* @author Kolja Blauhut
*/
export function getBitIndex(bitIndex: number): number {
return bitIndex % 8;
}
/**
* Set a certain bit in the byte to 1
* @return Edited byte
* @param indexInByte - Index of the bit in the byte to be set
* @param byte - Current byte
* @author Kolja Blauhut
*/
export function setBitInByte(indexInByte: number, byte: number): number {
const byteOR = 1 << indexInByte;
return byte | byteOR;
}
/**
* Returns a bit at a given index
* @return Bit 1 | 0
* @param array - Uint8Array containing bloom filter
* @param bitIndex - Index of bit to read
* @author Kolja Blauhut
*/
export function getBitAtIndex(array: Uint8Array, bitIndex: number): Bit {
const byte = array[getByteIndexInArray(bitIndex)];
const indexInByte = getBitIndex(bitIndex);
const byteAND = setBitInByte(indexInByte, 0);
return ((byte & byteAND) >> indexInByte) as Bit;
}