This repository was archived by the owner on Dec 17, 2025. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathBatchedHash.ts
More file actions
83 lines (74 loc) · 2.2 KB
/
BatchedHash.ts
File metadata and controls
83 lines (74 loc) · 2.2 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
import type { Hash, Encoding, BinaryToTextEncoding } from "crypto";
import { MAX_SHORT_STRING } from "./wasm-hash";
export default class BatchedHash {
public string?: string;
public encoding?: Encoding;
public readonly hash: Hash;
constructor(hash: Hash) {
this.string = undefined;
this.encoding = undefined;
this.hash = hash;
}
/**
* Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
* @param {string|Buffer} data data
* @param {string=} inputEncoding data encoding
* @returns {this} updated hash
*/
update(data: string | Buffer, inputEncoding?: Encoding): this {
if (this.string !== undefined) {
if (
typeof data === "string" &&
inputEncoding === this.encoding &&
this.string.length + data.length < MAX_SHORT_STRING
) {
this.string += data;
return this;
}
if (this.encoding !== undefined) {
this.hash.update(this.string, this.encoding);
} else {
this.hash.update(this.string);
}
this.string = undefined;
}
if (typeof data === "string") {
if (
data.length < MAX_SHORT_STRING &&
// base64 encoding is not valid since it may contain padding chars
(!inputEncoding || !inputEncoding.startsWith("ba"))
) {
this.string = data;
this.encoding = inputEncoding;
} else {
if (inputEncoding !== undefined) {
this.hash.update(data, inputEncoding);
} else {
this.hash.update(data);
}
}
} else {
this.hash.update(data);
}
return this;
}
/**
* Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
* @param {string=} encoding encoding of the return value
* @returns {string|Buffer} digest
*/
digest(encoding?: BinaryToTextEncoding): string | Buffer {
if (this.string !== undefined) {
if (this.encoding !== undefined) {
this.hash.update(this.string, this.encoding);
} else {
this.hash.update(this.string);
}
}
if (encoding !== undefined) {
return this.hash.digest(encoding);
} else {
return this.hash.digest();
}
}
}