MCPcopy Create free account
hub / github.com/Wscats/vscode-explore / encodeUTF8

Function encodeUTF8

contributes/src/vs/base/common/strings.ts:593–642  ·  view source on GitHub ↗
(str: string)

Source from the content-addressed store, hash-verified

591 * Use only in environments which do not offer native conversion methods!
592 */
593export function encodeUTF8(str: string): Uint8Array {
594 const strLen = str.length;
595
596 // See https://en.wikipedia.org/wiki/UTF-8
597
598 // first loop to establish needed buffer size
599 let neededSize = 0;
600 let strOffset = 0;
601 while (strOffset < strLen) {
602 const codePoint = getNextCodePoint(str, strLen, strOffset);
603 strOffset += (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
604
605 if (codePoint < 0x0080) {
606 neededSize += 1;
607 } else if (codePoint < 0x0800) {
608 neededSize += 2;
609 } else if (codePoint < 0x10000) {
610 neededSize += 3;
611 } else {
612 neededSize += 4;
613 }
614 }
615
616 // second loop to actually encode
617 const arr = new Uint8Array(neededSize);
618 strOffset = 0;
619 let arrOffset = 0;
620 while (strOffset < strLen) {
621 const codePoint = getNextCodePoint(str, strLen, strOffset);
622 strOffset += (codePoint >= Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN ? 2 : 1);
623
624 if (codePoint < 0x0080) {
625 arr[arrOffset++] = codePoint;
626 } else if (codePoint < 0x0800) {
627 arr[arrOffset++] = 0b11000000 | ((codePoint & 0b00000000000000000000011111000000) >>> 6);
628 arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
629 } else if (codePoint < 0x10000) {
630 arr[arrOffset++] = 0b11100000 | ((codePoint & 0b00000000000000001111000000000000) >>> 12);
631 arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);
632 arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
633 } else {
634 arr[arrOffset++] = 0b11110000 | ((codePoint & 0b00000000000111000000000000000000) >>> 18);
635 arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000111111000000000000) >>> 12);
636 arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000000000111111000000) >>> 6);
637 arr[arrOffset++] = 0b10000000 | ((codePoint & 0b00000000000000000000000000111111) >>> 0);
638 }
639 }
640
641 return arr;
642}
643
644/**
645 * A manual decoding of a UTF8 string.

Callers

nothing calls this directly

Calls 1

getNextCodePointFunction · 0.85

Tested by

no test coverage detected