UNPKG

@worker-tools/deno-kv-storage

Version:

An implementation of the StorageArea (1,2,3) interface for Deno with an extensible system for supporting various database backends.

88 lines 2.67 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getStr = exports.setArr = exports.setStr = void 0; const error_js_1 = __importDefault(require("./error.js")); // Move string to C function setStr(wasm, str, closure) { const bytes = new TextEncoder().encode(str); const ptr = wasm.malloc(bytes.length + 1); if (ptr === 0) { throw new error_js_1.default("Out of memory."); } const mem = new Uint8Array(wasm.memory.buffer, ptr, bytes.length + 1); mem.set(bytes); mem[bytes.length] = 0; // \0 terminator try { closure(ptr); wasm.free(ptr); } catch (error) { wasm.free(ptr); throw error; } } exports.setStr = setStr; // Move Uint8Array to C function setArr(wasm, arr, closure) { const ptr = wasm.malloc(arr.length); if (ptr === 0) { throw new error_js_1.default("Out of memory."); } const mem = new Uint8Array(wasm.memory.buffer, ptr, arr.length); mem.set(arr); try { closure(ptr); wasm.free(ptr); } catch (error) { wasm.free(ptr); throw error; } } exports.setArr = setArr; // Read string from C function getStr(wasm, ptr) { const len = wasm.str_len(ptr); const bytes = new Uint8Array(wasm.memory.buffer, ptr, len); if (len > 16) { return new TextDecoder().decode(bytes); } else { // This optimization is lifted from EMSCRIPTEN's glue code let str = ""; let idx = 0; while (idx < len) { let u0 = bytes[idx++]; if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; } const u1 = bytes[idx++] & 63; if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; } const u2 = bytes[idx++] & 63; if ((u0 & 0xF0) == 0xE0) { u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; } else { // cut warning u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (bytes[idx++] & 63); } if (u0 < 0x10000) { str += String.fromCharCode(u0); } else { const ch = u0 - 0x10000; str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); } } return str; } } exports.getStr = getStr; //# sourceMappingURL=wasm.js.map