MCPcopy Index your code
hub / github.com/nodejs/node / utf8Bytes

Function utf8Bytes

test/parallel/test-buffer-bytelength.js:138–150  ·  view source on GitHub ↗
(str)

Source from the content-addressed store, hash-verified

136
137 // Independent UTF-8 byte-length oracle with replacement semantics.
138 const utf8Bytes = (str) => {
139 let n = 0;
140 for (let i = 0; i < str.length; i++) {
141 const c = str.charCodeAt(i);
142 if (c < 0x80) n += 1;
143 else if (c < 0x800) n += 2;
144 else if (c >= 0xD800 && c <= 0xDBFF) {
145 const next = str.charCodeAt(i + 1);
146 if (next >= 0xDC00 && next <= 0xDFFF) { n += 4; i++; } else n += 3;
147 } else n += 3; // BMP >= 0x800, incl. unpaired low surrogate
148 }
149 return n;
150 };
151
152 const cases = [
153 'a'.repeat(300) + HI + 'b'.repeat(300), // Unpaired high inside large 2-byte

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected