Skip to content

Commit 158bc83

Browse files
committed
hash: remove repeated remainder calculation
1 parent d308cb0 commit 158bc83

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

hash.js

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -41,27 +41,32 @@ Hash.prototype.update = function (data, enc) {
4141
}
4242

4343
Hash.prototype.digest = function (enc) {
44-
// Suppose the length of the message M, in bits, is l
45-
var l = this._len * 8
44+
var rem = this._len % this._blockSize
4645

47-
// Append the bit 1 to the end of the message
48-
this._block[this._len % this._blockSize] = 0x80
46+
this._block[rem] = 0x80
4947

50-
// and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize
51-
this._block.fill(0, this._len % this._blockSize + 1)
48+
// zero (rem + 1) trailing bits, where (rem + 1) is the smallest
49+
// non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
50+
this._block.fill(0, rem + 1)
5251

53-
if (l % (this._blockSize * 8) >= this._finalSize * 8) {
52+
if (rem >= this._finalSize) {
5453
this._update(this._block)
5554
this._block.fill(0)
5655
}
5756

58-
// to this append the block which is equal to the number l written in binary
59-
if (l <= 0xffffffff) {
60-
this._block.writeUInt32BE(l, this._blockSize - 4)
57+
var bits = this._len * 8
58+
59+
// uint32
60+
if (bits <= 0xffffffff) {
61+
this._block.writeUInt32BE(bits, this._blockSize - 4)
62+
63+
// uint64
6164
} else {
62-
var ll = l & 0xffffffff
63-
this._block.writeUInt32BE((l - ll) / 0x100000000, this._blockSize - 8)
64-
this._block.writeUInt32BE(ll, this._blockSize - 4)
65+
var lowBits = bits & 0xffffffff
66+
var highBits = (bits - lowBits) / 0x100000000
67+
68+
this._block.writeUInt32BE(highBits, this._blockSize - 8)
69+
this._block.writeUInt32BE(lowBits, this._blockSize - 4)
6570
}
6671

6772
this._update(this._block)

0 commit comments

Comments
 (0)