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

Function stringToUTF8Array

sqlite-wasm-cos/sqlite3-node.mjs:796–835  ·  view source on GitHub ↗
(str, heap, outIdx, maxBytesToWrite)

Source from the content-addressed store, hash-verified

794 };
795
796 var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
797 // Parameter maxBytesToWrite is not optional. Negative values, 0, null,
798 // undefined and false each don't write out any bytes.
799 if (!(maxBytesToWrite > 0))
800 return 0;
801
802 var startIdx = outIdx;
803 var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
804 for (var i = 0; i < str.length; ++i) {
805 // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description
806 // and https://www.ietf.org/rfc/rfc2279.txt
807 // and https://tools.ietf.org/html/rfc3629
808 var u = str.codePointAt(i);
809 if (u <= 0x7F) {
810 if (outIdx >= endIdx) break;
811 heap[outIdx++] = u;
812 } else if (u <= 0x7FF) {
813 if (outIdx + 1 >= endIdx) break;
814 heap[outIdx++] = 0xC0 | (u >> 6);
815 heap[outIdx++] = 0x80 | (u & 63);
816 } else if (u <= 0xFFFF) {
817 if (outIdx + 2 >= endIdx) break;
818 heap[outIdx++] = 0xE0 | (u >> 12);
819 heap[outIdx++] = 0x80 | ((u >> 6) & 63);
820 heap[outIdx++] = 0x80 | (u & 63);
821 } else {
822 if (outIdx + 3 >= endIdx) break;
823 heap[outIdx++] = 0xF0 | (u >> 18);
824 heap[outIdx++] = 0x80 | ((u >> 12) & 63);
825 heap[outIdx++] = 0x80 | ((u >> 6) & 63);
826 heap[outIdx++] = 0x80 | (u & 63);
827 // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.
828 // We need to manually skip over the second code unit for correct iteration.
829 i++;
830 }
831 }
832 // Null-terminate the pointer to the buffer.
833 heap[outIdx] = 0;
834 return outIdx - startIdx;
835 };
836 /** @type {function(string, boolean=, number=)} */
837 var intArrayFromString = (stringy, dontAddNull, length) => {
838 var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;

Callers 2

intArrayFromStringFunction · 0.70
stringToUTF8Function · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected