-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
browser.js
55 lines (51 loc) 路 1.26 KB
/
browser.js
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
// @flow
import xxhash from 'xxhash-wasm';
let h64, h64Raw;
module.exports.init = (xxhash().then(xxh => {
({h64, h64Raw} = xxh);
}) /*: Promise<void> */);
const encoder = new TextEncoder();
function hashString(s /*: string */) /*: string */ {
return h64(s).padStart(16, '0');
}
module.exports.hashString = hashString;
function hashBuffer(b /*: Uint8Array */) /*: string */ {
return toHex(h64Raw(b));
}
module.exports.hashBuffer = hashBuffer;
class Hash {
/*:: data: Array<Uint8Array>; */
constructor() {
this.data = [];
}
writeString(s /*: string */) {
this.data.push(encoder.encode(s));
}
writeBuffer(b /*: Uint8Array */) {
this.data.push(b);
}
finish() /*: string */ {
return hashBuffer(concatUint8Arrays(this.data));
}
}
module.exports.Hash = Hash;
function concatUint8Arrays(arrays) {
let totalLength = 0;
for (let a of arrays) {
totalLength += a.byteLength;
}
let result = new Uint8Array(totalLength);
let offset = 0;
for (let a of arrays) {
result.set(a, offset);
offset += a.byteLength;
}
return result;
}
function toHex(arr) {
let dataView = new DataView(arr.buffer);
return (
dataView.getUint32(0, true).toString(16).padStart(8, '0') +
dataView.getUint32(4, true).toString(16).padStart(8, '0')
);
}