| 1 |
import { encoder, uint2String } from "./text-encoders.js"; |
| 2 |
import { trimNull } from "./trim-null.js"; |
| 3 |
|
| 4 |
/** |
| 5 |
* @param {WasmInst} wasm |
| 6 |
* @param {number} ptr |
| 7 |
*/ |
| 8 |
export const freeStringPtr = (wasm, ptr) => { |
| 9 |
wasm.exports.freeStringMem(ptr); |
| 10 |
}; |
| 11 |
|
| 12 |
export const ptr2string = (wasm, stringPtr) => { |
| 13 |
const { buffer } = wasm.wasi.memory; |
| 14 |
const intArray = new Uint8Array(buffer, stringPtr); |
| 15 |
const result = uint2String(intArray); |
| 16 |
return trimNull(result); |
| 17 |
}; |
| 18 |
|
| 19 |
export const string2ptr = (wasm, string) => { |
| 20 |
if (typeof string !== "string") { |
| 21 |
console.error("Expected string but got", typeof string); |
| 22 |
return; |
| 23 |
} |
| 24 |
|
| 25 |
const stringBuf = encoder.encode(string); |
| 26 |
const offset = wasm.exports.allocStringMem(stringBuf.length); |
| 27 |
const { buffer } = wasm.wasi.memory; |
| 28 |
const outBuf = new Uint8Array(buffer, offset, stringBuf.length + 1); |
| 29 |
outBuf.set(stringBuf); |
| 30 |
return offset; |
| 31 |
}; |