Skip to content

Commit d0716b0

Browse files
committed
Optimize loader string encoding routine
1 parent ad009d3 commit d0716b0

File tree

3 files changed

+32
-8
lines changed

3 files changed

+32
-8
lines changed

lib/loader/index.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,10 +141,14 @@ function postInstantiate(extendedExports, instance) {
141141
/** Allocates a new string in the module's memory and returns its pointer. */
142142
function __newString(str) {
143143
if (str == null) return 0;
144-
const length = str.length;
145-
const ptr = __new(length << 1, STRING_ID);
146-
const U16 = new Uint16Array(memory.buffer);
147-
for (var i = 0, p = ptr >>> 1; i < length; ++i) U16[p + i] = str.charCodeAt(i);
144+
const size = str.length << 1;
145+
const ptr = __new(size, STRING_ID);
146+
const buf = new Uint8Array(memory.buffer, ptr, size);
147+
for (let i = 0; i < size; i += 2) {
148+
let c = str.charCodeAt(i >>> 1);
149+
buf[i ] = c;
150+
buf[i + 1] = c >>> 8;
151+
}
148152
return ptr;
149153
}
150154

lib/loader/tests/index.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,22 @@ function test(file) {
5050
assert.strictEqual(exports.strlen(ref), str.length);
5151
}
5252

53+
// should be able to allocate and work with a string containing an isolated lead surrogate
54+
{
55+
let str = "𝄞".substring(0, 1);
56+
let ref = exports.__newString(str);
57+
assert.strictEqual(exports.__getString(ref), str);
58+
assert.strictEqual(exports.strlen(ref), str.length);
59+
}
60+
61+
// should be able to allocate and work with a string containing an isolated trail surrogate
62+
{
63+
let str = "𝄞".substring(1);
64+
let ref = exports.__newString(str);
65+
assert.strictEqual(exports.__getString(ref), str);
66+
assert.strictEqual(exports.strlen(ref), str.length);
67+
}
68+
5369
// should be able to allocate a typed array
5470
{
5571
let arr = [1, 2, 3, 4, 5, 0x80000000 | 0];

lib/loader/umd/index.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -173,13 +173,17 @@ var loader = (function(exports) {
173173

174174
function __newString(str) {
175175
if (str == null) return 0;
176-
const length = str.length;
176+
const size = str.length << 1;
177177

178-
const ptr = __new(length << 1, STRING_ID);
178+
const ptr = __new(size, STRING_ID);
179179

180-
const U16 = new Uint16Array(memory.buffer);
180+
const buf = new Uint8Array(memory.buffer, ptr, size);
181181

182-
for (var i = 0, p = ptr >>> 1; i < length; ++i) U16[p + i] = str.charCodeAt(i);
182+
for (let i = 0; i < size; i += 2) {
183+
let c = str.charCodeAt(i >>> 1);
184+
buf[i] = c;
185+
buf[i + 1] = c >>> 8;
186+
}
183187

184188
return ptr;
185189
}

0 commit comments

Comments
 (0)