-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (38 loc) · 1.23 KB
/
index.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
/*!
* crc32-js <https://github.com/orvn/crc32-js>
* Apache license
*/
'use strict';
const { crc32Table } = require('./lookups.js');
// Polynomial division implementation (slower, non-default)
function crc32_polynomialDivision(str) {
const polynomial = 0xEDB88320;
let crc = 0xFFFFFFFF;
for (let i = 0, len = str.length; i < len; i++) {
let byte = str.charCodeAt(i);
crc ^= byte;
for (let j = 0; j < 8; j++) {
const mask = -(crc & 1);
crc = (crc >>> 1) ^ (polynomial & mask);
}
}
return (crc ^ 0xFFFFFFFF) >>> 0;
}
// Lookup table implementation (this is the default because it's faster, due to being a precalculated table)
function crc32_lookupTable(str) {
let crc = 0xFFFFFFFF;
for (let i = 0, len = str.length; i < len; i++) {
crc = (crc >>> 8) ^ crc32Table[(crc ^ str.charCodeAt(i)) & 0xFF];
}
return (crc ^ 0xFFFFFFFF) >>> 0;
}
// Export complete crc32 function
module.exports = function crc32(str, usePolynomialDivision = false, hexFormat = true) {
let crc;
if (usePolynomialDivision) {
crc = crc32_polynomialDivision(str);
} else {
crc = crc32_lookupTable(str);
}
return hexFormat ? crc.toString(16).padStart(8, '0') : crc.toString(10);
}