Skip to content

Commit 1d9f405

Browse files
committed
Micro-optimize string length computation in UTF16ToString and add string pointer alignment assertions.
1 parent d55dabd commit 1d9f405

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/preamble.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -681,10 +681,15 @@ function lengthBytesUTF8(str) {
681681

682682
var UTF16Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined;
683683
function UTF16ToString(ptr) {
684+
#if ASSERTIONS
685+
assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!');
686+
#endif
684687
var endPtr = ptr;
685688
// TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself.
686689
// Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage.
687-
while ({{{ makeGetValue('endPtr', 0, 'i16') }}}) endPtr += 2;
690+
var idx = endPtr >> 1;
691+
while (HEAP16[idx]) ++idx;
692+
endPtr = idx << 1;
688693

689694
if (endPtr - ptr > 32 && UTF16Decoder) {
690695
return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr));
@@ -715,6 +720,9 @@ function UTF16ToString(ptr) {
715720
// Returns the number of bytes written, EXCLUDING the null terminator.
716721

717722
function stringToUTF16(str, outPtr, maxBytesToWrite) {
723+
#if ASSERTIONS
724+
assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!');
725+
#endif
718726
#if ASSERTIONS
719727
assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
720728
#endif
@@ -746,6 +754,9 @@ function lengthBytesUTF16(str) {
746754
{{{ maybeExport('lengthBytesUTF16') }}}
747755

748756
function UTF32ToString(ptr) {
757+
#if ASSERTIONS
758+
assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!');
759+
#endif
749760
var i = 0;
750761

751762
var str = '';
@@ -778,6 +789,9 @@ function UTF32ToString(ptr) {
778789
// Returns the number of bytes written, EXCLUDING the null terminator.
779790

780791
function stringToUTF32(str, outPtr, maxBytesToWrite) {
792+
#if ASSERTIONS
793+
assert(outPtr % 4 == 0, 'Pointer passed to stringToUTF32 must be aligned to four bytes!');
794+
#endif
781795
#if ASSERTIONS
782796
assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!');
783797
#endif

0 commit comments

Comments
 (0)