Skip to content

Commit

Permalink
optimize setLanguage, setScript, shapeWithTrace
Browse files Browse the repository at this point in the history
Nodejs text encoding/decoding is slow: nodejs/node#39879

It's faster to encode in JS. Browsers don't show much difference
with this change.
  • Loading branch information
chearon committed May 19, 2023
1 parent d4bdb23 commit 2563129
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions hbjs.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,14 +238,15 @@ function hbjs(instance) {
};
}

var utf8Encoder = new TextEncoder("utf8");
function createCString(text) {
var bytes = utf8Encoder.encode(text);
var ptr = exports.malloc(bytes.byteLength);
heapu8.set(bytes, ptr);
function createAsciiString(text) {
var ptr = exports.malloc(text.length + 1);
for (let i = 0; i < text.length; ++i) {
heapu8[ptr + i] = text.charCodeAt(i);
}
heapu8[ptr + text.length] = 0;
return {
ptr: ptr,
length: bytes.byteLength,
length: text.length,
free: function () { exports.free(ptr); }
};
}
Expand Down Expand Up @@ -320,7 +321,7 @@ function hbjs(instance) {
* @param {string} language: The buffer language
*/
setLanguage: function (language) {
var str = createCString(language);
var str = createAsciiString(language);
exports.hb_buffer_set_language(ptr, exports.hb_language_from_string(str.ptr,-1));
str.free();
},
Expand All @@ -329,7 +330,7 @@ function hbjs(instance) {
* @param {string} script: The buffer script
*/
setScript: function (script) {
var str = createCString(script);
var str = createAsciiString(script);
exports.hb_buffer_set_script(ptr, exports.hb_script_from_string(str.ptr,-1));
str.free();
},
Expand Down Expand Up @@ -421,7 +422,7 @@ function hbjs(instance) {
function shapeWithTrace(font, buffer, features, stop_at, stop_phase) {
var bufLen = 1024 * 1024;
var traceBuffer = exports.malloc(bufLen);
var featurestr = createCString(features);
var featurestr = createAsciiString(features);
var traceLen = exports.hbjs_shape_with_trace(font.ptr, buffer.ptr, featurestr.ptr, stop_at, stop_phase, traceBuffer, bufLen);
featurestr.free();
var trace = utf8Decoder.decode(heapu8.subarray(traceBuffer, traceBuffer + traceLen - 1));
Expand Down

0 comments on commit 2563129

Please sign in to comment.