Skip to content

Port Node's normalizeEncoding() for buffer.transcode and StringDecoder - #46006

Closed
robobun wants to merge 2 commits into
mainfrom
robobun/6307c270/transcode-encoding-argument
Closed

robobun wants to merge 2 commits into
mainfrom
robobun/6307c270/transcode-encoding-argument

Conversation

@robobun

@robobun robobun commented Oct 19, 2026

Copy link
Copy Markdown
Collaborator

Problem

  • No user reported this. It is a difference from Node v26.3.0.
  • buffer.transcode() converts every encoding that is not undefined or null to a string (value.toWTFString(), src/jsc/modules/NodeBufferModule.cpp:167). So transcode(buf, "utf8", ["latin1"]) returns a Buffer. Node throws Unable to transcode Buffer [U_ILLEGAL_ARGUMENT_ERROR].
  • new StringDecoder() takes strings only: new StringDecoder(new String("latin1")) throws ERR_UNKNOWN_ENCODING. Node uses one function for both.

Fix

  • normalizeEncoding() in JSBufferEncodingType.h is that Node function for a JSValue. transcode() and the StringDecoder constructor call it, one commit each.
  • As in Node, transcode() ends a string that is not a name at its first NUL. It rejects an unsupported encoding before it reads the source again.
  • Verified: test/js/node/buffer.test.js runs 136 values under Node and Bun and compares the output.
  • Self-reviewed: 24 concerns raised, 20 addressed. Notes list the other 4.

Background

  • Node's normalizeEncoding() converts a value that is not a string only when its length is 3 to 9. So new String("latin1") is a name and ["latin1"] is not.
  • Node's native parser, which transcode() uses next, reads a C string.
  • Considered a strings-only gate (rejects new String("latin1")) and Node's JS wrapper (3 to 5 JS calls per call).

Downsides

  • transcode() accepts less: 30 of 139 values now throw. StringDecoder accepts more: 37 of 139.
  • new StringDecoder(name) runs 5 more instructions (711 to 716), and transcode() 33 more per "" encoding. Release text grows by 2,560 bytes.
  • If user code empties the source during the call, Node aborts for 10 of 16 encoding pairs. Bun returns an empty Buffer.
Notes

Repro

import { transcode } from "node:buffer";
import { StringDecoder } from "node:string_decoder";
let calls = 0;
const enc = { toString() { calls++; return "latin1"; } };
const show = f => { try { return JSON.stringify(f()); } catch (e) { return "throws " + e.code; } };
console.log(show(() => [...transcode(Buffer.from("a"), "utf8", enc)]), "toString calls:", calls);
console.log(show(() => [...transcode(Buffer.from("a"), "utf8", ["latin1"])]));
console.log(show(() => new StringDecoder(new String("latin1")).encoding));
console.log(show(() => new StringDecoder("").encoding));
line Node v26.3.0 and this PR Bun 1.4.2 and main
1 throws U_ILLEGAL_ARGUMENT_ERROR toString calls: 0 [97] toString calls: 1
2 throws U_ILLEGAL_ARGUMENT_ERROR [97]
3 "latin1" throws ERR_UNKNOWN_ENCODING
4 "utf8" throws ERR_UNKNOWN_ENCODING

Node's rule (v26.3.0)

  • normalizeEncoding: undefined, null and "" are utf8. slowCases does switch (enc.length). Only the cases 3 to 9 call StringPrototypeToLowerCase(enc), once, and compare the result with the names of that length.
  • transcode does normalizeEncoding(enc) || enc for each encoding, then calls the native function. ParseEncoding gives the default for a value that is not a string, which Transcode rejects. It reads a string through Utf8Value as a C string, so "latin1\0xyz" is latin1.
  • StringDecoder takes the result of normalizeEncoding(encoding) and throws ERR_UNKNOWN_ENCODING when there is none.

The code

  • normalizeEncoding() is inline: undefined and null are utf8, then the existing string parser runs (parseEnumeration<BufferEncodingType>), then "" is utf8. Only a value that is not a string goes to the new function normalizeEncodingOfNonString(). So a call with a name takes the same path as before. The header gets #pragma once because it now has a definition.
  • jsBufferTranscode keeps what only transcode() does: parseTranscodeEncodingBeforeNul(), the map to its four encodings, and the order of the checks. Its private name table and the lowercase copy of each name are deleted.
  • createDecoder changes one line. The path that builds ERR_UNKNOWN_ENCODING is not changed.

Behavior change

Probe: 139 values, each as fromEnc, as toEnc, and as the StringDecoder encoding, compared with Node v26.3.0.

main differs from Node this PR differs from Node
transcode() 48 values 2 values, only the wording of an engine TypeError
new StringDecoder() 52 values 3 values, see below
  • transcode(): 30 values that returned a Buffer now throw U_ILLEGAL_ARGUMENT_ERROR. They are { toString }, { [Symbol.toPrimitive] }, [], [""], ["latin1"], new String(""), an object with a length that is not 3 to 9, and an object whose string is not a name of its length.
  • transcode(): 9 strings with a NUL that threw now return a Buffer, for example "latin1\0" and "UTF8\0xyz". The cut applies to a string primitive only: new String("latin1\0") stays rejected, as in Node.
  • transcode(): Symbol(), Object(Symbol()) and Object.create(null) now throw U_ILLEGAL_ARGUMENT_ERROR. They threw a TypeError. A length getter now runs, and an error from it propagates.
  • StringDecoder, readable.setEncoding() and the other callers of the constructor: 37 values that threw ERR_UNKNOWN_ENCODING now give a decoder. They are "", a String object, a Buffer that holds a name, and an object whose length and string are those of a name. No value goes the other way.
  • StringDecoder still differs for Symbol(), Object(Symbol()) and Object.create(null): Bun throws a TypeError while it builds the message of ERR_UNKNOWN_ENCODING. The text of that message also differs for 17 more values (Node formats the value with %s). This PR does not touch that path. node errors: render %s codes like util.format and keep the sign of a received -0 #43087 changes it.
  • Unchanged: every name in every letter case, undefined, null, and for transcode() also "", "hex", "base64", "buffer", numbers, booleans, new String("latin1"), Buffer.from("latin1").

User code that changes the source

A length getter or a toString() of an encoding can detach or resize the source. Both encodings resolve before the pointer and the length are read, as before. Two results changed to match Node:

  • An encoding that is not supported wins over a source that the user code emptied. Main returned an empty Buffer.
  • With an emptied source and two supported encodings, Node's simdutf paths fail with U_INVALID_CHAR_FOUND (src/node_i18n.cc): latin1, ascii or utf8 to ucs2, and ucs2 to utf8. Bun now does the same. ucs2 to latin1 or ascii gives an empty Buffer in both. For the other 10 pairs Node aborts the process (exit 134) and Bun returns an empty Buffer.

Measurements (release builds of main 017b243 with and without this change, linux-x64)

  • Instructions per transcode() call, 1-byte source, gdb single-step of jsBufferTranscode with its callees: omitted 1374 -> 1354, null/null 1376 -> 1362, utf8/utf8 1672 -> 1530, UTF8/UTF8 1836 -> 1530, ASCII/ASCII 1973 -> 1315, utf8/latin1 1690 -> 1428. Each of the 9 names in lower and upper case is below main (142 to 658 fewer). ""/"" is above main: 1428 -> 1494.
  • Instructions per new StringDecoder(x), gdb single-step of the constructor: omitted 628 -> 628, each of 12 names +5 (for example utf8 711 -> 716).
  • mi_malloc per call (gdb hit counts, N=200 against 1200): transcode utf8/latin1 2.156 -> 2.156, UTF8/LATIN1 4.156 -> 2.156, new StringDecoder("utf8") 0.14 -> 0.14. convertToASCIILowercase calls per 1000 transcode calls: 2000 -> 0.
  • Release binary text: +2,560 bytes (size, 106,738,870 against 106,741,430). By nm -S: the transcode symbols go from 3,908 to 5,164 bytes, normalizeEncodingOfNonString is 908 bytes, createDecoder goes from 1,220 to 1,412 bytes. 0 new host functions. bloaty is not installed.
  • Changed path, instructions per transcode() call: a rejected name "bogus" 4620 -> 4412, a rejected 1000-character string 12544 -> 4594, {} 4882 -> 4448, new String("latin1") 2212 -> 2171. [] goes from 1866 to 4466 because it now throws. toWTFStringSlowCase calls per 1000 calls with {}: 1000 -> 0.

Tests

  • test/js/node/normalize-encoding-fixture.js prints what transcode() (both positions) and StringDecoder do with each value, and the order in which transcode() reads its arguments. buffer.test.js runs it under nodeExe() and bunExe() and compares the output, as the fill() fixture in the same file does. With Node v26.3.0: main differs on 76 of 136 lines, this PR on 0.
  • The other new tests hold a short set of the same rows with the whole error object, so the rule is covered where there is no Node.js. The tests for a source that user code empties cannot run under Node, because Node aborts for 10 of the 16 pairs. For those, each of the 200 combinations ran in its own Node process: the 120 that do not abort give the expected value.
  • Each clause of the change was removed in turn (13 mutations). Each one fails at least one test that does not need Node.js.
  • On main: 7 of the 8 new tests in buffer.test.js fail, and the new test in string-decoder.test.js fails. The one that passes pins that the source is checked before the encodings.
  • Also run on the debug build: all of buffer.test.js and string-decoder.test.js, the transcode and StringDecoder tests with BUN_JSC_validateExceptionChecks=1, and these vendored Node tests: test-icu-transcode, test-string-decoder, test-string-decoder-end, test-string-decoder-fuzz, test-crypto-encoding-validation-error, test-crypto-cipheriv-decipheriv, test-stream2-set-encoding, test-stream-readable-setEncoding-null, test-stream-readable-setEncoding-existing-buffers, test-stream-readable-default-encoding, test-stream-decoder-objectmode, test-fs-read-stream-encoding. They passed before too: no upstream test reaches the changed behavior.

Self-review: the 4 concerns not taken

  • Two asked to remove the NUL cut, because Node's other users of the native parser (hash and cipher update(), digest(), fs.write, os.userInfo) do not have it in Bun, and node:fs: write UTF-8 when fs.write gets an unknown encoding name #43435 declines it for fs.write. It stays for transcode(): Node's result there is stable (for fs.write Node can abort, which is the reason node:fs: write UTF-8 when fs.write gets an unknown encoding name #43435 gives), and without it Bun rejects 9 of the 139 values that Node takes. It is one function, parseTranscodeEncodingBeforeNul, and the test takes a string as a name, or as a C string that ends at its first NUL. Removing both removes the behavior.
  • One asked to remove the U_INVALID_CHAR_FOUND results for an emptied source. They stay, because they are what Node returns. They are the nodeUsesSimdutf block.
  • One asked to keep the helper private to transcode() until a maintainer asks for a shared one. It is shared with one more caller that has the same Node contract, in its own commit. If the StringDecoder change is not wanted, drop the second commit.

Not in this PR

  • Buffer.alloc(size, fill, encoding) and buf.fill(value, offset, end, encoding) convert every non-string encoding (resolveEncodingString in src/jsc/bindings/JSBuffer.cpp). Node's _fill uses normalizeEncoding only to validate, and takes the encoding from a string-only native parse. So Buffer.alloc(4, "ab", new String("hex")) is 61626162 in Node and abababab in Bun, and { toString } throws ERR_INVALID_ARG_TYPE in Node. buffer: match Node's Buffer.prototype.fill offset and end argument handling #33033 kept Bun's conversion there and a test in buffer.test.js pins it.
  • Buffer.byteLength, buf.toString, buf.write and buf.indexOf follow another Node rule (encoding += ''). node:buffer: coerce a non-string encoding like Node's getEncodingOps #43442 has them.
  • Bun's stand-ins for Node's validateEncoding, which also calls normalizeEncoding, take strings only: validateEncoding in NodeValidator.cpp (behind fs.write) and the update() of Hash, Hmac, Sign, Verify and Cipher.
  • The normalizeEncoding binding for built-in JS (node_util_binding), used by the cipher decoder and Writable.fromWeb, converts every value.
  • Two transcode() results that differ from Node for other reasons, on main and here: ucs2 to ucs2 of the bytes 00 d8 41 is fdff in Node and fdfffdff in Bun, and a source with an own length of 0 is an empty Buffer in Node.

Related PRs

…zeEncoding

transcode() converted every encoding argument that was not undefined or
null to a string, so it ran user toString() code and returned a Buffer
where Node throws U_ILLEGAL_ARGUMENT_ERROR.

Node passes each encoding through `normalizeEncoding(enc) || enc` and
then to a native parser that takes a string only. normalizeEncoding()
converts a value that is not a string only when its `length` is the
length of an encoding name, and then takes only a name of that length.

WebCore::normalizeEncoding() is that function for a JSValue. It is
beside the encoding table, and a string goes through the existing
parser first. transcode() calls it and keeps what is its own: a string
that is not a name ends at its first NUL, because Node's native parser
reads a C string.

An encoding that is not supported is now reported before the source is
read again. A source that user code emptied fails with
U_INVALID_CHAR_FOUND for the pairs that fail in Node.

The new fixture prints what transcode() does with each value of a list.
buffer.test.js runs it under Node.js and under Bun and compares the
output.
…port

Node's StringDecoder takes its encoding from normalizeEncoding(), as
transcode() does. The constructor took a string only, so it threw
ERR_UNKNOWN_ENCODING for "", for a String object, and for a value whose
`length` and string are those of an encoding name. Node accepts them.

The constructor now calls WebCore::normalizeEncoding(). The path that
builds ERR_UNKNOWN_ENCODING does not change. Readable#setEncoding()
constructs a StringDecoder, so it follows.
@robobun

robobun commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 12:15 AM PT - Oct 19th, 2026

✅ @robobun, your commit ce5fece8dcf6d1c0a60aa93bd86c7d736ffc9e6a passed in Build #128691! 🎉


🧪   To try this PR locally:

bunx bun-pr 46006

That installs a local version of the PR into your bun-46006 executable, so you can run:

bun-46006 --bun

@coderabbitai

coderabbitai Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: oven-sh/bun/.coderabbit.yaml
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: f3c26055-3eae-4719-bfea-95508e9c0342
📥 Commits

Reviewing files that changed from the base of the PR and between 91e7e3b and ce5fece.

📒 Files selected for processing: 7
  • src/jsc/bindings/JSBufferEncodingType.cpp
  • src/jsc/bindings/JSBufferEncodingType.h
  • src/jsc/bindings/JSStringDecoder.cpp
  • src/jsc/modules/NodeBufferModule.cpp
  • test/js/node/buffer.test.js
  • test/js/node/normalize-encoding-fixture.js
  • test/js/node/string_decoder/string-decoder.test.js

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

Walkthrough

The change adds shared encoding normalization for StringDecoder and buffer.transcode(). Transcoding now validates encodings before reading the source view and checks the view length again after encoding coercion. Tests compare behavior with Node.js and cover coercion, evaluation order, and source changes.

Changes

Encoding Normalization and Transcoding

Layer / File(s) Summary
Shared encoding normalization and StringDecoder
src/jsc/bindings/JSBufferEncodingType.*, src/jsc/bindings/JSStringDecoder.cpp, test/js/node/normalize-encoding-fixture.js, test/js/node/string_decoder/string-decoder.test.js
The shared normalization functions handle string and non-string encoding values. StringDecoder uses the shared normalization, and tests check results and coercion accesses.
Transcode encoding and source handling
src/jsc/modules/NodeBufferModule.cpp, test/js/node/buffer.test.js, test/js/node/normalize-encoding-fixture.js
transcode() maps normalized encodings, handles names containing NUL, validates encodings before reading the source view, and rechecks its length after coercion. Tests cover argument order, errors, and source changes during coercion.

Suggested reviewers: cirospaciari, jarred-sumner

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to ce5fe

This change aligns encoding normalization for buffer.transcode and StringDecoder with Node. No actionable merge-blocking risk was identified from the supplied context.

Pre-merge checks: Passed 4
Check name Status Explanation
Title check Passed The title clearly and concisely identifies the main change: porting Node's normalizeEncoding behavior to buffer.transcode and StringDecoder.
Description check Passed The description explains the problem, implementation, behavior changes, scope, tradeoffs, related work, and extensive verification. It does not use the exact template headings, but it fully covers wha…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description explains the problem, implementation, behavior changes, scope, tradeoffs, related work, and extensive verification. It does not use the exact template headings, but it fully covers what the PR does and how it was verified.

✨ Finishing Touches: 💡 1
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

Reproduction, on Bun 1.4.2 and a release build of main (017b2439a, linux x64):

bun -e 'const { transcode } = require("node:buffer"); const { StringDecoder } = require("node:string_decoder"); const show = f => { try { return JSON.stringify(f()); } catch (e) { return "throws " + e.code; } }; console.log(show(() => [...transcode(Buffer.from("a"), "utf8", ["latin1"])]), show(() => new StringDecoder(new String("latin1")).encoding));'

It prints [97] throws ERR_UNKNOWN_ENCODING. Node v26.3.0 prints throws U_ILLEGAL_ARGUMENT_ERROR "latin1" for the same line with node -e. A build of this branch prints the same as Node.

  • On a release build of main, bun test test/js/node/buffer.test.js -t transcode fails 7 of the 8 new tests, and bun test test/js/node/string_decoder/string-decoder.test.js fails the new test.
  • On this branch, bun bd test test/js/node/buffer.test.js passes (726 pass, 1 skip, 0 fail) and bun bd test test/js/node/string_decoder/string-decoder.test.js passes (144 pass).

CI: build #128691 passed on ce5fece8dc, 181 of 181 jobs. Two test files failed on a first attempt and passed on a retry: test/js/node/process/process.test.js (process.hrtime(), debian 13 x64-asan) and test/js/web/fetch/fetch-http3-client.test.ts (macOS x64). This PR does not touch the code that they test.

The fix is in this PR (#46006). It waits for a maintainer's review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review found no issues

No high-confidence issues detected in this change.

@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-19.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant