Repository navigation
Conversation
…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.
|
Updated 12:15 AM PT - Oct 19th, 2026
✅ @robobun, your commit ce5fece8dcf6d1c0a60aa93bd86c7d736ffc9e6a passed in 🧪 To try this PR locally: bunx bun-pr 46006That installs a local version of the PR into your bun-46006 --bun |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
WalkthroughThe change adds shared encoding normalization for ChangesEncoding Normalization and Transcoding
Suggested reviewers: Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to
|
|
Status Reproduction, on Bun 1.4.2 and a release build of main ( 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
CI: build #128691 passed on The fix is in this PR (#46006). It waits for a maintainer's review. |
|
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. |
Problem
buffer.transcode()converts every encoding that is notundefinedornullto a string (value.toWTFString(),src/jsc/modules/NodeBufferModule.cpp:167). Sotranscode(buf, "utf8", ["latin1"])returns a Buffer. Node throwsUnable to transcode Buffer [U_ILLEGAL_ARGUMENT_ERROR].new StringDecoder()takes strings only:new StringDecoder(new String("latin1"))throwsERR_UNKNOWN_ENCODING. Node uses one function for both.Fix
normalizeEncoding()inJSBufferEncodingType.his that Node function for a JSValue.transcode()and theStringDecoderconstructor call it, one commit each.transcode()ends a string that is not a name at its first NUL. It rejects an unsupported encoding before it reads the source again.test/js/node/buffer.test.jsruns 136 values under Node and Bun and compares the output.Background
normalizeEncoding()converts a value that is not a string only when itslengthis 3 to 9. Sonew String("latin1")is a name and["latin1"]is not.transcode()uses next, reads a C string.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.StringDecoderaccepts more: 37 of 139.new StringDecoder(name)runs 5 more instructions (711 to 716), andtranscode()33 more per""encoding. Release text grows by 2,560 bytes.Notes
Repro
throws U_ILLEGAL_ARGUMENT_ERROR toString calls: 0[97] toString calls: 1throws U_ILLEGAL_ARGUMENT_ERROR[97]"latin1"throws ERR_UNKNOWN_ENCODING"utf8"throws ERR_UNKNOWN_ENCODINGNode's rule (v26.3.0)
normalizeEncoding:undefined,nulland""are utf8.slowCasesdoesswitch (enc.length). Only the cases 3 to 9 callStringPrototypeToLowerCase(enc), once, and compare the result with the names of that length.transcodedoesnormalizeEncoding(enc) || encfor each encoding, then calls the native function.ParseEncodinggives the default for a value that is not a string, whichTranscoderejects. It reads a string throughUtf8Valueas a C string, so"latin1\0xyz"is latin1.StringDecodertakes the result ofnormalizeEncoding(encoding)and throwsERR_UNKNOWN_ENCODINGwhen there is none.The code
normalizeEncoding()is inline:undefinedandnullare utf8, then the existing string parser runs (parseEnumeration<BufferEncodingType>), then""is utf8. Only a value that is not a string goes to the new functionnormalizeEncodingOfNonString(). So a call with a name takes the same path as before. The header gets#pragma oncebecause it now has a definition.jsBufferTranscodekeeps what onlytranscode()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.createDecoderchanges one line. The path that buildsERR_UNKNOWN_ENCODINGis not changed.Behavior change
Probe: 139 values, each as
fromEnc, astoEnc, and as theStringDecoderencoding, compared with Node v26.3.0.transcode()TypeErrornew StringDecoder()transcode(): 30 values that returned a Buffer now throwU_ILLEGAL_ARGUMENT_ERROR. They are{ toString },{ [Symbol.toPrimitive] },[],[""],["latin1"],new String(""), an object with alengththat is not 3 to 9, and an object whose string is not a name of itslength.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())andObject.create(null)now throwU_ILLEGAL_ARGUMENT_ERROR. They threw aTypeError. Alengthgetter now runs, and an error from it propagates.StringDecoder,readable.setEncoding()and the other callers of the constructor: 37 values that threwERR_UNKNOWN_ENCODINGnow give a decoder. They are"", a String object, a Buffer that holds a name, and an object whoselengthand string are those of a name. No value goes the other way.StringDecoderstill differs forSymbol(),Object(Symbol())andObject.create(null): Bun throws aTypeErrorwhile it builds the message ofERR_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.undefined,null, and fortranscode()also"","hex","base64","buffer", numbers, booleans,new String("latin1"),Buffer.from("latin1").User code that changes the source
A
lengthgetter or atoString()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: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)
transcode()call, 1-byte source, gdb single-step ofjsBufferTranscodewith its callees: omitted 1374 -> 1354,null/null1376 -> 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.new StringDecoder(x), gdb single-step of the constructor: omitted 628 -> 628, each of 12 names +5 (for example utf8 711 -> 716).mi_mallocper call (gdb hit counts, N=200 against 1200):transcodeutf8/latin1 2.156 -> 2.156, UTF8/LATIN1 4.156 -> 2.156,new StringDecoder("utf8")0.14 -> 0.14.convertToASCIILowercasecalls per 1000transcodecalls: 2000 -> 0.size, 106,738,870 against 106,741,430). Bynm -S: the transcode symbols go from 3,908 to 5,164 bytes,normalizeEncodingOfNonStringis 908 bytes,createDecodergoes from 1,220 to 1,412 bytes. 0 new host functions.bloatyis not installed.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.toWTFStringSlowCasecalls per 1000 calls with{}: 1000 -> 0.Tests
test/js/node/normalize-encoding-fixture.jsprints whattranscode()(both positions) andStringDecoderdo with each value, and the order in whichtranscode()reads its arguments.buffer.test.jsruns it undernodeExe()andbunExe()and compares the output, as thefill()fixture in the same file does. With Node v26.3.0: main differs on 76 of 136 lines, this PR on 0.buffer.test.jsfail, and the new test instring-decoder.test.jsfails. The one that passes pins that the source is checked before the encodings.buffer.test.jsandstring-decoder.test.js, the transcode and StringDecoder tests withBUN_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
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 forfs.write. It stays fortranscode(): Node's result there is stable (forfs.writeNode 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 testtakes a string as a name, or as a C string that ends at its first NUL. Removing both removes the behavior.U_INVALID_CHAR_FOUNDresults for an emptied source. They stay, because they are what Node returns. They are thenodeUsesSimdutfblock.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 theStringDecoderchange is not wanted, drop the second commit.Not in this PR
Buffer.alloc(size, fill, encoding)andbuf.fill(value, offset, end, encoding)convert every non-string encoding (resolveEncodingStringinsrc/jsc/bindings/JSBuffer.cpp). Node's_fillusesnormalizeEncodingonly to validate, and takes the encoding from a string-only native parse. SoBuffer.alloc(4, "ab", new String("hex"))is61626162in Node andababababin Bun, and{ toString }throwsERR_INVALID_ARG_TYPEin Node. buffer: match Node's Buffer.prototype.fill offset and end argument handling #33033 kept Bun's conversion there and a test inbuffer.test.jspins it.Buffer.byteLength,buf.toString,buf.writeandbuf.indexOffollow another Node rule (encoding += ''). node:buffer: coerce a non-string encoding like Node's getEncodingOps #43442 has them.validateEncoding, which also callsnormalizeEncoding, take strings only:validateEncodinginNodeValidator.cpp(behindfs.write) and theupdate()of Hash, Hmac, Sign, Verify and Cipher.normalizeEncodingbinding for built-in JS (node_util_binding), used by the cipher decoder andWritable.fromWeb, converts every value.transcode()results that differ from Node for other reasons, on main and here: ucs2 to ucs2 of the bytes00 d8 41isfdffin Node andfdfffdffin Bun, and a source with an ownlengthof 0 is an empty Buffer in Node.Related PRs
transcodeEncodeNarrowin the same file. The two merge cleanly in either order. Its body lists the encoding difference that this PR removes.""utf8 increateDecoderand other places. This PR covers its 3-linecreateDecoderhunk, so the second of the two to land has a small conflict inJSStringDecoder.cpp.createDecoder. This PR does not touch those lines.jsBufferTranscodereads the source. The second of the two to land has a conflict inNodeBufferModule.cpp.