From d0716b0475c7152ea1eaaaab90c0399ce381e3a4 Mon Sep 17 00:00:00 2001 From: dcode Date: Fri, 18 Jun 2021 00:26:20 +0200 Subject: [PATCH] Optimize loader string encoding routine --- lib/loader/index.js | 12 ++++++++---- lib/loader/tests/index.js | 16 ++++++++++++++++ lib/loader/umd/index.js | 12 ++++++++---- 3 files changed, 32 insertions(+), 8 deletions(-) diff --git a/lib/loader/index.js b/lib/loader/index.js index e7b24f74a9..0d170cef61 100644 --- a/lib/loader/index.js +++ b/lib/loader/index.js @@ -141,10 +141,14 @@ function postInstantiate(extendedExports, instance) { /** Allocates a new string in the module's memory and returns its pointer. */ function __newString(str) { if (str == null) return 0; - const length = str.length; - const ptr = __new(length << 1, STRING_ID); - const U16 = new Uint16Array(memory.buffer); - for (var i = 0, p = ptr >>> 1; i < length; ++i) U16[p + i] = str.charCodeAt(i); + const size = str.length << 1; + const ptr = __new(size, STRING_ID); + const buf = new Uint8Array(memory.buffer, ptr, size); + for (let i = 0; i < size; i += 2) { + let c = str.charCodeAt(i >>> 1); + buf[i ] = c; + buf[i + 1] = c >>> 8; + } return ptr; } diff --git a/lib/loader/tests/index.js b/lib/loader/tests/index.js index aac09f91ae..3d29b9df2f 100644 --- a/lib/loader/tests/index.js +++ b/lib/loader/tests/index.js @@ -50,6 +50,22 @@ function test(file) { assert.strictEqual(exports.strlen(ref), str.length); } + // should be able to allocate and work with a string containing an isolated lead surrogate + { + let str = "𝄞".substring(0, 1); + let ref = exports.__newString(str); + assert.strictEqual(exports.__getString(ref), str); + assert.strictEqual(exports.strlen(ref), str.length); + } + + // should be able to allocate and work with a string containing an isolated trail surrogate + { + let str = "𝄞".substring(1); + let ref = exports.__newString(str); + assert.strictEqual(exports.__getString(ref), str); + assert.strictEqual(exports.strlen(ref), str.length); + } + // should be able to allocate a typed array { let arr = [1, 2, 3, 4, 5, 0x80000000 | 0]; diff --git a/lib/loader/umd/index.js b/lib/loader/umd/index.js index 44a6fe11a0..df22d8dd28 100644 --- a/lib/loader/umd/index.js +++ b/lib/loader/umd/index.js @@ -173,13 +173,17 @@ var loader = (function(exports) { function __newString(str) { if (str == null) return 0; - const length = str.length; + const size = str.length << 1; - const ptr = __new(length << 1, STRING_ID); + const ptr = __new(size, STRING_ID); - const U16 = new Uint16Array(memory.buffer); + const buf = new Uint8Array(memory.buffer, ptr, size); - for (var i = 0, p = ptr >>> 1; i < length; ++i) U16[p + i] = str.charCodeAt(i); + for (let i = 0; i < size; i += 2) { + let c = str.charCodeAt(i >>> 1); + buf[i] = c; + buf[i + 1] = c >>> 8; + } return ptr; }