MCPcopy Create free account
hub / github.com/Snapchat/Valdi / encodeUtf8

Function encodeUtf8

src/valdi_modules/src/valdi/coreutils/web/UnicodeNative.ts:80–112  ·  view source on GitHub ↗
(str: string)

Source from the content-addressed store, hash-verified

78 if (cp >= 0 && cp <= 0x10ffff && !(cp >= 0xd800 && cp <= 0xdfff)) return cp >>> 0;
79 return REPLACEMENT;
80}
81
82/* ===== UTF-8 ===== */
83
84function encodeUtf8(str: string): Uint8Array {
85 if (typeof TextEncoder !== 'undefined') {
86 return new TextEncoder().encode(str);
87 }
88 // Manual fallback (sufficient for BMP + astral)
89 const cps = toCodePoints(str);
90 // worst case 4 bytes/code point
91 const out: number[] = [];
92 for (const cp of cps) {
93 if (cp <= 0x7f) {
94 out.push(cp);
95 } else if (cp <= 0x7ff) {
96 out.push(0b11000000 | (cp >> 6), 0b10000000 | (cp & 0b00111111));
97 } else if (cp <= 0xffff) {
98 out.push(0b11100000 | (cp >> 12), 0b10000000 | ((cp >> 6) & 0b00111111), 0b10000000 | (cp & 0b00111111));
99 } else {
100 out.push(
101 0b11110000 | (cp >> 18),
102 0b10000000 | ((cp >> 12) & 0b00111111),
103 0b10000000 | ((cp >> 6) & 0b00111111),
104 0b10000000 | (cp & 0b00111111),
105 );
106 }
107 }
108 return Uint8Array.from(out);
109}
110
111function decodeUtf8(bytes: Uint8Array): string {
112 if (typeof TextDecoder !== 'undefined') {
113 try {
114 return new TextDecoder('utf-8', { fatal: false }).decode(bytes);
115 } catch {

Callers 1

encodeStringFunction · 0.85

Calls 4

toCodePointsFunction · 0.85
encodeMethod · 0.65
pushMethod · 0.45
fromMethod · 0.45

Tested by

no test coverage detected