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

Function stringToUTF8Array

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

Source from the content-addressed store, hash-verified

937 };
938
939 var stringToUTF8Array = (str, heap, outIdx, maxBytesToWrite) => {
940 // Parameter maxBytesToWrite is not optional. Negative values, 0, null,
941 // undefined and false each don't write out any bytes.
942 if (!(maxBytesToWrite > 0))
943 return 0;
944
945 var startIdx = outIdx;
946 var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator.
947 for (var i = 0; i < str.length; ++i) {
948 // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description
949 // and https://www.ietf.org/rfc/rfc2279.txt
950 // and https://tools.ietf.org/html/rfc3629
951 var u = str.codePointAt(i);
952 if (u <= 0x7F) {
953 if (outIdx >= endIdx) break;
954 heap[outIdx++] = u;
955 } else if (u <= 0x7FF) {
956 if (outIdx + 1 >= endIdx) break;
957 heap[outIdx++] = 0xC0 | (u >> 6);
958 heap[outIdx++] = 0x80 | (u & 63);
959 } else if (u <= 0xFFFF) {
960 if (outIdx + 2 >= endIdx) break;
961 heap[outIdx++] = 0xE0 | (u >> 12);
962 heap[outIdx++] = 0x80 | ((u >> 6) & 63);
963 heap[outIdx++] = 0x80 | (u & 63);
964 } else {
965 if (outIdx + 3 >= endIdx) break;
966 heap[outIdx++] = 0xF0 | (u >> 18);
967 heap[outIdx++] = 0x80 | ((u >> 12) & 63);
968 heap[outIdx++] = 0x80 | ((u >> 6) & 63);
969 heap[outIdx++] = 0x80 | (u & 63);
970 // Gotcha: if codePoint is over 0xFFFF, it is represented as a surrogate pair in UTF-16.
971 // We need to manually skip over the second code unit for correct iteration.
972 i++;
973 }
974 }
975 // Null-terminate the pointer to the buffer.
976 heap[outIdx] = 0;
977 return outIdx - startIdx;
978 };
979 /** @type {function(string, boolean=, number=)} */
980 var intArrayFromString = (stringy, dontAddNull, length) => {
981 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