-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdeflate-crc32-stream.js
40 lines (39 loc) · 1.01 KB
/
deflate-crc32-stream.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
import { DeflateRaw } from "zlib";
import crc32 from "crc-32";
export default class DeflateCRC32Stream extends DeflateRaw {
constructor(options) {
super(options);
this.checksum = Buffer.allocUnsafe(4);
this.checksum.writeInt32BE(0, 0);
this.rawSize = 0;
this.compressedSize = 0;
}
push(chunk, encoding) {
if (chunk) {
this.compressedSize += chunk.length;
}
return super.push(chunk, encoding);
}
_transform(chunk, encoding, callback) {
if (chunk) {
this.checksum = crc32.buf(chunk, this.checksum) >>> 0;
this.rawSize += chunk.length;
}
super._transform(chunk, encoding, callback);
}
digest(encoding) {
const checksum = Buffer.allocUnsafe(4);
checksum.writeUInt32BE(this.checksum >>> 0, 0);
return encoding ? checksum.toString(encoding) : checksum;
}
hex() {
return this.digest("hex").toUpperCase();
}
size(compressed = false) {
if (compressed) {
return this.compressedSize;
} else {
return this.rawSize;
}
}
}