Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions bench/snippets/buffer-transcode.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
// @runtime bun,node
import { Buffer, transcode } from "node:buffer";
import { bench, group, run } from "../runner.mjs";

// UTF-16 units in each source. Example: UNITS=16,1024,32768,524288
const sizes = (process.env.UNITS ?? "16,32768").split(",").map(Number);

// The same sources on every run and in every runtime.
let state = 1;
const random = () => {
state = (state + 0x6d2b79f5) | 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
const range = (first, last) => () => first + Math.floor(random() * (last - first + 1));
const oneOf = list => () => list[Math.floor(random() * list.length)];
// `share` of the code points come from `special`, the others from `common`.
const mix = (share, special, common) => () => (random() < share ? special() : common());
// Words of 2 to 8 code points with a space between them. `share` of the words come from `special`.
const words = (share, special, common) => {
let left = 0;
let letter = common;
return () => {
if (left-- > 0) return letter();
left = 2 + Math.floor(random() * 7);
letter = random() < share ? special : common;
return 0x20;
};
};

const ascii = range(0x61, 0x7a);
const cyrillic = range(0x0430, 0x044f);
const cjk = range(0x4e00, 0x9fff);
const emoji = range(0x1f600, 0x1f64f);
const zeroWidthSpace = () => 0x200b;

// [text, from, to, next code point, encoding of the source bytes when it is not `from`]
const rows = [
// A latin1 target converts in bulk when it can encode every code point.
["latin1 text", "ucs2", "latin1", mix(0.1, range(0xe0, 0xfd), ascii)],
["ASCII", "utf8", "latin1", ascii],
// Every other row converts unit by unit.
["ASCII", "ucs2", "ascii", ascii],
["ASCII", "utf8", "ascii", ascii],
["ASCII", "latin1", "ascii", ascii],
["8% accented letters", "utf8", "ascii", mix(0.08, oneOf([0xe9, 0xe8, 0xe0, 0xe7, 0xea, 0xfc, 0xf1]), ascii)],
[
"3% curly quotes and dashes",
"ucs2",
"latin1",
mix(0.03, oneOf([0x2018, 0x2019, 0x201c, 0x201d, 0x2014, 0x2026]), ascii),
],
["Cyrillic words, 20% ASCII words", "utf8", "latin1", words(0.2, ascii, cyrillic)],
["Cyrillic words, 20% ASCII words", "ucs2", "ascii", words(0.2, ascii, cyrillic)],
["CJK, 10% fullwidth punctuation", "ucs2", "latin1", mix(0.1, oneOf([0xff0c, 0x3002, 0xff1f, 0xff01]), cjk)],
["2% emoji", "ucs2", "ascii", mix(0.02, emoji, ascii)],
["all CJK", "ucs2", "latin1", cjk],
["all emoji", "ucs2", "latin1", emoji],
["all bytes above 0x7F", "ascii", "latin1", range(0x80, 0xff), "latin1"],
["all invalid bytes", "utf8", "latin1", range(0x80, 0xbf), "latin1"],
// ICU, and so Node, writes nothing for a default-ignorable code point that the target cannot encode.
["2.5% zero width spaces", "ucs2", "ascii", mix(0.025, zeroWidthSpace, ascii)],
["2.5% zero width spaces", "utf8", "latin1", mix(0.025, zeroWidthSpace, ascii)],
["all zero width spaces", "ucs2", "latin1", zeroWidthSpace],
];

function source(units, encoding, next) {
const text = new Uint16Array(units);
for (let length = 0; length < units;) {
const codePoint = next();
if (codePoint <= 0xffff) {
text[length++] = codePoint;
} else if (length + 2 <= units) {
text[length++] = 0xd800 + ((codePoint - 0x10000) >> 10);
text[length++] = 0xdc00 + ((codePoint - 0x10000) & 0x3ff);
} else {
text[length++] = 0x20;
}
}
const ucs2 = Buffer.from(text.buffer);
return encoding === "ucs2" ? ucs2 : Buffer.from(ucs2.toString("ucs2"), encoding);
}

for (const units of sizes) {
// Each row converts a pool of different sources in rotation. The unit by unit path has branches on the text,
// and one source that repeats lets the branch predictor learn it.
const pool = 2 ** Math.max(1, Math.min(12, Math.floor(Math.log2(2 ** 19 / units))));
group(`${units} UTF-16 units`, () => {
for (const [text, from, to, next, encoding = from] of rows) {
const sources = Array.from({ length: pool }, () => source(units, encoding, next));
let cursor = 0;
bench(`${from} to ${to}, ${text}`, () => transcode(sources[cursor++ & (pool - 1)], from, to));
}
});
}

await run();
101 changes: 81 additions & 20 deletions src/jsc/modules/NodeBufferModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "JSDOMExceptionHandling.h"
#include "wtf/SIMDUTF.h"
#include <JavaScriptCore/JSTypedArrays.h>
#include <array>

namespace WebCore {
JSC::JSUint8Array* createUninitializedBuffer(JSC::JSGlobalObject*, size_t);
Expand Down Expand Up @@ -101,10 +102,67 @@ static bool transcodeDecodeToUtf16(std::span<const uint8_t> input, TranscodeEnco
return true;
}

// Encode well-formed UTF-16 into a single-byte encoding: code points above
// maxCodePoint become '?', matching ICU's substitution behavior.
// Returns nullptr with an exception pending when the result cannot be allocated.
static JSC::JSUint8Array* transcodeEncodeNarrow(JSGlobalObject* globalObject, const WTF::Vector<char16_t>& units, char16_t maxCodePoint)
// The code points that ICU's default callback skips when the target cannot encode them. IS_DEFAULT_IGNORABLE_CODE_POINT: https://github.com/unicode-org/icu/blob/release-78.3/icu4c/source/common/ucnv_err.cpp#L68-L86
static constexpr std::pair<char32_t, char32_t> transcodeSkippedRanges[] = {
{ 0x00AD, 0x00AD },
{ 0x034F, 0x034F },
{ 0x061C, 0x061C },
{ 0x115F, 0x115F },
{ 0x1160, 0x1160 },
{ 0x17B4, 0x17B5 },
{ 0x180B, 0x180F },
{ 0x200B, 0x200F },
{ 0x202A, 0x202E },
{ 0x2060, 0x206F },
{ 0x3164, 0x3164 },
{ 0xFE00, 0xFE0F },
{ 0xFEFF, 0xFEFF },
{ 0xFFA0, 0xFFA0 },
{ 0xFFF0, 0xFFF8 },
{ 0x1BCA0, 0x1BCA3 },
{ 0x1D173, 0x1D17A },
{ 0xE0000, 0xE0FFF },
};

static constexpr bool transcodeSkipsUnmappable(char32_t codePoint)
{
for (const auto& [first, last] : transcodeSkippedRanges) {
if (codePoint >= first && codePoint <= last)
return true;
}
return false;
}

// One bit for each UTF-16 unit that can start a code point of those ranges: a BMP code point of one, or a lead surrogate of one.
static constexpr std::array<uint64_t, 1024> transcodeSkippedStarts = [] {
std::array<uint64_t, 1024> bits {};
for (const auto& [first, last] : transcodeSkippedRanges) {
const bool isBMP = U_IS_BMP(first);
for (char32_t unit = isBMP ? first : U16_LEAD(first); unit <= (isBMP ? last : U16_LEAD(last)); ++unit)
bits[unit >> 6] |= uint64_t { 1 } << (unit & 63);
}
return bits;
}();

// One step of transcodeEncodeNarrow: writes the byte of source[i], if it has one.
static ALWAYS_INLINE void transcodeEncodeNarrowUnit(const char16_t* source, size_t i, size_t length, char16_t maxCodePoint, uint8_t* bytes, size_t& written)
{
const char16_t unit = source[i];
// A trail surrogate writes nothing: its lead wrote the byte of the pair.
if (U16_IS_TRAIL(unit)) [[unlikely]]
return;
if ((transcodeSkippedStarts[unit >> 6] >> (unit & 63)) & 1) [[unlikely]] {
// Skipped, unless the target has this code point (U+00AD in latin1) or this lead surrogate starts a pair outside the ranges.
if (unit > maxCodePoint && (!U16_IS_LEAD(unit) || (i + 1 < length && U16_IS_TRAIL(source[i + 1]) && transcodeSkipsUnmappable(U16_GET_SUPPLEMENTARY(unit, source[i + 1])))))
return;
}
bytes[written++] = unit <= maxCodePoint ? static_cast<uint8_t>(unit) : '?';
}

// Encode well-formed UTF-16 into a single-byte encoding as ICU's converter does with '?' for its substitution character.
// A code point above maxCodePoint becomes '?', or nothing when ICU skips it: https://github.com/unicode-org/icu/blob/release-78.3/icu4c/source/common/ucnv_err.cpp#L174-L185
// Overwrites `units`. Returns nullptr with an exception pending when the result cannot be allocated.
static JSC::JSUint8Array* transcodeEncodeNarrow(JSGlobalObject* globalObject, WTF::Vector<char16_t>& units, char16_t maxCodePoint)
{
auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
JSC::JSUint8Array* result = nullptr;
Expand All @@ -117,24 +175,27 @@ static JSC::JSUint8Array* transcodeEncodeNarrow(JSGlobalObject* globalObject, co
if (converted.error == simdutf::error_code::SUCCESS)
return result;
}
// Substitution path: simdutf conversions are strict, so out-of-range
// code points ('?' in ICU) are handled per unit.
constexpr auto writesByte = [](char16_t unit) { return !U16_IS_TRAIL(unit); };
size_t length = 0;
for (const char16_t unit : units)
length += writesByte(unit);
// A surrogate pair writes one '?', so a source with pairs needs a shorter result than the bulk attempt allocated.
if (!result || length != units.size()) {
result = WebCore::createUninitializedBuffer(globalObject, length);
RETURN_IF_EXCEPTION(scope, nullptr);
}
const std::span<uint8_t> out = result->typedSpan();
// Substitution path: simdutf conversions are strict, so each unit is handled here.
// The bytes overwrite the front of `units`: a step reads its unit before it writes at most one byte.
const size_t length = units.size();
const char16_t* const source = units.begin();
auto* const bytes = reinterpret_cast<uint8_t*>(units.begin());
size_t written = 0;
for (const char16_t unit : units) {
if (writesByte(unit))
out[written++] = unit <= maxCodePoint ? static_cast<uint8_t>(unit) : '?';
size_t i = 0;
// Two units in a step. The compiler unrolled the loop that this replaces and does not unroll this one: a step of one unit takes 1.5 times as long.
for (; i + 1 < length; i += 2) {
transcodeEncodeNarrowUnit(source, i, length, maxCodePoint, bytes, written);
transcodeEncodeNarrowUnit(source, i + 1, length, maxCodePoint, bytes, written);
}
if (i < length)
transcodeEncodeNarrowUnit(source, i, length, maxCodePoint, bytes, written);
// A surrogate pair or a skipped code point leaves fewer bytes than the bulk attempt allocated.
if (!result || written != length) {
result = WebCore::createUninitializedBuffer(globalObject, written);
RETURN_IF_EXCEPTION(scope, nullptr);
}
ASSERT(written == out.size());
if (written)
memcpy(result->typedVector(), bytes, written);
return result;
}

Expand Down
Loading
Loading