1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | 'use strict';
|
10 |
|
11 | const {DeflateRaw} = require('zlib');
|
12 |
|
13 | const crc32 = require('crc-32');
|
14 |
|
15 | class DeflateCRC32Stream extends DeflateRaw {
|
16 | constructor(options) {
|
17 | super(options);
|
18 |
|
19 | this.checksum = Buffer.allocUnsafe(4);
|
20 | this.checksum.writeInt32BE(0, 0);
|
21 |
|
22 | this.rawSize = 0;
|
23 | this.compressedSize = 0;
|
24 | }
|
25 |
|
26 | push(chunk, encoding) {
|
27 | if (chunk) {
|
28 | this.compressedSize += chunk.length;
|
29 | }
|
30 |
|
31 | return super.push(chunk, encoding);
|
32 | }
|
33 |
|
34 | _transform(chunk, encoding, callback) {
|
35 | if (chunk) {
|
36 | this.checksum = crc32.buf(chunk, this.checksum) >>> 0;
|
37 | this.rawSize += chunk.length;
|
38 | }
|
39 |
|
40 | super._transform(chunk, encoding, callback)
|
41 | }
|
42 |
|
43 | digest(encoding) {
|
44 | const checksum = Buffer.allocUnsafe(4);
|
45 | checksum.writeUInt32BE(this.checksum >>> 0, 0);
|
46 | return encoding ? checksum.toString(encoding) : checksum;
|
47 | }
|
48 |
|
49 | hex() {
|
50 | return this.digest('hex').toUpperCase();
|
51 | }
|
52 |
|
53 | size(compressed = false) {
|
54 | if (compressed) {
|
55 | return this.compressedSize;
|
56 | } else {
|
57 | return this.rawSize;
|
58 | }
|
59 | }
|
60 | }
|
61 |
|
62 | module.exports = DeflateCRC32Stream;
|