Skip to content

Commit

Permalink
Increase memory size if necessary sha256.js
Browse files Browse the repository at this point in the history
  • Loading branch information
RobinLinus authored Feb 2, 2024
1 parent 05513b4 commit 799a2b6
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions sha256.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
const fileUrl = import.meta.url.replace(/\.js$/, '.wasm');
const sha256_wasm = await (await fetch(fileUrl)).arrayBuffer()

const sha256_wasm_exports = (await WebAssembly.instantiate(sha256_wasm)).instance.exports
const memory = sha256_wasm_exports.memory
const bytesPerPage = 64 * 1024

export function sha256(data) {
const wasm_data = new Uint8Array(sha256_wasm_exports.memory.buffer, 0, data.length)
const wasm_hash = new Uint8Array(sha256_wasm_exports.memory.buffer, data.length, 32)
// Increase the size of the wasm memory if necessary
if(data.length > memory.buffer.byteLength){
const pages = Math.floor((data.length - memory.buffer.byteLength) / bytesPerPage ) + 1
memory.grow(pages)
}

const wasm_data = new Uint8Array(memory.buffer, 0, data.length)
const wasm_hash = new Uint8Array(memory.buffer, data.length, 32)
wasm_data.set(data)
sha256_wasm_exports.SHA256(wasm_data.byteOffset, wasm_hash.byteOffset);
return wasm_hash.slice(0, 32)
Expand Down

0 comments on commit 799a2b6

Please sign in to comment.