-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbsdsum.js
64 lines (57 loc) · 1.35 KB
/
bsdsum.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
'use strict';
const bufferify = require('./bufferify.js');
const finalize = require('./finalize.js');
var BsdSum = function(algorithm) {
if (! algorithm) {
algorithm = BsdSum.algorithms[0];
}
if (BsdSum.algorithms.indexOf(algorithm) < 0) {
throw new Error('Unsupported algorithm');
}
this.algorithm = algorithm;
this.defaultEncoding = 'number';
this.length = 0;
this.block = null;
this.state = 0;
this.finalized = false;
};
BsdSum.algorithms = [ 'bsdsum', 'sum-bsd' ];
BsdSum.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.state >> 1) + ((this.state & 1) << 15) + b[i]) & 0xffff;
}
this.length += b.length;
return this;
};
BsdSum.prototype.digest = function(encoding) {
if (! this.finalized) {
this.block = Math.ceil(this.length / 1024);
this.finalized = true;
Object.freeze(this);
}
if (encoding === 'default') {
encoding = this.defaultEncoding;
}
return finalize(this.state, 16, encoding);
};
BsdSum.prototype.final = function(encoding) {
if (this.finalized) {
throw new Error('Checksum context in finalized state');
}
return this.digest(encoding);
}
module.exports = BsdSum;