encodeInto Writes UTF-8 Within Bounds

TextEncoder.encodeInto writes into an existing Uint8Array and reports both read and written counts, stopping at the buffer boundary instead of allocating.

JavascriptData Integrity

Code

javascriptsnippet
15 lines
const shared = new Uint8Array(16);
const encoder = new TextEncoder();
const parts = ['héllo', ' ', 'wörld'];

let written = 0;
let read = 0;
for (const part of parts) {
  // encodeInto 写进已有缓冲区:返回 { read, written },超界即停
  const result = encoder.encodeInto(part, shared.subarray(written));
  written += result.written;
  read += result.read;
}
console.log('bytes written:', written, '| text chars read:', read);
console.log('decoded back:', JSON.stringify(new TextDecoder().decode(shared.subarray(0, written))));
console.log('buffer size 16 >= bytes:', shared.length >= written);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

bytes written: 13 | text chars read: 11
decoded back: "héllo wörld"
buffer size 16 >= bytes: true

The outline of the run

The loop for (const part of parts) is the only repeated construct.

Everything operates on top-level bindings: shared, encoder, parts, written.

Points of care

  • Installation never happens: every API the code calls comes with the platform.

Applying it

The demo output is labeled (bytes written:, decoded back:, buffer size 16 >= bytes:); each label names the call that printed it.

Statements that matter

written += result.written;
read += result.read;

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. Its state lives in module-level bindings: `shared`, `encoder`, `parts`.