Skip to content

buffer.transcode: write nothing for a default-ignorable code point the target cannot encode - #45732

Open
robobun wants to merge 1 commit into
mainfrom
robobun/af4d3822/transcode-skip-default-ignorable
Open

robobun wants to merge 1 commit into
mainfrom
robobun/af4d3822/transcode-skip-default-ignorable

Conversation

@robobun

@robobun robobun commented Oct 17, 2026

Copy link
Copy Markdown
Collaborator

Problem

  • buffer.transcode() to latin1 or ascii writes ? for an invisible code point that Node leaves out. transcode(Buffer.from("\uFEFFname;city"), "utf8", "latin1") returns ?name;city. Node v26.3.0 returns name;city.
  • ICU's default callback writes nothing for an unmappable code point in its IS_DEFAULT_IGNORABLE_CODE_POINT list (ucnv_err.cpp#L174-L180). transcodeEncodeNarrow (src/jsc/modules/NodeBufferModule.cpp:107) ports that converter and wrote ?.
  • No user reported this. A differential run against Node found it, first recorded in Fix buffer.transcode() abort when the output needs 2 GiB or more #42875.

Fix

  • transcodeEncodeNarrow writes nothing for the 4,174 code points of ICU's list.
  • The substitution path is one in-place pass over the UTF-16 copy, then one exact-length Buffer. The sizing loop is gone.
  • Correct because Node v26.3.0 returns the same bytes for all 1,112,064 scalar values.
  • Verified: 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

  • A default-ignorable code point has no glyph: byte order mark, zero width space, soft hyphen.
  • transcode decodes the source to a private UTF-16 copy, then encodes it. A latin1 target tries a simdutf bulk conversion first (unchanged).
  • Weighed: a shared walk for a sizing and a write loop (two scalar passes), ICU's ucnv converter (not linked, 10 to 21 times slower in Node), u_hasBinaryProperty (no compile-time table).

Downsides

  • Behaviour change since v1.4.0: a result can hold fewer bytes than its source has code points.
  • Text with skipped code points converts slower: +8% to +18% with one zero width space in 40 code points.
  • The binary grows by 8,448 bytes. Each substitution call adds one memcpy, and takes 0.91x to 1.04x of main's time when nothing is skipped.
Notes

Reproduction. bun repro.mjs exits 1 on 1.4.2, 1.4.3 and main. It exits 0 with this PR and on Node v26.3.0.

import { transcode } from "node:buffer";
const to = (text, target) => transcode(Buffer.from(text, "utf8"), "utf8", target).toString("latin1");
const cp = n => String.fromCodePoint(n);
const rows = [
  ["name;city", "name;city"],
  ["5 " + cp(0x20ac), "5 ?"], // the euro sign is visible: "?" in every runtime
  [cp(0xfeff) + "name;city", "name;city"], // byte order mark
  ["name;" + cp(0x200b) + "city", "name;city"], // zero width space
  ["name;city" + cp(0x200e), "name;city"], // left-to-right mark
  ["name" + cp(0x2060) + ";city", "name;city"], // word joiner
  ["1" + cp(0xfe0f) + " name", "1 name"], // variation selector 16
];
let bad = 0;
for (const [text, expected] of rows) for (const target of ["ascii", "latin1"]) if (to(text, target) !== expected) bad++;
console.log(bad + " of 14 results are wrong");
process.exit(bad ? 1 : 0);
main:         10 of 14 results are wrong
this PR:       0 of 14 results are wrong
node v26.3.0:  0 of 14 results are wrong

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() and TranscodeFromUcs2() in node_i18n.cc open ICU's us-ascii or iso8859-1 converter, 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 in transcodeEncodeNarrowUnit. 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 ucnv code (0 ucnv_ symbols in the release binary), and the loop needs the list at compile time for its bit table. The macro and the Unicode 17 property Default_Ignorable_Code_Point hold 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 one memcpy. 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:

  • The loop handles two units in each step. The compiler unrolled main's write loop and does not unroll this one. With one unit in a step every substitution call takes 1.46 times the cycles of main (4.45 against 3.05 for each unit).
  • ALWAYS_INLINE on 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).

  • Every scalar value as "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.
  • A matrix of 2,264 lines (every byte from latin1 and ascii sources to the 4 targets, 22 texts with invisible characters from utf8 and ucs2 to the 4 targets, ill-formed utf8 and ucs2 next to them): 0 lines differ. On main 89 differ, all with a latin1 or ascii target.
  • The new describe block runs under Node with small shims for describe, it and expect: 6 of 6 pass.

Measurements. Release builds (ThinLTO, linux x64) of main (5866b5f) and of this PR from one tree. Only NodeBufferModule.cpp differs. The rows are those of the new bench/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_open around 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.

                                                  main                     PR
                                          instr  cycles  miss/1k   instr  cycles  miss/1k
ucs2 -> latin1, latin1 text (bulk)         0.87    0.48     0.1     0.87    0.52     0.2
utf8 -> latin1, ASCII (bulk)               0.75    0.37     0.2     0.75    0.38     0.1
ucs2 -> ascii, ASCII                      15.73    3.08     0.3    16.04    2.91     0.1
utf8 -> ascii, ASCII                      15.63    3.03     0.2    15.93    2.83     0.2
latin1 -> ascii, ASCII                    15.41    2.93     0.2    15.71    2.75     0.1
utf8 -> ascii, 8% accented letters        35.98    8.16    81.9    36.27    8.23    82.4
ucs2 -> latin1, 3% curly quotes, dashes   15.73    3.01     0.2    16.03    2.84     0.2
utf8 -> latin1, Cyrillic and ASCII words  46.56   12.88   174.5    46.85   12.72   173.4
ucs2 -> ascii, Cyrillic and ASCII words   15.73    3.07     0.2    16.04    2.88     0.2
ucs2 -> latin1, CJK, fullwidth punct.     15.73    3.04     0.2    16.03    2.89     0.2
ucs2 -> ascii, 2% emoji                   15.64    3.40    15.8    15.85    3.23    13.9
ucs2 -> latin1, all CJK                   15.73    3.02     0.2    16.03    2.88     0.2
ucs2 -> latin1, all emoji                 13.26    2.29     0.2    11.54    2.31     0.2
ascii -> latin1, all bytes above 0x7F     20.19    4.11     0.2    20.49    3.93     0.2
utf8 -> latin1, all invalid bytes         41.52    8.02     0.2    41.82    7.91     0.2
ucs2 -> ascii, 2.5% zero width spaces     15.73    3.01     0.2    16.02    3.44    17.6
utf8 -> latin1, 2.5% zero width spaces    35.35    6.76    26.4    35.68    7.21    46.5
ucs2 -> latin1, all zero width spaces     15.73    3.06     0.2    15.98    2.71     0.2

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.

                                          1.4.3     main       PR     Node   PR/main
ucs2 -> latin1, latin1 text (bulk)      5.59 us  5.16 us  5.00 us  18.4 us   0.97
utf8 -> latin1, ASCII (bulk)            4.19 us  3.92 us  4.36 us  21.9 us   1.11
ucs2 -> ascii, ASCII                    29.2 us  29.5 us  27.9 us  18.2 us   0.94
utf8 -> ascii, ASCII                    28.7 us  28.6 us  26.9 us  7.47 us   0.94
latin1 -> ascii, ASCII                  27.9 us  28.4 us  26.2 us  13.2 us   0.92
utf8 -> ascii, 8% accented letters      82.3 us  79.9 us  78.1 us   138 us   0.98
ucs2 -> latin1, 3% curly quotes, dashes 29.9 us  29.6 us  28.1 us  43.6 us   0.95
utf8 -> latin1, Cyrillic, ASCII words    117 us   124 us   122 us   485 us   0.98
ucs2 -> ascii, Cyrillic, ASCII words    29.6 us  29.3 us  27.5 us   369 us   0.94
ucs2 -> latin1, CJK, fullwidth punct.   28.8 us  29.7 us  27.7 us   451 us   0.93
ucs2 -> ascii, 2% emoji                 32.3 us  32.7 us  30.8 us  31.8 us   0.94
ucs2 -> latin1, all CJK                 28.7 us  28.7 us  27.4 us   447 us   0.95
ucs2 -> latin1, all emoji               21.8 us  21.9 us  22.2 us   243 us   1.02
ascii -> latin1, all bytes above 0x7F   38.4 us  38.9 us  37.3 us   821 us   0.96
utf8 -> latin1, all invalid bytes       67.1 us  76.8 us  75.7 us   787 us   0.98
ucs2 -> ascii, 2.5% zero width spaces   29.0 us  29.5 us  33.8 us  32.8 us   1.14
utf8 -> latin1, 2.5% zero width spaces  67.3 us  65.5 us  71.1 us  52.4 us   1.08
ucs2 -> latin1, all zero width spaces   29.6 us  29.8 us  23.7 us   323 us   0.80

The same rows at other sizes, PR against main:

  • 16 units: 0.93 to 1.07 (ASCII to ascii 117 ns on both, all zero width spaces 110 ns to 118 ns). Main against main: 0.96 to 1.02.
  • 1,024 units: 0.96 to 1.04 with no skipped code point. 2.5% zero width spaces 1.15 and 1.18. All zero width spaces 0.87.
  • 524,288 units (1 MiB): 0.91 to 1.00 with no skipped code point. 2.5% zero width spaces 1.09 and 1.15. All zero width spaces 0.80. The bulk row ucs2 -> latin1 reads 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 -> ascii 555 ns to 542 ns, Node 8,050 ns.

  • Buffers for one call (live Uint8Array cells 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.
  • memcpy for 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.
  • Binary size (llvm-size -A, release, linux x64): .text 81,071,045 to 81,071,301 bytes (+256). .rodata 22,532,844 to 22,541,036 bytes (+8,192, the bit table). transcodeEncodeNarrow 1,348 to 1,362 bytes. jsBufferTranscode 3,410 bytes in both.
  • Write bound on ill-formed input: 400,000 random sources, most of them ill-formed, each as ucs2 and as utf8, on the debug ASAN build. Every ucs2 result equals a model of ICU's rule (the model agrees with Node on the first 200,000 sources), and ASAN reports nothing. The same run with 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 ucnv user. 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 one describe next 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.
  • The existing test transcode to latin1 and ascii writes one byte for each code point keeps its assertions. Its title and comment now say "that ICU keeps".
  • Full file: 724 pass, 1 skip, 0 fail on the debug ASAN build. The transcode tests also pass under 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 above jsBufferTranscode says that the macOS system ICU hides the ucnv API. 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.

Input Node v26.3.0 Bun
encoding { toString() { return "latin1" } } or ["latin1"] throws U_ILLEGAL_ARGUMENT_ERROR converts
encoding new String("latin1") converts converts
encoding Symbol() throws U_ILLEGAL_ARGUMENT_ERROR throws TypeError
label "latin1\0zzz" or "utf8\0" converts throws U_ILLEGAL_ARGUMENT_ERROR
ucs2 to ucs2, bytes 00 d8 41 fdff fdfffdff
source with an own length of 0 empty Buffer converts

Node's rule for an encoding is normalizeEncoding(enc) || enc in lib/buffer.js, which switches on enc.length, then a string check and a C string parse in native code. So it accepts a String object and ignores everything after a NUL. The NUL label and the own length row look like accidents of that code. Say if an issue for these rows is wanted.

…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.
@robobun

robobun commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 8:05 AM PT - Oct 17th, 2026

❌ @robobun, your commit 7220fb0 has some failures in Build #127488 (All Failures)


🧪   To try this PR locally:

bunx bun-pr 45732

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

bun-45732 --bun

@robobun

robobun commented Oct 17, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

Reproduction, on Bun 1.4.2, 1.4.3 and a release build of main (5866b5f13d, linux x64):

bun -e 'const { transcode } = require("node:buffer"); console.log(JSON.stringify(transcode(Buffer.from("\uFEFFname;city"), "utf8", "latin1").toString("latin1")))'

It prints "?name;city". Node v26.3.0 prints "name;city" for the same line with node -e.

  • On Bun 1.4.2 and 1.4.3, bun test test/js/node/buffer.test.js -t "skips a default-ignorable" fails 5 of the 6 new tests. The sixth pins that utf8 and ucs2 targets do not change.
  • bun bd test test/js/node/buffer.test.js passes on this branch: 724 pass, 1 skip, 0 fail.

CI: build #127488 passed on 7220fb0a09, 181 of 181 jobs. test/js/node/buffer.test.js has no failure on any lane (x64-asan: 723 pass, 0 fail. macOS aarch64: 724 pass, 0 fail). Six other test files failed on a first attempt and passed on a retry or alone: setTimeout.test.js, websocket-server.test.ts, hot.test.ts, serve-http3.test.ts, socket.test.ts and sql-pool-transaction-isolation.test.ts. This PR does not touch the code that they test.

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.

@coderabbitai

coderabbitai Bot commented Oct 17, 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: 68aa1ea3-342f-41ea-838e-6b000616c0fa
📥 Commits

Reviewing files that changed from the base of the PR and between 017b243 and 7220fb0.

📒 Files selected for processing: 3
  • bench/snippets/buffer-transcode.mjs
  • src/jsc/modules/NodeBufferModule.cpp
  • test/js/node/buffer.test.js

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

Walkthrough

Narrow-encoding Buffer.transcode now omits specified ICU default-ignorable code points while retaining replacement behavior for other unencodable characters. The pull request adds regression coverage and a configurable benchmark for multiple encoding pairs and text distributions.

Changes

Buffer transcode

Layer / File(s) Summary
Narrow-encoding skip behavior
src/jsc/modules/NodeBufferModule.cpp
The narrow encoder checks ICU default-callback skip ranges and writes output bytes in place. It sizes the result to the bytes written.
Transcode behavior coverage
test/js/node/buffer.test.js
Tests cover omission, replacement, preserved target encodings, malformed inputs, exhaustive code point ranges, and output lengths.
Transcode benchmark
bench/snippets/buffer-transcode.mjs
Adds seeded input generation and configurable benchmarks across encoding pairs, text distributions, and input sizes.

Suggested reviewers: jarred-sumner, cirospaciari

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 7220f

No actionable issue remains from this review; the change is mergeable after normal checks.

Pre-merge checks: Passed 4
Check name Status Explanation
Title check Passed The title clearly and specifically summarizes the main behavior change in buffer.transcode: omitting unencodable default-ignorable code points.
Description check Passed The description thoroughly explains the problem, implementation, tradeoffs, and verification results. It does not use the template headings exactly, but it provides the required information in equival…
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 thoroughly explains the problem, implementation, tradeoffs, and verification results. It does not use the template headings exactly, but it provides the required information in equivalent sections.

✨ 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.

@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.

This branch has not been deployed

No deployments
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.

2 participants