Repository navigation
Conversation
…e target cannot encode ICU's default from-Unicode callback skips an unmappable code point that is in its IS_DEFAULT_IGNORABLE_CODE_POINT list, so Node's transcode() to latin1 or ascii leaves it out. Bun wrote '?' for it. The narrow encoder is now one pass. It narrows the UTF-16 copy in place and then creates the Buffer at its exact length. The sizing loop is gone. The step for one unit is the one it had (a trail surrogate writes nothing, any other unit is itself or '?') plus one table bit for the units that can start a skipped code point.
|
Updated 8:05 AM PT - Oct 17th, 2026
❌ @robobun, your commit 7220fb0 has some failures in 🧪 To try this PR locally: bunx bun-pr 45732That installs a local version of the PR into your bun-45732 --bun |
|
Status Reproduction, on Bun 1.4.2, 1.4.3 and a release build of main ( bun -e 'const { transcode } = require("node:buffer"); console.log(JSON.stringify(transcode(Buffer.from("\uFEFFname;city"), "utf8", "latin1").toString("latin1")))'It prints
CI: build #127488 passed on The fix is in this PR (#45732). It waits for a maintainer's review, and for a yes to the change of output that the description lists under Downsides. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
WalkthroughNarrow-encoding ChangesBuffer transcode
Suggested reviewers: Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to
|
Problem
buffer.transcode()tolatin1orasciiwrites?for an invisible code point that Node leaves out.transcode(Buffer.from("\uFEFFname;city"), "utf8", "latin1")returns?name;city. Node v26.3.0 returnsname;city.IS_DEFAULT_IGNORABLE_CODE_POINTlist (ucnv_err.cpp#L174-L180).transcodeEncodeNarrow(src/jsc/modules/NodeBufferModule.cpp:107) ports that converter and wrote?.Fix
transcodeEncodeNarrowwrites nothing for the 4,174 code points of ICU's list.test/js/node/buffer.test.js(6 new tests, 5 fail on 1.4.3),test-icu-transcode.js, a 400,000-source ASAN fuzz. Self-reviewed: 12 concerns raised, 12 addressed, one in part (Notes).Background
transcodedecodes the source to a private UTF-16 copy, then encodes it. A latin1 target tries a simdutf bulk conversion first (unchanged).ucnvconverter (not linked, 10 to 21 times slower in Node),u_hasBinaryProperty(no compile-time table).Downsides
Notes
Reproduction.
bun repro.mjsexits 1 on 1.4.2, 1.4.3 and main. It exits 0 with this PR and on Node v26.3.0.Why change it. For
node:*modules Node's observed output is the rule. The comment on the encoder said that?matches ICU's substitution, and ICU does not substitute these code points. #42875 listed this exact difference under "Not changed here". No issue asks for it, and this PR does not claim that a user was hit.What Node runs.
Transcode()andTranscodeFromUcs2()in node_i18n.cc open ICU'sus-asciioriso8859-1converter, set?as its substitution character and keep ICU's default callback. The ICU user guide states the rule: "ICU 54 and above by default skip default-ignorable code points if they are unmappable" (converters.md, ICU-10551). The list is a macro with 18 clauses, ucnv_err.cpp#L68-L86: U+00AD, U+034F, U+061C, U+115F, U+1160, U+17B4 to 17B5, U+180B to 180F, U+200B to 200F, U+202A to 202E, U+2060 to 206F, U+3164, U+FE00 to FE0F, U+FEFF, U+FFA0, U+FFF0 to FFF8, U+1BCA0 to 1BCA3, U+1D173 to 1D17A, U+E0000 to E0FFF. U+00AD is in latin1, so a latin1 target keeps it.Which lines are the fix. The fix is the table
transcodeSkippedRanges(ICU's 18 clauses as data), the bit table built from it, and the one test of that bit intranscodeEncodeNarrowUnit. The rest of the hunk is the rewrite that hosts it: one pass in place of the sizing loop and the write loop.Why a copy of the list. Node runs ICU's macro, not the Unicode property. #38013 removed a hand-copied Unicode table once the bundled ICU had the data. This list is different: ICU hard-codes it in the converter's callback, Bun links no
ucnvcode (0ucnv_symbols in the release binary), and the loop needs the list at compile time for its bit table. The macro and the Unicode 17 propertyDefault_Ignorable_Code_Pointhold the same 4,174 code points today.The loop. The step for one UTF-16 unit is the one main has (a trail surrogate writes nothing, any other unit is itself or
?) plus one bit test. The bit is set for the 72 units that can start a skipped code point: the 66 BMP code points of the list and the 6 lead surrogates of its supplementary ranges. Those units take a branch that no other text takes. The bytes go to the front of the UTF-16 copy, which this function owns: a step reads its unit before it writes at most one byte, so a byte never lands on a unit that is still to be read. After the walk the result is created at its exact length and filled with onememcpy. A latin1 target still tries the simdutf bulk conversion first and reuses that Buffer when no unit was a trail surrogate or was skipped.Three things in the loop are there for speed only:
ALWAYS_INLINEon the step keeps those two copies in the loop.[[unlikely]]on the two rare branches keeps the common path straight.An earlier version of this PR branched on "the target can encode this unit". It halved the time of ASCII-heavy text and made mixed text 1.3 to 5.3 times slower than main (French to ascii 1.3x, Russian prose 3.3x) when each call saw a different buffer, because that branch follows the text. The self-review found it. The step above has no branch that follows ordinary text.
Output against Node v26.3.0 (ICU 78.3).
"a" + cp + "b", from utf8 and from ucs2, to ascii and to latin1: 0 of 4,448,256 results differ. On main 16,694 differ.describeblock runs under Node with small shims fordescribe,itandexpect: 6 of 6 pass.Measurements. Release builds (ThinLTO, linux x64) of main (5866b5f) and of this PR from one tree. Only
NodeBufferModule.cppdiffers. The rows are those of the newbench/snippets/buffer-transcode.mjs. Each row converts a pool of different sources in rotation (16 sources of 64 KiB). One source that repeats lets the branch predictor learn the text, and that hid the slow rows of the earlier version.Hardware counters for one UTF-16 unit (
perf_event_openaround each sweep of a pool, user mode, this thread, the sweep with the fewest cycles of 40). 32,768 units in each source. Main against main differs by at most 2% in cycles.The step costs 0.3 more instructions for each unit, and its cycles are 0.93 to 1.01 times main's. The bulk rows run the same instructions. Only the rows with zero width spaces have more branch misses: one for each skipped code point.
Wall clock, min time for one call. One pinned core, 5 alternating runs of each runtime, 15 sweeps of the pool in each run. Sources of 32,768 units (64 KiB of ucs2). Main against main differs by at most 3% on the unit by unit rows and by 12% on the two bulk rows.
The same rows at other sizes, PR against main:
ucs2 -> latin1reads 1.20, and main against main reads 1.19 on it.Node is faster than Bun where an ascii target gets pure ASCII (7.47 us against 26.9 us at 64 KiB). Bun has no bulk path for an ascii target. This PR does not add one.
The inputs of Node's own benchmark (
benchmark/buffers/buffer-transcode.js:"a".repeat(length)for every pair, lengths 1, 10 and 1,000): all 45 rows are within 0.91 to 1.06 of main, and main against main is 0.94 to 1.04. Its two rows where every code point is unmappable (the bytes read as ucs2 are U+6161):ucs2 -> latin1, length 1,000, 566 ns to 537 ns, Node 7,924 ns.ucs2 -> ascii555 ns to 542 ns, Node 8,050 ns.Uint8Arraycells around 8 calls, no collection between): unchanged on the 14 classes measured with no skipped code point (1, or 2 for a latin1 target with a surrogate pair). With a skipped code point: to ascii 1 to 1, to latin1 1 to 2, because the Buffer of the bulk attempt is too long.memcpyfor one call: substitution path 0 to 1 call of the result length. Bulk path 0 to 0. Counted with a breakpoint on the line in the debug build, 10 calls each.llvm-size -A, release, linux x64):.text81,071,045 to 81,071,301 bytes (+256)..rodata22,532,844 to 22,541,036 bytes (+8,192, the bit table).transcodeEncodeNarrow1,348 to 1,362 bytes.jsBufferTranscode3,410 bytes in both.SIMDUTF_FORCE_IMPLEMENTATION=nonsense(simdutf's stub leaves lone surrogates in the copy) also reports nothing, and no result is longer than its source has units.Why not ICU's converter. It returns the same bytes. Bun links none of it today, so it would be the first
ucnvuser. Node, which uses it, takes 10 to 21 times as long as this walk on text with unmappable code points (all CJK to latin1, 64 KiB: 447 us against 27 us).One question for a maintainer. #42875 converts straight into the final Buffer with no intermediate copy. This PR narrows in the UTF-16 copy and then copies once. The other form writes into a Buffer of one byte for each unit and creates a second Buffer only when the result is shorter. It saves the
memcpy(about 1.3 us for 64 KiB in an earlier build of this PR). It also needs 2 Buffers for an ascii target with a surrogate pair (main and this PR need 1), up to one byte for each unit of extra memory for a moment, and a keep-alive on the first Buffer across the second allocation. Say if you prefer that form.Tests. All in
test/js/node/buffer.test.js, in onedescribenext to the existing narrow-encoder test. On 1.4.2 and 1.4.3 five of the six fail.in text: 10 texts from utf8 and ucs2 to ascii, latin1 and binary. The expected strings are Node's.from a latin1 source and next to ill-formed input: byte 0xAD from latin1, binary and ascii sources, and a skipped code point next to a lone surrogate, an odd byte and an invalid UTF-8 byte.for each byte of a latin1 or ascii source: all 256 bytes from latin1 and ascii to latin1 and ascii. Only latin1 to ascii drops 0xAD. An ascii source decodes that byte to U+FFFD.for every code point in ICU's list and no other: all 1,112,064 scalar values to ascii and latin1, 4,096 in a call. 0.5 s to 1 s on the debug ASAN build.at each result length: results shortened by a skipped code point at the lengths of the existing test, up to 1,001 bytes.but keeps it for a utf8 or ucs2 target: passes on main too. It pins that the other targets do not change.transcode to latin1 and ascii writes one byte for each code pointkeeps its assertions. Its title and comment now say "that ICU keeps".BUN_JSC_validateExceptionChecks=1.Self-review. The 12 concerns: say that no user reported this, cite the public records, drop the speed claim from the title, list every slower row with a Node column, correct the list of differences that remain, the step that branched on the text, derive the bit table from the list, measure with a different buffer for each call, Node's own benchmark, a
bench/snippet, the reason against ICU's converter, and an ascii to ascii test. Addressed in part: the comment from #34660 abovejsBufferTranscodesays that the macOS system ICU hides theucnvAPI. The review reads the SDK's export list as having it. No macOS SDK is here to check, so that comment stays and this text does not repeat the claim.Differences from Node v26.3.0 that remain. Main and this PR agree on every row, so none comes from this PR. The code is the argument handling and the ucs2 decode, not the encoder.
{ toString() { return "latin1" } }or["latin1"]U_ILLEGAL_ARGUMENT_ERRORnew String("latin1")Symbol()U_ILLEGAL_ARGUMENT_ERRORTypeError"latin1\0zzz"or"utf8\0"U_ILLEGAL_ARGUMENT_ERROR00 d8 41fdfffdfffdfflengthof 0Node's rule for an encoding is
normalizeEncoding(enc) || encinlib/buffer.js, which switches onenc.length, then a string check and a C string parse in native code. So it accepts aStringobject and ignores everything after a NUL. The NUL label and the ownlengthrow look like accidents of that code. Say if an issue for these rows is wanted.