-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrc32generator.js
75 lines (67 loc) · 1.49 KB
/
crc32generator.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
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
'use strict';
const bufferify = require('./bufferify.js');
const finalize = require('./finalize.js');
var crcTblCache = new Map();
function crcInit(poly) {
if (! crcTblCache.has(poly)) {
let r = [];
for (let i = 0; i < 256; i++) {
let c = i;
for (let j = 0; j < 8; j++) {
//
c = (c & 1 ? 0 : poly) ^ (c >>> 1)
}
r.push(c ^ -16777216);
}
crcTblCache.set(poly, r);
}
return crcTblCache.get(poly);
}
var CRC32gen = function(poly) {
this.poly = poly | 0;
this.crcTbl = crcInit(this.poly);
this.defaultEncoding = 'hex-with-prefix';
this.length = 0;
this.state = 0;
this.finalized = false;
};
CRC32gen.prototype.update = function(b) {
var err;
if (this.finalized) {
throw new Error('Checksum context in finalized state');
}
try {
b = bufferify(b);
} catch(e) {
b = undefined;
err = e;
}
if (err) {
this.finalized = true;
throw err;
}
for (let i = 0; i < b.length; i++) {
this.state = this.crcTbl[(this.state & 255) ^ b[i]] ^ (this.state >>> 8);
}
this.length += b.length;
return this;
};
CRC32gen.prototype.digest = function(encoding) {
if (! this.finalized) {
this.finalized = true;
if (this.state < 0) {
this.state += 4294967296;
}
}
if (encoding === 'default') {
encoding = this.defaultEncoding;
}
return finalize(this.state, 32, encoding);
};
CRC32gen.prototype.final = function(encoding) {
if (this.finalized) {
throw new Error('Checksum context in finalized state');
}
return this.digest(encoding);
};
module.exports = CRC32gen;