MCPcopy Create free account
hub / github.com/GoogleChrome/samples / UTF8ArrayToString

Function UTF8ArrayToString

mkbitmap/mkbitmap.js:3350–3391  ·  view source on GitHub ↗

* Given a pointer 'idx' to a null-terminated UTF8-encoded string in the given * array that contains uint8 values, returns a copy of that string as a * Javascript String object. * heapOrArray is either a regular array, or a JavaScript typed array view. * @param {number} idx *

(heapOrArray, idx, maxBytesToRead)

Source from the content-addressed store, hash-verified

3348 * @return {string}
3349 */
3350 function UTF8ArrayToString(heapOrArray, idx, maxBytesToRead) {
3351 var endIdx = idx + maxBytesToRead;
3352 var endPtr = idx;
3353 // TextDecoder needs to know the byte length in advance, it doesn't stop on
3354 // null terminator by itself. Also, use the length info to avoid running tiny
3355 // strings through TextDecoder, since .subarray() allocates garbage.
3356 // (As a tiny code save trick, compare endPtr against endIdx using a negation,
3357 // so that undefined means Infinity)
3358 while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
3359
3360 if (endPtr - idx > 16 && heapOrArray.buffer && UTF8Decoder) {
3361 return UTF8Decoder.decode(heapOrArray.subarray(idx, endPtr));
3362 }
3363 var str = '';
3364 // If building with TextDecoder, we have already computed the string length
3365 // above, so test loop end condition against that
3366 while (idx < endPtr) {
3367 // For UTF8 byte structure, see:
3368 // http://en.wikipedia.org/wiki/UTF-8#Description
3369 // https://www.ietf.org/rfc/rfc2279.txt
3370 // https://tools.ietf.org/html/rfc3629
3371 var u0 = heapOrArray[idx++];
3372 if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; }
3373 var u1 = heapOrArray[idx++] & 63;
3374 if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; }
3375 var u2 = heapOrArray[idx++] & 63;
3376 if ((u0 & 0xF0) == 0xE0) {
3377 u0 = ((u0 & 15) << 12) | (u1 << 6) | u2;
3378 } else {
3379 if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte ' + ptrToString(u0) + ' encountered when deserializing a UTF-8 string in wasm memory to a JS string!');
3380 u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (heapOrArray[idx++] & 63);
3381 }
3382
3383 if (u0 < 0x10000) {
3384 str += String.fromCharCode(u0);
3385 } else {
3386 var ch = u0 - 0x10000;
3387 str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF));
3388 }
3389 }
3390 return str;
3391 }
3392
3393
3394 /**

Callers 1

mkbitmap.jsFile · 0.70

Calls 2

ptrToStringFunction · 0.85
warnOnceFunction · 0.70

Tested by

no test coverage detected