diff --git a/lib/getHashDigest.ts b/lib/getHashDigest.ts index 49a0966..953a183 100644 --- a/lib/getHashDigest.ts +++ b/lib/getHashDigest.ts @@ -1,4 +1,4 @@ -import type { Hash, BinaryToTextEncoding } from "crypto"; +import type { BinaryToTextEncoding } from "crypto"; const baseEncodeTables = { 26: "abcdefghijklmnopqrstuvwxyz", @@ -95,7 +95,7 @@ export default function getHashDigest( } } - hash = new BatchedHash(createXXHash64() as unknown as Hash); + hash = new BatchedHash(createXXHash64()); } else if (algorithm === "md4") { if (createMd4 === undefined) { createMd4 = require("./hash/md4").create; @@ -105,7 +105,7 @@ export default function getHashDigest( } } - hash = new BatchedHash(createMd4() as unknown as Hash); + hash = new BatchedHash(createMd4()); } else if (algorithm === "native-md4") { if (typeof crypto === "undefined") { crypto = require("crypto"); diff --git a/lib/hash/BatchedHash.ts b/lib/hash/BatchedHash.ts index 5e1516c..ee194ed 100644 --- a/lib/hash/BatchedHash.ts +++ b/lib/hash/BatchedHash.ts @@ -1,12 +1,17 @@ -import type { Hash, Encoding, BinaryToTextEncoding } from "crypto"; +import type { Encoding, BinaryToTextEncoding } from "crypto"; import { MAX_SHORT_STRING } from "./wasm-hash"; +export interface IHashLike { + update(data: string | Buffer, inputEncoding?: Encoding): this; + digest(encoding?: BinaryToTextEncoding): string | Buffer; +} + export class BatchedHash { public string?: string; public encoding?: Encoding; - public readonly hash: Hash; + public readonly hash: IHashLike; - constructor(hash: Hash) { + constructor(hash: IHashLike) { this.string = undefined; this.encoding = undefined; this.hash = hash; diff --git a/lib/hash/wasm-hash.ts b/lib/hash/wasm-hash.ts index d846515..2437d4b 100644 --- a/lib/hash/wasm-hash.ts +++ b/lib/hash/wasm-hash.ts @@ -1,5 +1,7 @@ import { BinaryToTextEncoding } from "crypto"; +import type { IHashLike } from "./BatchedHash"; + /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra @@ -11,7 +13,7 @@ import { BinaryToTextEncoding } from "crypto"; // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64 export const MAX_SHORT_STRING: number = Math.floor((65536 - 64) / 4) & ~3; -export class WasmHash { +export class WasmHash implements IHashLike { /** * @param {WebAssembly.Instance} instance wasm instance * @param {WebAssembly.Instance[]} instancesPool pool of instances @@ -200,15 +202,16 @@ export const create = ( chunkSize: number, digestSize: number ) => { + let result: WasmHash | undefined; if (instancesPool.length > 0) { - const old = instancesPool.pop(); + result = instancesPool.pop(); // old is possibly undefined // protect reset call here - old && old.reset(); + result?.reset(); + } - return old; - } else { + if (result === undefined) { return new WasmHash( new WebAssembly.Instance(wasmModule), instancesPool, @@ -216,4 +219,6 @@ export const create = ( digestSize ); } + + return result; };