fix Fletcher-32/64 Checksum

* Operate on words, not bytes
* Add tests
This commit is contained in:
MikeCAT 2022-11-02 21:54:45 +09:00
parent ed8bd34915
commit 5b134d7e9e
5 changed files with 137 additions and 8 deletions

View file

@ -35,10 +35,18 @@ class Fletcher32Checksum extends Operation {
run(input, args) {
let a = 0,
b = 0;
input = new Uint8Array(input);
if (ArrayBuffer.isView(input)) {
input = new DataView(input.buffer, input.byteOffset, input.byteLength);
} else {
input = new DataView(input);
}
for (let i = 0; i < input.length; i++) {
a = (a + input[i]) % 0xffff;
for (let i = 0; i < input.byteLength - 1; i += 2) {
a = (a + input.getUint16(i, true)) % 0xffff;
b = (b + a) % 0xffff;
}
if (input.byteLength % 2 !== 0) {
a = (a + input.getUint8(input.byteLength - 1)) % 0xffff;
b = (b + a) % 0xffff;
}

View file

@ -35,10 +35,22 @@ class Fletcher64Checksum extends Operation {
run(input, args) {
let a = 0,
b = 0;
input = new Uint8Array(input);
if (ArrayBuffer.isView(input)) {
input = new DataView(input.buffer, input.byteOffset, input.byteLength);
} else {
input = new DataView(input);
}
for (let i = 0; i < input.length; i++) {
a = (a + input[i]) % 0xffffffff;
for (let i = 0; i < input.byteLength - 3; i += 4) {
a = (a + input.getUint32(i, true)) % 0xffffffff;
b = (b + a) % 0xffffffff;
}
if (input.byteLength % 4 !== 0) {
let lastValue = 0;
for (let i = 0; i < input.byteLength % 4; i++) {
lastValue = (lastValue << 8) | input.getUint8(input.byteLength - 1 - i);
}
a = (a + lastValue) % 0xffffffff;
b = (b + a) % 0xffffffff;
}