Skip to content

Commit

Permalink
reuse global Uint8Array
Browse files Browse the repository at this point in the history
  • Loading branch information
qti3e committed Apr 16, 2024
1 parent 7a0d2d0 commit 568d62d
Show file tree
Hide file tree
Showing 3 changed files with 441 additions and 8 deletions.
4 changes: 3 additions & 1 deletion bench.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { hash as jsHashV3 } from "./js/v3.ts";
import { hash as jsHashV4 } from "./js/v4.ts";
import { hash as jsHashV5 } from "./js/v5.ts";
import { hash as jsHashV6 } from "./js/v6.ts";
import { hash as jsHashV7 } from "./js/v7.ts";
import { hash as latestHash } from "./js/latest.ts";

// Share the same input buffer across benchmars.
Expand Down Expand Up @@ -55,4 +56,5 @@ bench("Js#04", jsHashV3);
bench("Js#05", jsHashV4);
bench("Js#06", jsHashV5);
bench("Js#07", jsHashV6);
bench("Js#08", latestHash);
bench("Js#08", jsHashV7);
bench("Js#09", latestHash);
26 changes: 19 additions & 7 deletions js/latest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,16 +246,28 @@ function readLittleEndianWordsFull(
}
}

// Pre-allocate and reuse when possible.
const blockWords = new Uint32Array(16) as W16;
let cvStack: Uint32Array | null = null;

function getCvStack(maxDepth: number) {
const depth = Math.max(maxDepth, 10);
const length = depth * 8;
if (cvStack == null || cvStack.length < length) {
cvStack = new Uint32Array(length);
}
return cvStack;
}

export function hash(input: Uint8Array): Uint8Array {
const flags = 0;
const keyWords = IV;
const out = new Uint32Array(8);

// The hasher state.
const blockWords = new Uint32Array(16) as W16;
const maxCvDepth = Math.log2(1 + (input.length >> 10)) + 1;
const cvStack = new Uint32Array(maxCvDepth << 3);
const maxCvDepth = Math.log2(1 + Math.ceil(input.length / 1024)) + 1;
const cvStack = getCvStack(maxCvDepth);
let cvStackPos = 0;

let chunkCounter = 0;
let offset = 0;

Expand Down Expand Up @@ -346,7 +358,7 @@ export function hash(input: Uint8Array): Uint8Array {
0,
blockWords,
0,
blockWords,
out,
0,
true,
0,
Expand Down Expand Up @@ -394,7 +406,7 @@ export function hash(input: Uint8Array): Uint8Array {
0,
cvStack,
cvStackPos,
blockWords,
out,
0,
true,
0,
Expand All @@ -403,5 +415,5 @@ export function hash(input: Uint8Array): Uint8Array {
);
}

return new Uint8Array(blockWords.buffer, 0, 32);
return new Uint8Array(out.buffer, 0, 32);
}

0 comments on commit 568d62d

Please sign in to comment.