forked from reklatsmasters/webassembly-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
33 lines (25 loc) · 798 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const wasm = require('webassembly')
const assert = require('assert')
wasm.load('crc32.wasm').then(main).catch(e => console.error(e))
// wrapper
const _crc32 = ({crc32, _malloc, _free}, memory) => (buf, crc = 0) => {
if (!Buffer.isBuffer(buf)) {
buf = Buffer.from(buf)
}
// allocate internal memory for Buffer buf
// return pointer (int value) to free memory
const mem = _malloc(buf.length)
// fill memory, copy data
memory.U8.set(buf, mem)
// call wasm function directly
const result = crc32(mem, buf.length, crc)
// free memory
_free(mem)
return result
}
function main({exports, memory}) {
const crc32 = _crc32(exports, memory)
const crc = crc32('123456789') >>> 0
assert.strictEqual(crc, 0xcbf43926)
console.log(`crc32('123456789') =`, crc)
}