forked from sormy/rollup-plugin-smart-asset
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMetroHashWrapper.js
38 lines (31 loc) · 938 Bytes
/
MetroHashWrapper.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
import { safeRequire } from "./safeRequire"
const metrohash = safeRequire("metrohash")
/**
* Wraps MetroHash instance to implement Hash-compliant `digest()` implementation.
*
* MetroHash has `digest()` implementation that always return hex string.
*/
export class MetroHashWrapper {
constructor(size) {
if (!metrohash) {
throw new Error("Unable to find metrohash module")
}
if (size !== 128 && size !== 64) {
throw new Error(`Invalid metrohash size: ${size}`)
}
const MetroHash = size === 128 ? metrohash.MetroHash128 : metrohash.MetroHash64
this.hasher = new MetroHash()
}
update(data) {
this.hasher.update(data)
return this
}
digest(encoding) {
if (encoding === "hex") {
return this.hasher.digest()
}
const hex = this.hasher.digest()
const buffer = Buffer.from(hex, "hex")
return encoding === "buffer" ? buffer : buffer.toString(encoding)
}
}