Run SHA-256 as WebAssembly with JS fallback; note ffmpeg.wasm as deferred
This commit is contained in:
@@ -43,3 +43,32 @@ test('update after digest throws; isHex', () => {
|
||||
assert.ok(Sha256.isHex(ref(Buffer.from('x'))));
|
||||
assert.ok(!Sha256.isHex('ABC'));
|
||||
});
|
||||
|
||||
// ---- WebAssembly engine ----
|
||||
test('wasm engine is available in Node and matches the JS engine and node:crypto', () => {
|
||||
const crypto = require('node:crypto');
|
||||
assert.equal(Sha256.engine(), 'wasm');
|
||||
const sizes = [0, 1, 55, 56, 63, 64, 65, 1000, (1 << 20) - 1, 1 << 20, (1 << 20) + 1, 3_000_001];
|
||||
for (const n of sizes) {
|
||||
const buf = Buffer.alloc(n).map((_, i) => (i * 7 + n) & 255);
|
||||
const want = crypto.createHash('sha256').update(buf).digest('hex');
|
||||
assert.equal(Sha256.create().update(buf).hex(), want, `wasm ${n}`);
|
||||
assert.equal(Sha256.create({ js: true }).update(buf).hex(), want, `js ${n}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('wasm engine hashes streamed odd-sized chunks like one-shot', () => {
|
||||
const crypto = require('node:crypto');
|
||||
const buf = Buffer.alloc(2_500_003).map((_, i) => (i * 13) & 255);
|
||||
const h = Sha256.create();
|
||||
for (let o = 0; o < buf.length; o += 77_777) h.update(buf.subarray(o, o + 77_777));
|
||||
assert.equal(h.hex(), crypto.createHash('sha256').update(buf).digest('hex'));
|
||||
});
|
||||
|
||||
test('falls back to the JS engine when WebAssembly is unavailable', () => {
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const out = execFileSync(process.execPath, ['-e',
|
||||
"delete globalThis.WebAssembly; const S=require('./frontend/sha256.js');" +
|
||||
"console.log(S.engine(), S.hex(new TextEncoder().encode('abc')))"], { cwd: require('node:path').join(__dirname, '..') }).toString().trim();
|
||||
assert.equal(out, 'js ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user