From 92198da676aa2ecf04314d88813fe87566759825 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 25 Oct 2026 16:21:46 -0700 Subject: [PATCH 1/5] chore(quest): claim quest/m2/ts-wide-fast.md Quest-Claim: 8d40da37bd40de3a From 7961e4e612de31c082f7abd9aa768be3a9dfe375 Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:55:30 -0700 Subject: [PATCH 2/5] feat(ts): multiply wide integers on halves, and join u64 halves in one call Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/bench/main.ts | 2 +- ts/bench/moq.ts | 3 + ts/bench/rescale.ts | 31 +++++ ts/bench/workloads.ts | 23 +++- ts/fixtures/codec/expected/bench.ts | 63 +++++++++++ ts/fixtures/codec/src/bench.rs | 51 ++++++++- ts/fixtures/lang/expected/ints.ts | 8 ++ ts/fixtures/lang/src/ints.rs | 9 ++ ts/runtime/rt/int.ts | 170 ++++++++++++++++++++-------- ts/src/lower/mir/mod.rs | 68 +++++++++++ ts/src/lower/mir/rvalue.rs | 19 ++++ ts/tests/differential.ts | 23 +++- 12 files changed, 414 insertions(+), 56 deletions(-) create mode 100644 ts/bench/rescale.ts diff --git a/ts/bench/main.ts b/ts/bench/main.ts index 55766de61..3270435ea 100644 --- a/ts/bench/main.ts +++ b/ts/bench/main.ts @@ -305,7 +305,7 @@ function render(): string { `- moq: ${text(["git", "-C", checkout, "rev-parse", "HEAD"])}`, ...engines.map((e) => `- ${e.engine}`), "", - "Each cell is nanoseconds per item (a varint, a frame header, a message, or a byte iterated): the median", + "Each cell is nanoseconds per item (a varint, a frame header, a message, a byte iterated, or a timestamp converted): the median", `of ${rounds} samples of at least ${sampleMs} ms, ± half their interquartile range. Each round runs`, `the JS routes and workloads in a new random order, from seed ${seed}. \`native\` is a release`, "build on the host, its workloads in a fixed order. `wasm` is the same", diff --git a/ts/bench/moq.ts b/ts/bench/moq.ts index 682886876..030137519 100644 --- a/ts/bench/moq.ts +++ b/ts/bench/moq.ts @@ -14,6 +14,7 @@ import { Cursor, Reader, Writer } from "moq/js/net/src/stream.ts"; import * as Varint from "moq/js/net/src/varint.ts"; import { iterate } from "./iter.ts"; +import { rescale } from "./rescale.ts"; type Version = (typeof Lite)[keyof typeof Lite]; @@ -48,6 +49,8 @@ export function run(input: Uint8Array): Uint8Array | Promise { return iterate(selector, data); case 7: return decodeSplit(data, lite(selector)); + case 8: + return rescale(selector, data); default: throw new Error(`unknown workload ${op}`); } diff --git a/ts/bench/rescale.ts b/ts/bench/rescale.ts new file mode 100644 index 000000000..63eee647c --- /dev/null +++ b/ts/bench/rescale.ts @@ -0,0 +1,31 @@ +// The timestamp workloads' hand-written route: `bench.rs`'s op 8 with `bigint`, as moq's +// TypeScript converts timescales (`wallClockTime` in `js/hang/src/catalog/clock.ts`). + +const MAX_TIMESTAMP = (1n << 61n) - 1n; + +/** Convert every timestamp, as `bench::run`'s op 8 does: how many, how many overflowed, and the last. */ +export function rescale(selector: number, data: Uint8Array): Uint8Array { + const view = new DataView(data.buffer, data.byteOffset, data.byteLength); + const [count, start, step, from, to] = [0, 1, 2, 3, 4].map((i) => view.getBigUint64(i * 8)); + // `u64` overflows where `u128` doesn't. + const limit = selector === 0 ? (1n << 128n) - 1n : (1n << 64n) - 1n; + let converted = 0n; + let overflowed = 0n; + let last = 0n; + for (let i = 0n; i < count; i++) { + const scaled = (start + i * step) * to; + const value = scaled > limit ? undefined : scaled / from; + if (value === undefined || value > MAX_TIMESTAMP) { + overflowed++; + } else { + last = value; + converted++; + } + } + const out = new Uint8Array(24); + const put = new DataView(out.buffer); + put.setBigUint64(0, converted); + put.setBigUint64(8, overflowed); + put.setBigUint64(16, last); + return out; +} diff --git a/ts/bench/workloads.ts b/ts/bench/workloads.ts index 1c6624e0e..d16e74f85 100644 --- a/ts/bench/workloads.ts +++ b/ts/bench/workloads.ts @@ -3,10 +3,10 @@ // reads what its encode wrote, and a split decode reads it as it arrives over a stream. export interface Workload { - /** What is coded, such as `varint/quic/2B` or `frames/video/lite-07`, or iterated. */ + /** What is coded, such as `varint/quic/2B` or `frames/video/lite-07`, iterated, or converted. */ name: string; - op: "encode" | "decode" | "iterate" | "handoff"; - /** Varints, frame headers, messages, items, or handoffs per call, which each time is divided by. */ + op: "encode" | "decode" | "iterate" | "convert" | "handoff"; + /** Varints, frame headers, messages, items, timestamps, or handoffs per call, which each time is divided by. */ items: number; input: Uint8Array; } @@ -62,6 +62,23 @@ export function workloads(encode: (input: Uint8Array) => Uint8Array): Workload[] chains.forEach((chain, selector) => { out.push({ name: `iter/${chain}`, op: "iterate", items: bytes.length, input: Uint8Array.of(6, selector, ...bytes) }); }); + + // Microseconds since moq's 2020 epoch, a frame apart at 30 fps, to 90 kHz and back: + // each product passes 2^53 and each quotient is back under it. `bench.rs`'s op 8 converts + // them as moq-net's `Timestamp::convert` does in `u128`, then in `u64`. + const count = 1024; + const start = 190_000_000_000_000n; + const micros = [start, 33_333n, 1_000_000n, 90_000n]; + const ninety = [(start * 90_000n) / 1_000_000n, 3_000n, 90_000n, 1_000_000n]; + for (const [selector, type] of ["u128", "u64"].entries()) { + for (const [name, params] of [ + ["micros-to-90k", micros], + ["90k-to-micros", ninety], + ] as const) { + const input = Uint8Array.of(8, selector, ...[BigInt(count), ...params].flatMap(u64)); + out.push({ name: `time/${type}/${name}`, op: "convert", items: count, input }); + } + } return out; } diff --git a/ts/fixtures/codec/expected/bench.ts b/ts/fixtures/codec/expected/bench.ts index 2c44ef839..20807d843 100644 --- a/ts/fixtures/codec/expected/bench.ts +++ b/ts/fixtures/codec/expected/bench.ts @@ -40,6 +40,8 @@ export function run(input: Uint8Array): rt.ByteVec { iterate(selector, data2, out); } else if (op === 7) { decoded(decodeSplit(data2, liteVersion(selector), out), out); + } else if (op === 8) { + rescale(selector, data2, out); } else { decoded(decodeGroup(data2, liteVersion(selector), out), out); } @@ -282,6 +284,67 @@ export function iterate(chain: rt.u8, data: Uint8Array, out: rt.ByteVec): void { } } +/** + * Timestamps from one timescale to another, products past 2^53: moq-net's + * `Timestamp::convert` in `u128`, or the same in `u64` (selector 1), which overflows + * sooner. How many converted, how many overflowed, and the last converted. + */ +export function rescale(selector: rt.u8, data: Uint8Array, out: rt.ByteVec): void { + const [count, data2] = takeU64(data); + const [start, data3] = takeU64(data2); + const [step, data4] = takeU64(data3); + const [from, data5] = takeU64(data4); + const [to, ] = takeU64(data5); + let [converted, overflowed, last] = [0, 0, 0] as [rt.u64, rt.u64, rt.u64]; + const end = rt.u64Low(count); + for (let i = 0; i < end; i++) { + const value = rt.u64Add(start, rt.u64Mul(i as rt.u64, step)); + let scaled: rt.u64 | undefined; + if (selector === 0) { + const checkedMul = rt.u128CheckedMul(rt.u128Cast(value), rt.u128Cast(to)); + if (checkedMul !== undefined) { + const scaled2 = checkedMul; + scaled = bounded(rt.u128Div(scaled2, rt.u128Cast(from))); + } else { + scaled = undefined; + } + } else { + const map = rt.optionMap(rt.u64CheckedMul(value, to), (scaled3: rt.u64): rt.u64 => { + return rt.u64Div(scaled3, from); + }); + arms: { + if (map !== undefined) { + const v = map; + if (rt.u64Le(v, rt.u64Of(2305843009213693951n))) { + scaled = v; + break arms; + } + } + scaled = undefined; + } + } + if (scaled !== undefined) { + const v2 = scaled; + last = v2; + converted = rt.u64Add(converted, 1); + } else { + overflowed = rt.u64Add(overflowed, 1); + } + } + putU64(out, converted); + putU64(out, overflowed); + putU64(out, last); +} + +/** `value`, or `None` past [`MAX_TIMESTAMP`], as moq-net bounds a converted timestamp. */ +export function bounded(value: rt.u128): rt.u64 | undefined { + if (rt.u128Le(value, rt.u128Cast(rt.u64Of(2305843009213693951n)))) { + return rt.u64Cast(value); + } else { + return undefined; + } +} + export function decodeGroup(wire: Uint8Array, version: Version.Version, out: rt.ByteVec): rt.Result { const decodeSlice = Group.decodeSlice$Decode_Version(wire, version); if (!decodeSlice.ok) { diff --git a/ts/fixtures/codec/src/bench.rs b/ts/fixtures/codec/src/bench.rs index 36f46db4d..69c77999f 100644 --- a/ts/fixtures/codec/src/bench.rs +++ b/ts/fixtures/codec/src/bench.rs @@ -2,7 +2,8 @@ //! benchmarks: `js/net/bench/varint.ts` and `lite-varint.ts`. The first input byte picks //! the workload and the second its wire format; an encode's output is the matching //! decode's input. Op 6 runs iterator chains over its bytes instead, as moq-net's model -//! writes them, and op 7 decodes frame headers as they arrive a few bytes at a time. +//! writes them, op 7 decodes frame headers as they arrive a few bytes at a time, and op 8 +//! converts timestamps between timescales. use crate::coding::{Decode, DecodeError, Decoder, Encode, EncodeError, Encoder, Form, varint}; use crate::harness::{decode_error, encode_error, form, lite_version, put_u64, put_usize, take_u64}; @@ -26,6 +27,7 @@ pub fn run(input: &[u8]) -> Vec { 4 => encoded(encode_group(data, lite_version(selector), &mut out), &mut out), 6 => iterate(selector, data, &mut out), 7 => decoded(decode_split(data, lite_version(selector), &mut out), &mut out), + 8 => rescale(selector, data, &mut out), _ => decoded(decode_group(data, lite_version(selector), &mut out), &mut out), } out @@ -200,6 +202,53 @@ fn iterate(chain: u8, data: &[u8], out: &mut Vec) { } } +/// Timestamps from one timescale to another, products past 2^53: moq-net's +/// `Timestamp::convert` in `u128`, or the same in `u64` (selector 1), which overflows +/// sooner. How many converted, how many overflowed, and the last converted. +fn rescale(selector: u8, data: &[u8], out: &mut Vec) { + let (count, data) = take_u64(data); + let (start, data) = take_u64(data); + let (step, data) = take_u64(data); + let (from, data) = take_u64(data); + let (to, _) = take_u64(data); + let (mut converted, mut overflowed, mut last) = (0, 0, 0); + for i in 0..count as usize { + let value = start + i as u64 * step; + let scaled = match selector { + 0 => match (value as u128).checked_mul(to as u128) { + Some(scaled) => bounded(scaled / from as u128), + None => None, + }, + _ => match value.checked_mul(to).map(|scaled| scaled / from) { + Some(v) if v <= MAX_TIMESTAMP => Some(v), + _ => None, + }, + }; + match scaled { + Some(v) => { + last = v; + converted += 1; + } + None => overflowed += 1, + } + } + put_u64(out, converted); + put_u64(out, overflowed); + put_u64(out, last); +} + +/// moq-net's largest timestamp. +const MAX_TIMESTAMP: u64 = (1 << 61) - 1; + +/// `value`, or `None` past [`MAX_TIMESTAMP`], as moq-net bounds a converted timestamp. +const fn bounded(value: u128) -> Option { + if value <= MAX_TIMESTAMP as u128 { + Some(value as u64) + } else { + None + } +} + fn decode_group(wire: &[u8], version: lite::Version, out: &mut Vec) -> Result<(), DecodeError> { let (group, used) = lite::Group::decode_slice(wire, version)?; put_u64(out, group.subscribe); diff --git a/ts/fixtures/lang/expected/ints.ts b/ts/fixtures/lang/expected/ints.ts index 66cb0cb96..a25866351 100644 --- a/ts/fixtures/lang/expected/ints.ts +++ b/ts/fixtures/lang/expected/ints.ts @@ -1908,6 +1908,14 @@ export function convert(data: Uint8Array, out: rt.ByteVec): void { rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(rt.u64FromBeBytes(Uint8Array.of(d, c, b, a, a, b, c, d)))); const bytes = Uint8Array.of(d, c, b, a); rt.byteVecExtendFromSlice(out, rt.i32ToBeBytes(rt.i32FromBeBytes(bytes))); + rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(fromHalves(rt.u64Low(rt.u64Shr(wide, 32)), rt.u64Low(wide)))); + const narrow = rt.u64Or(rt.u64Shl((rt.u64Low(rt.u64Shr(wide, 40)) & 0xff) as rt.u64, 32), (rt.u64Low(wide) & 0xffff) as rt.u64); + rt.byteVecExtendFromSlice(out, rt.u64ToBeBytes(narrow)); +} + +/** A `u64` from its high and low 32 bits, as moq-net's varints join them. */ +export function fromHalves(hi: rt.u32, lo: rt.u32): rt.u64 { + return rt.u64Or(rt.u64Shl(hi as rt.u64, 32), lo as rt.u64); } //# sourceMappingURL=ints.ts.map diff --git a/ts/fixtures/lang/src/ints.rs b/ts/fixtures/lang/src/ints.rs index 307fc9541..2b16c423d 100644 --- a/ts/fixtures/lang/src/ints.rs +++ b/ts/fixtures/lang/src/ints.rs @@ -190,4 +190,13 @@ pub fn convert(data: &[u8], out: &mut Vec) { out.extend_from_slice(&u64::from_be_bytes([d, c, b, a, a, b, c, d]).to_be_bytes()); let bytes = &[d, c, b, a]; out.extend_from_slice(&i32::from_be_bytes(*bytes).to_be_bytes()); + // Halves joined back, which the runtime does in one call, of each width it takes. + out.extend_from_slice(&from_halves((wide >> 32) as u32, wide as u32).to_be_bytes()); + let narrow = ((wide >> 40) as u8 as u64) << 32 | (wide as u16) as u64; + out.extend_from_slice(&narrow.to_be_bytes()); +} + +/// A `u64` from its high and low 32 bits, as moq-net's varints join them. +fn from_halves(hi: u32, lo: u32) -> u64 { + ((hi as u64) << 32) | lo as u64 } diff --git a/ts/runtime/rt/int.ts b/ts/runtime/rt/int.ts index d2fc8c21b..331f7ff6d 100644 --- a/ts/runtime/rt/int.ts +++ b/ts/runtime/rt/int.ts @@ -618,6 +618,23 @@ function halves(hi: number, lo: number): Limbs { return { hi, lo } as Limbs; } +/** The one form of a 64-bit value from its halves: `hi` in the type's sign, `lo` a uint32. */ +function join(hi: number, lo: number): Wide { + // Rounding keeps the order, so a value past the safe integers still tests past them. + const n = hi * TWO32 + lo; + return safe(n) ? n : halves(hi, lo); +} + +/** A 64-bit value's high half, in the type's sign, read without boxing a number. */ +function hiOf(v: Wide): number { + return typeof v === "number" ? Math.floor(v / TWO32) : v.hi; +} + +/** A 64-bit value's low half, a uint32. */ +function loOf(v: Wide): number { + return typeof v === "number" ? v >>> 0 : v.lo; +} + /** A value's limbs, from a safe integer wrapped into range. */ function limbs(v: Wide, bits: number, signed: boolean): Limbs { if (typeof v !== "number") return v; @@ -670,7 +687,7 @@ function add(a: Wide, b: Wide, bits: number, signed: boolean): Wide { const lo = x.lo + y.lo; const hi = x.hi + y.hi + (lo >= TWO32 ? 1 : 0); if (hi !== high(hi, signed)) panic("attempt to add with overflow"); - return one(halves(hi, lo >>> 0)); + return join(hi, lo >>> 0); } return one(bigChecked(exact(x) + exact(y), bits, signed, "add")); } @@ -683,44 +700,103 @@ function sub(a: Wide, b: Wide, bits: number, signed: boolean): Wide { const lo = x.lo - y.lo; const hi = x.hi - y.hi - (lo < 0 ? 1 : 0); if (hi !== high(hi, signed)) panic("attempt to subtract with overflow"); - return one(halves(hi, lo >>> 0)); + return join(hi, lo >>> 0); } return one(bigChecked(exact(x) - exact(y), bits, signed, "subtract")); } function mul(a: Wide, b: Wide, bits: number, signed: boolean): Wide { + const v = product(a, b, bits, signed); + if (v === undefined) panic("attempt to multiply with overflow"); + return v; +} + +/** + * `a * b`, or `undefined` past the type's range. Neither factor is boxed: 64-bit ones + * multiply by their halves, as do two safe integers at 128 bits. + */ +function product(a: Wide, b: Wide, bits: number, signed: boolean): Wide | undefined { // `+ 0` turns -0 into 0. if (typeof a === "number" && typeof b === "number" && safe(a * b)) return a * b + 0; - const x = limbs(a, bits, signed); - const y = limbs(b, bits, signed); - if (bits === 64 && !signed && (x.hi === 0 || y.hi === 0)) { - // One factor below 2^32: its product with the other's high half must be too. - const cross = x.hi * y.lo + x.lo * y.hi; - const lo = mul32(x.lo, y.lo); - const hi = mulHi + cross; - if (hi > 0xffffffff) panic("attempt to multiply with overflow"); - return one(halves(hi, lo)); + if (bits === 64) return product64(a, b, signed); + if (typeof a === "number" && typeof b === "number") return product128(a, b); + const v = exact(limbs(a, bits, signed)) * exact(limbs(b, bits, signed)); + return fitsBig(v, bits, signed) ? one(box(v, bits, signed)) : undefined; +} + +/** A 64-bit product on halves: of the magnitudes, then signed. */ +function product64(a: Wide, b: Wide, signed: boolean): Wide | undefined { + let xh = hiOf(a); + let xl = loOf(a); + let yh = hiOf(b); + let yl = loOf(b); + const negative = signed && xh < 0 !== yh < 0; + if (signed && xh < 0) { + xl = -xl >>> 0; + xh = (~xh + (xl === 0 ? 1 : 0)) >>> 0; + } + if (signed && yh < 0) { + yl = -yl >>> 0; + yh = (~yh + (yl === 0 ? 1 : 0)) >>> 0; } - return one(bigChecked(exact(x) * exact(y), bits, signed, "multiply")); + // Two high halves pass 2^64. Otherwise one factor is below 2^32, and its product with + // the other's high half must be too: past 2^53 that sum rounds, but stays past it. + if (xh !== 0 && yh !== 0) return undefined; + const lo = mul32(xl, yl); + const hi = mulHi + xh * yl + xl * yh; + if (!signed) return hi > 0xffffffff ? undefined : join(hi, lo); + if (!negative) return hi > 0x7fffffff ? undefined : join(hi, lo); + if (hi > 0x80000000 || (hi === 0x80000000 && lo !== 0)) return undefined; + const nlo = -lo >>> 0; + return join((~hi + (nlo === 0 ? 1 : 0)) | 0, nlo); +} + +/** + * The product of two safe integers past 2^53, as 128-bit limbs: of their magnitudes' + * halves, each partial product below 2^53 and so exact, then signed: negative only in an + * `i128`. Under 2^106, it fits either 128-bit type. + */ +function product128(a: number, b: number): Limbs { + const x = Math.abs(a); + const y = Math.abs(b); + const xh = Math.floor(x / TWO32); + const xl = x >>> 0; + const yh = Math.floor(y / TWO32); + const yl = y >>> 0; + const w0 = mul32(xl, yl); + const m1 = xh * yl; + const m2 = xl * yh; + const s1 = mulHi + (m1 >>> 0) + (m2 >>> 0); + const s2 = xh * yh + Math.floor(m1 / TWO32) + Math.floor(m2 / TWO32) + Math.floor(s1 / TWO32); + const w1 = s1 >>> 0; + const w2 = s2 >>> 0; + const w3 = Math.floor(s2 / TWO32); + if (a < 0 === b < 0) return { hi: w3, w2, w1, lo: w0 } as Limbs; + // Two's complement: each limb inverted, plus the carry out of those below it. + const lo = -w0 >>> 0; + const n1 = (~w1 + (lo === 0 ? 1 : 0)) >>> 0; + const n2 = (~w2 + (lo === 0 && n1 === 0 ? 1 : 0)) >>> 0; + const n3 = ~w3 + (lo === 0 && n1 === 0 && n2 === 0 ? 1 : 0); + return { hi: n3 | 0, w2: n2, w1: n1, lo } as Limbs; } function div(a: Wide, b: Wide, bits: number, signed: boolean): Wide { // Below 2^53, a quotient of doubles truncates to the exact one. if (typeof a === "number" && typeof b === "number" && b !== 0) return Math.trunc(a / b) + 0; - const x = limbs(a, bits, signed); - const y = limbs(b, bits, signed); - if (bits === 64 && !signed && y.hi === 0 && y.lo !== 0) { + if (bits === 64 && !signed && typeof b === "number" && b !== 0 && b < TWO32) { // Long division by a uint32 in 32- and 16-bit digits, every step exact. - const d = y.lo; - const qh = Math.floor(x.hi / d); - let r = x.hi - qh * d; - const t1 = r * 65536 + (x.lo >>> 16); - const q1 = Math.floor(t1 / d); - r = t1 - q1 * d; - const q2 = Math.floor((r * 65536 + (x.lo & 0xffff)) / d); - return one(halves(qh, (q1 * 65536 + q2) >>> 0)); + const xh = hiOf(a); + const xl = loOf(a); + const qh = Math.floor(xh / b); + let r = xh - qh * b; + const t1 = r * 65536 + (xl >>> 16); + const q1 = Math.floor(t1 / b); + r = t1 - q1 * b; + const q2 = Math.floor((r * 65536 + (xl & 0xffff)) / b); + return join(qh, (q1 * 65536 + q2) >>> 0); } - const d = exact(y); + const x = limbs(a, bits, signed); + const d = exact(limbs(b, bits, signed)); if (d === 0n) panic("attempt to divide by zero"); return one(bigChecked(exact(x) / d, bits, signed, "divide")); } @@ -738,7 +814,7 @@ function neg(a: Wide, bits: number, signed: boolean): Wide { const x = limbs(a, bits, signed); if (bits === 64 && signed && !(x.hi === -0x80000000 && x.lo === 0)) { const lo = -x.lo >>> 0; - return one(halves((~x.hi + (lo === 0 ? 1 : 0)) | 0, lo)); + return join((~x.hi + (lo === 0 ? 1 : 0)) | 0, lo); } return one(bigChecked(-exact(x), bits, signed, "negate")); } @@ -749,8 +825,8 @@ function shl(a: Wide, b: number | Limbs, bits: number, signed: boolean): Wide { const x = limbs(a, bits, signed); if (bits !== 64) return one(box(exact(x) << BigInt(n), bits, signed)); if (n === 0) return one(x); - if (n < 32) return one(halves(high((x.hi << n) | (x.lo >>> (32 - n)), signed), (x.lo << n) >>> 0)); - return one(halves(high(x.lo << (n - 32), signed), 0)); + if (n < 32) return join(high((x.hi << n) | (x.lo >>> (32 - n)), signed), (x.lo << n) >>> 0); + return join(high(x.lo << (n - 32), signed), 0); } function shr(a: Wide, b: number | Limbs, bits: number, signed: boolean): Wide { @@ -759,11 +835,11 @@ function shr(a: Wide, b: number | Limbs, bits: number, signed: boolean): Wide { if (bits !== 64) return one(box((signed ? exact(a) : BigInt.asUintN(bits, exact(a))) >> BigInt(n), bits, signed)); if (n === 0) return one(a); if (signed) { - if (n < 32) return one(halves(a.hi >> n, ((a.lo >>> n) | (a.hi << (32 - n))) >>> 0)); - return one(halves(a.hi >> 31, (a.hi >> (n - 32)) >>> 0)); + if (n < 32) return join(a.hi >> n, ((a.lo >>> n) | (a.hi << (32 - n))) >>> 0); + return join(a.hi >> 31, (a.hi >> (n - 32)) >>> 0); } - if (n < 32) return one(halves(a.hi >>> n, ((a.lo >>> n) | (a.hi << (32 - n))) >>> 0)); - return one(halves(0, a.hi >>> (n - 32))); + if (n < 32) return join(a.hi >>> n, ((a.lo >>> n) | (a.hi << (32 - n))) >>> 0); + return join(0, a.hi >>> (n - 32)); } // The bitwise operators. On two safe integers, a type's own computes them a 32-bit half @@ -785,32 +861,32 @@ function wordXor(a: number, b: number): number { function and(a: Wide, b: Wide, bits: number, signed: boolean): Wide { const x = limbs(a, bits, signed); const y = limbs(b, bits, signed); - if (bits === 64) return one(halves(high(x.hi & y.hi, signed), (x.lo & y.lo) >>> 0)); + if (bits === 64) return join(high(x.hi & y.hi, signed), (x.lo & y.lo) >>> 0); return one(box(exact(x) & exact(y), bits, signed)); } function or(a: Wide, b: Wide, bits: number, signed: boolean): Wide { const x = limbs(a, bits, signed); const y = limbs(b, bits, signed); - if (bits === 64) return one(halves(high(x.hi | y.hi, signed), (x.lo | y.lo) >>> 0)); + if (bits === 64) return join(high(x.hi | y.hi, signed), (x.lo | y.lo) >>> 0); return one(box(exact(x) | exact(y), bits, signed)); } function xor(a: Wide, b: Wide, bits: number, signed: boolean): Wide { const x = limbs(a, bits, signed); const y = limbs(b, bits, signed); - if (bits === 64) return one(halves(high(x.hi ^ y.hi, signed), (x.lo ^ y.lo) >>> 0)); + if (bits === 64) return join(high(x.hi ^ y.hi, signed), (x.lo ^ y.lo) >>> 0); return one(box(exact(x) ^ exact(y), bits, signed)); } function not(a: Wide, bits: number, signed: boolean): Wide { if (signed && typeof a === "number" && a !== MAX_SAFE) return -a - 1; const x = limbs(a, bits, signed); - if (bits === 64) return one(halves(high(~x.hi, signed), ~x.lo >>> 0)); + if (bits === 64) return join(high(~x.hi, signed), ~x.lo >>> 0); return one(box(~exact(x), bits, signed)); } -/** Two values' sum, difference, or product, exactly. */ +/** Two values' sum or difference, exactly. */ function sum(a: Wide, b: Wide, bits: number, signed: boolean): bigint { return exact(limbs(a, bits, signed)) + exact(limbs(b, bits, signed)); } @@ -819,10 +895,6 @@ function difference(a: Wide, b: Wide, bits: number, signed: boolean): bigint { return exact(limbs(a, bits, signed)) - exact(limbs(b, bits, signed)); } -function product(a: Wide, b: Wide, bits: number, signed: boolean): bigint { - return exact(limbs(a, bits, signed)) * exact(limbs(b, bits, signed)); -} - /** `v` if it is in range, or `undefined`. */ function checkedOp(v: bigint, bits: number, signed: boolean): Wide | undefined { return fitsBig(v, bits, signed) ? one(box(v, bits, signed)) : undefined; @@ -839,7 +911,7 @@ function wrappingAdd(a: Wide, b: Wide, bits: number, signed: boolean): Wide { const y = limbs(b, bits, signed); if (bits !== 64) return one(box(exact(x) + exact(y), bits, signed)); const lo = x.lo + y.lo; - return one(halves(high(x.hi + y.hi + (lo >= TWO32 ? 1 : 0), signed), lo >>> 0)); + return join(high(x.hi + y.hi + (lo >= TWO32 ? 1 : 0), signed), lo >>> 0); } function wrappingSub(a: Wide, b: Wide, bits: number, signed: boolean): Wide { @@ -847,7 +919,7 @@ function wrappingSub(a: Wide, b: Wide, bits: number, signed: boolean): Wide { const y = limbs(b, bits, signed); if (bits !== 64) return one(box(exact(x) - exact(y), bits, signed)); const lo = x.lo - y.lo; - return one(halves(high(x.hi - y.hi - (lo < 0 ? 1 : 0), signed), lo >>> 0)); + return join(high(x.hi - y.hi - (lo < 0 ? 1 : 0), signed), lo >>> 0); } /** The number of leading ones of `v`'s bits. */ @@ -874,7 +946,7 @@ function leadingOnes(a: Wide, bits: number, signed: boolean): number { function fromBeBytes(b: Uint8Array, bits: number, signed: boolean): Wide { if (bits === 64) { const hi = (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3]; - return one(halves(high(hi, signed), ((b[4] << 24) | (b[5] << 16) | (b[6] << 8) | b[7]) >>> 0)); + return join(high(hi, signed), ((b[4] << 24) | (b[5] << 16) | (b[6] << 8) | b[7]) >>> 0); } // A 32-bit word at a time: one bigint step per word, not per byte. let value = 0n; @@ -928,7 +1000,7 @@ function of(value: number | bigint, bits: number, signed: boolean): Wide { /** `value as T`, from any integer. */ function cast(value: number | Limbs, bits: number, signed: boolean): Wide { if (typeof value === "number") return fits(value, signed) ? value : one(limbs(value, bits, signed)); - if (bits === 64) return one(halves(high("w1" in value ? value.w1 : value.hi, signed), value.lo)); + if (bits === 64) return join(high("w1" in value ? value.w1 : value.hi, signed), value.lo); return one(box(exact(value), bits, signed)); } @@ -988,7 +1060,7 @@ export const u64CheckedAdd = (a: u64, b: u64): u64 | undefined => checkedOp(sum( /** `u64`'s `checked_sub`: `a - b`, or `undefined` on overflow. */ export const u64CheckedSub = (a: u64, b: u64): u64 | undefined => checkedOp(difference(a, b, 64, false), 64, false) as u64 | undefined; /** `u64`'s `checked_mul`: `a * b`, or `undefined` on overflow. */ -export const u64CheckedMul = (a: u64, b: u64): u64 | undefined => checkedOp(product(a, b, 64, false), 64, false) as u64 | undefined; +export const u64CheckedMul = (a: u64, b: u64): u64 | undefined => product(a, b, 64, false) as u64 | undefined; /** `u64`'s `saturating_add`: `a + b`, clamped to the type's range. */ export const u64SaturatingAdd = (a: u64, b: u64): u64 => saturate(sum(a, b, 64, false), 64, false) as u64; /** `u64`'s `saturating_sub`: `a - b`, clamped to the type's range. */ @@ -1019,6 +1091,8 @@ export const u64Of = (value: number | bigint): u64 => of(value, 64, false) as u6 export const u64Cast = (value: number | Limbs): u64 => (typeof value === "number" && fits(value, false) ? value : cast(value, 64, false)) as u64; /** The low 32 bits, as a uint32. */ export const u64Low = (a: u64): number => low(a); +/** `(hi as u64) << 32 | lo as u64`: a `u64` from its high and low 32 bits. */ +export const u64FromHalves = (hi: u32, lo: u32): u64 => join(hi, lo) as u64; /** `u64`'s `a == b`. */ export const u64Eq = (a: u64, b: u64): boolean => eq(a, b); /** `u64`'s `a != b`. */ @@ -1076,7 +1150,7 @@ export const i64CheckedAdd = (a: i64, b: i64): i64 | undefined => checkedOp(sum( /** `i64`'s `checked_sub`: `a - b`, or `undefined` on overflow. */ export const i64CheckedSub = (a: i64, b: i64): i64 | undefined => checkedOp(difference(a, b, 64, true), 64, true) as i64 | undefined; /** `i64`'s `checked_mul`: `a * b`, or `undefined` on overflow. */ -export const i64CheckedMul = (a: i64, b: i64): i64 | undefined => checkedOp(product(a, b, 64, true), 64, true) as i64 | undefined; +export const i64CheckedMul = (a: i64, b: i64): i64 | undefined => product(a, b, 64, true) as i64 | undefined; /** `i64`'s `saturating_add`: `a + b`, clamped to the type's range. */ export const i64SaturatingAdd = (a: i64, b: i64): i64 => saturate(sum(a, b, 64, true), 64, true) as i64; /** `i64`'s `saturating_sub`: `a - b`, clamped to the type's range. */ @@ -1162,7 +1236,7 @@ export const u128CheckedAdd = (a: u128, b: u128): u128 | undefined => checkedOp( /** `u128`'s `checked_sub`: `a - b`, or `undefined` on overflow. */ export const u128CheckedSub = (a: u128, b: u128): u128 | undefined => checkedOp(difference(a, b, 128, false), 128, false) as u128 | undefined; /** `u128`'s `checked_mul`: `a * b`, or `undefined` on overflow. */ -export const u128CheckedMul = (a: u128, b: u128): u128 | undefined => checkedOp(product(a, b, 128, false), 128, false) as u128 | undefined; +export const u128CheckedMul = (a: u128, b: u128): u128 | undefined => product(a, b, 128, false) as u128 | undefined; /** `u128`'s `saturating_add`: `a + b`, clamped to the type's range. */ export const u128SaturatingAdd = (a: u128, b: u128): u128 => saturate(sum(a, b, 128, false), 128, false) as u128; /** `u128`'s `saturating_sub`: `a - b`, clamped to the type's range. */ @@ -1250,7 +1324,7 @@ export const i128CheckedAdd = (a: i128, b: i128): i128 | undefined => checkedOp( /** `i128`'s `checked_sub`: `a - b`, or `undefined` on overflow. */ export const i128CheckedSub = (a: i128, b: i128): i128 | undefined => checkedOp(difference(a, b, 128, true), 128, true) as i128 | undefined; /** `i128`'s `checked_mul`: `a * b`, or `undefined` on overflow. */ -export const i128CheckedMul = (a: i128, b: i128): i128 | undefined => checkedOp(product(a, b, 128, true), 128, true) as i128 | undefined; +export const i128CheckedMul = (a: i128, b: i128): i128 | undefined => product(a, b, 128, true) as i128 | undefined; /** `i128`'s `saturating_add`: `a + b`, clamped to the type's range. */ export const i128SaturatingAdd = (a: i128, b: i128): i128 => saturate(sum(a, b, 128, true), 128, true) as i128; /** `i128`'s `saturating_sub`: `a - b`, clamped to the type's range. */ diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index e58761d49..04d48a18d 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -184,6 +184,10 @@ pub struct Fx<'m, 'b, 'a, 'tcx> { range_nexts: FxHashSet, /// Their names, and their flags' names, which a switch on their variant tests. range_flags: FxHashMap, + /// The halves a `|` joins into a `u64`, by the local of the shift that is its left side. + halves: FxHashMap, &'m Operand<'tcx>)>, + /// Temporaries of those joins, whose assignments go unlowered. + joined: FxHashSet, } impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { @@ -226,6 +230,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { next_names: FxHashSet::default(), range_nexts: FxHashSet::default(), range_flags: FxHashMap::default(), + halves: FxHashMap::default(), + joined: FxHashSet::default(), }; fx.analyze(); fx @@ -319,6 +325,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } self.find_next_results(); + self.find_halves(); for local in mir.local_decls.indices() { let ty = mir.local_decls[local].ty; let slot = if self.zero_sized(ty) { @@ -642,6 +649,64 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } + /// Each `(hi as u64) << 32 | lo as u64` of halves of at most 32 bits, as moq's + /// `from_halves` writes it, which lowers to `rt.u64FromHalves(hi, lo)`: no shift that + /// boxes limbs past 2^53, and no `|` that unboxes them. Its shift and casts go + /// unlowered, so it reads the halves where the `|` is, which takes temporaries read + /// once, of halves nothing assigns again. + fn find_halves(&mut self) { + let mir: &'m mir::Body<'tcx> = self.mir; + let tcx = self.tcx; + let temp = |op: &Operand<'tcx>| match op { + Operand::Move(p) => p.as_local().filter(|&l| self.defs[l] == 1 && self.uses[l] == 1), + _ => None, + }; + // A temporary's cast to `u64` from at most 32 unsigned bits (`usize` is 32), and + // what it casts. + let half = |op: &Operand<'tcx>| { + let local = temp(op)?; + let Some(Rvalue::Cast(mir::CastKind::IntToInt, from, _)) = self.def_rvalue(local) else { + return None; + }; + let narrow = + matches!(from.ty(&mir.local_decls, tcx).kind(), ty::Uint(u) if u.bit_width().is_none_or(|b| b <= 32)); + let fixed = match from { + Operand::Constant(_) => true, + Operand::Copy(p) | Operand::Move(p) => { + p.as_local().is_some_and(|l| !self.mutated[l]) && self.stable(*p) + } + _ => false, + }; + (narrow && fixed).then_some((local, from)) + }; + let mut found = Vec::new(); + for data in mir.basic_blocks.iter() { + for stmt in &data.statements { + let StatementKind::Assign(assign) = &stmt.kind else { + continue; + }; + let Rvalue::BinaryOp(mir::BinOp::BitOr, ops) = &assign.1 else { + continue; + }; + let Some(shift) = temp(&ops.0).filter(|_| ops.0.ty(&mir.local_decls, tcx) == tcx.types.u64) else { + continue; + }; + let Some(Rvalue::BinaryOp(mir::BinOp::Shl, shifted)) = self.def_rvalue(shift) else { + continue; + }; + if self.const_int(&shifted.1) == Some(32) + && let (Some(hi), Some(lo)) = (half(&shifted.0), half(&ops.1)) + { + found.push((shift, hi, lo)); + } + } + } + for (shift, (cast_hi, hi), (cast_lo, lo)) in found { + self.halves.insert(shift, (hi, lo)); + self.joined.extend([shift, cast_hi, cast_lo]); + } + } + /// The rvalue a local's one assignment by a statement assigns. fn def_rvalue(&self, local: Local) -> Option<&'m Rvalue<'tcx>> { let (bb, i) = self.def_at[local]?; @@ -1280,6 +1345,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { fn assign(&mut self, place: Place<'tcx>, rvalue: &Rvalue<'tcx>, span: Span, out: &mut Vec) { if let Some(local) = place.as_local() { + if self.joined.contains(&local) { + return; + } match self.slots[local] { Slot::Alias(_) => { let target = match rvalue { diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index 0bfe9b86d..13c77a96e 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -50,6 +50,14 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { Rvalue::ThreadLocalRef(_) => self.err(span, "thread locals are not supported"), Rvalue::WrapUnsafeBinder(..) => self.err(span, "unsafe binders are not supported"), Rvalue::Cast(kind, op, to) => self.cast(*kind, op, *to, span, out), + Rvalue::BinaryOp(BinOp::BitOr, ops) + if let Operand::Move(p) = &ops.0 + && let Some(&(hi, lo)) = p.as_local().and_then(|l| self.halves.get(&l)) => + { + let hi = self.half(hi, span, out); + let lo = self.half(lo, span, out); + Expr::rt("u64FromHalves", vec![hi, lo]) + } Rvalue::BinaryOp(op, ops) => { let (l, r) = &**ops; let lty = l.ty(&self.mir.local_decls, tcx); @@ -99,6 +107,17 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { }) } + /// An unsigned integer of at most 32 bits, as a `u32`. + fn half(&mut self, op: &Operand<'tcx>, span: Span, out: &mut Vec) -> Expr { + let from = op.ty(&self.mir.local_decls, self.tcx); + let expr = self.operand(op, span, out); + let value = num::Operand { + expr, + value: self.const_int(op), + }; + num::cast(self.b, value, from, self.tcx.types.u32, span) + } + /// The integer an operand has, if it is a constant one. pub(super) fn const_int(&self, op: &Operand<'tcx>) -> Option { let Operand::Constant(c) = op else { diff --git a/ts/tests/differential.ts b/ts/tests/differential.ts index 8da73d7ee..208b377b4 100644 --- a/ts/tests/differential.ts +++ b/ts/tests/differential.ts @@ -97,12 +97,20 @@ for (let op = 0; op < 8; op++) { if (wideArg === "wide") { // 2^k - 1, 2^k, and 2^k + 1 for each k where a limb, a safe number, or a sign ends, // and values without that structure, whose quotients and remainders are not round. - const edges = new Set([1_000_000n, 0x9e3779b97f4a7c15n, 0x0123456789abcdefn, 0xfedcba9876543210n]); + const edges = new Set([ + 1_000_000n, + 0x9e3779b97f4a7c15n, + 0x0123456789abcdefn, + 0xfedcba9876543210n, + // Safe integers whose halves carry when multiplied, and a negative one. + 0x1d3c5b7a9f8e6dn, + -0x1b2a3c4d5e6f71n & 0xffffffffffffffffn, + ]); for (const k of [0n, 1n, 16n, 21n, 31n, 32n, 33n, 52n, 53n, 54n, 63n, 64n]) { for (const delta of [-1n, 0n, 1n]) edges.add(((1n << k) + delta) & 0xffffffffffffffffn); } - // Small negative numbers, and where negative safe numbers end, as signed values. - for (const k of [1n, 53n]) { + // Small negative numbers, -2^32, and where negative safe numbers end, as signed values. + for (const k of [1n, 32n, 53n]) { for (const delta of [-1n, 0n, 1n]) edges.add((-(1n << k) + delta) & 0xffffffffffffffffn); } const values = [...edges]; @@ -127,7 +135,16 @@ if (wideArg === "wide") { } // Negating an `i64` and an `i128`. cases.push(Uint8Array.of(12, 3, ...be(x)), Uint8Array.of(12, 4, ...be(x), ...be(y))); + // `x * y` and `x.checked_mul(y)` at 128 bits, extended in each type's sign: a product + // of two numbers, past 2^53, multiplies their halves. + const signs = (v: bigint) => (v >> 63n === 1n ? 0xffffffffffffffffn : 0n); + for (const kind of [2, 13]) { + cases.push(Uint8Array.of(4, kind, ...be(0n), ...be(x), ...be(0n), ...be(y))); + cases.push(Uint8Array.of(10, kind, ...be(signs(x)), ...be(x), ...be(signs(y)), ...be(y))); + } } + // Conversions, and halves joined back. + cases.push(Uint8Array.of(14, 0, ...be(x), ...be(x))); for (const y of [0n, 1n, 1n << 32n, 1n << 63n, 0xffffffffffffffffn]) { for (const from of [3, 4, 9, 10]) { // A cast to every type, and every format spec. From e31eca9f14146552eb90633c8681e542271f912b Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 25 Oct 2026 18:57:37 -0700 Subject: [PATCH 3/5] docs(ts): the halves join and the timestamp workloads Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- ts/README.md | 14 +++++++++----- ts/bench/main.ts | 3 ++- ts/runtime/rt/int.ts | 5 +++-- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/ts/README.md b/ts/README.md index 0b84b8808..7d807418c 100644 --- a/ts/README.md +++ b/ts/README.md @@ -94,7 +94,8 @@ object of 32-bit limbs, `{ hi, lo }`, with `w2` and `w1` between them at 128 bit `hi` signed in a signed type. Each value has one form, so `x === 0` is exact; a caller makes one past 2^53 with `rt.u64Of(18446744073709551615n)`. Its other operators and comparisons are runtime calls, `rt.u64Add(a, b)` and `rt.u64Lt(a, b)`, and `x as u32` -is `rt.u64Low(x)`. +is `rt.u64Low(x)`. From MIR, `((hi as u64) << 32) | lo as u64` of halves of at most 32 +bits is one call, `rt.u64FromHalves(hi, lo)`. `format!`, `write!`, `panic!`, `assert!`, and the other macros of `format_args!` translate, as do `Display` and `Debug` impls, derived and thiserror's included. The @@ -285,7 +286,8 @@ built natively for wasm32 and run beside its translation on the same inputs by that log what each adaptor reads. Its differential test runs through `caller.ts`, a hand-written caller that also prints a `printable` error nothing translated prints, and adds every 64- and 128-bit case over each pair of values next to a power of two, - where the runtime switches between numbers and limbs, and its limbs carry and borrow. + where the runtime switches between numbers and limbs, and its limbs carry and borrow, + with products of those values at 128 bits and their halves joined back. `brands.ts`, another caller, mixes integer types where `tsc` must refuse them. - `task` trims moq's kio to a channel of `Arc`ed state, waiters, and wakers, under async functions. Its caller is hand-written TS (`tests/task.ts`): a FIFO executor that runs a @@ -312,9 +314,11 @@ nix develop .#bench --command just ts bench # report to target/bench/report.md The codec fixture's `bench::run` holds the cases moq's own TypeScript benchmarks time (`js/net/bench/varint.ts` and `lite-varint.ts`), at the pinned moq revision, the same frame headers decoded as they arrive a few bytes at a time, which prices a decode that -comes up `Short` and retries, and iterator chains over bytes. Each runs four ways: -natively, as wasm32 at moq-wasm's size-optimized profile, hand-written (moq's `js/net` in `bench/moq.ts`, and ES iterator -helpers in `bench/iter.ts`), and translated; every route's output must match +comes up `Short` and retries, iterator chains over bytes, and timestamps converted between +timescales as moq-net's `Timestamp::convert` does, whose products pass 2^53. Each runs four ways: +natively, as wasm32 at moq-wasm's size-optimized profile, hand-written (moq's `js/net` in `bench/moq.ts`, ES iterator +helpers in `bench/iter.ts`, and `bigint` in `bench/rescale.ts`, as moq's `js/hang` +converts timescales), and translated; every route's output must match native Rust's first. The JS routes run in Node, Bun, and Chrome, with the WASM route's copies across the boundary timed apart from its compute, and an A/A copy of the translation to show the noise. Each round runs the JS routes and workloads in a new diff --git a/ts/bench/main.ts b/ts/bench/main.ts index 3270435ea..921f6a356 100644 --- a/ts/bench/main.ts +++ b/ts/bench/main.ts @@ -312,7 +312,8 @@ function render(): string { "Rust at moq-wasm's size-optimized profile, run with its input already in memory;", "copying the input in and the output out are timed apart. `hand-written` is moq's", "`js/net`, called as its own benchmarks call it, and for `iter/` the same chain with ES", - "iterator helpers (`bench/iter.ts`). `A/A` is the translation loaded a second time: its", + "iterator helpers (`bench/iter.ts`), and for `time/` `bigint`, as moq's `js/hang` converts", + "timescales (`bench/rescale.ts`). `A/A` is the translation loaded a second time: its", "gap from `translated` is the noise. A `reads` decode is the frame headers above as they", "arrive that many bytes at a time, so a header cut by a read comes up short and is", "decoded again on the next: its gap from the whole decode is the error path's price.", diff --git a/ts/runtime/rt/int.ts b/ts/runtime/rt/int.ts index 331f7ff6d..a3930ec15 100644 --- a/ts/runtime/rt/int.ts +++ b/ts/runtime/rt/int.ts @@ -571,8 +571,9 @@ export const isizeStep: Step = i32Step as never; // width and sign, which each type's own passes as literals. A type's own takes the // number path itself where it is hot, small enough for a JIT to inline: through the // shared function alone, V8 took up to 1.7x as long on the codec's frames. 64-bit limbs -// compute on their halves where that is several times faster than bigints; the rest -// goes through bigints. +// compute on their halves where that is several times faster than bigints, reading a +// number's halves without boxing it, as does a product of two numbers at 128 bits; the +// rest goes through bigints. type Wide = number | Limbs; From 174146158933d996cb50d79b40439ca8ac5c331a Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 25 Oct 2026 19:19:42 -0700 Subject: [PATCH 4/5] chore(quest): finish ts-wide-fast, plan the rest of the wide runtime off bigint Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/README.md | 2 +- quest/m2/ts-wide-bigint.md | 26 ++++++++++++++++++++++++++ quest/m2/ts-wide-fast.md | 22 ---------------------- ts/README.md | 22 ++++++++++++++-------- 4 files changed, 41 insertions(+), 31 deletions(-) create mode 100644 quest/m2/ts-wide-bigint.md delete mode 100644 quest/m2/ts-wide-fast.md diff --git a/quest/m2/README.md b/quest/m2/README.md index 10b4b227a..5caad5ec3 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -23,7 +23,7 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); - [Lower bodies from MIR](/quest/m2/ts-mir.md) - the MIR spike's prototype becomes the only lowering, and the THIR one goes - [Cheaper byte slices](/quest/m2/ts-byte-views.md) - splitting a `&[u8]` stops making a `Uint8Array` view per split -- [Wide-integer fast paths](/quest/m2/ts-wide-fast.md) - a fused `from_halves` and an unboxed limb product, kept only if measured faster +- [Wide-integer runtime off bigint](/quest/m2/ts-wide-bigint.md) - checked sums, 128-bit quotients, and comparisons with numbers stop going through `bigint`, kept only if measured faster - [Drop in the TypeScript translator](/quest/m2/ts-drop.md) - every value that drops in moq-net and kio drops where Rust drops it - [Async in the TypeScript translator](/quest/m2/ts-async.md) - moq-net's and kio's async code translates with Rust's lazy futures - [Shared ownership](/quest/m2/ts-shared.md) - `Arc`/`Rc`/`Weak` keep exact counts, and locks and atomics become plain values diff --git a/quest/m2/ts-wide-bigint.md b/quest/m2/ts-wide-bigint.md new file mode 100644 index 000000000..89c4869d1 --- /dev/null +++ b/quest/m2/ts-wide-bigint.md @@ -0,0 +1,26 @@ +# [M] Wide-integer runtime off bigint + +## Goal + +[rust2-ts](/ts/README.md)'s 64- and 128-bit runtime stops going through `bigint` on the +paths moq-net's code reaches, each change kept only if the +[TS benchmark](/ts/README.md#bench) measures it faster, with the wide differential sweep +still passing. + +## Plan + +The `time/u128` workloads, moq-net's `Timestamp::convert`, still take 8-12x the +hand-written `bigint` route's time after products moved onto halves. What remains there, +and elsewhere: + +- `u128` and `i128` division and remainder of limbs by a number go through `bigint`, + where a long division by a 32-bit divisor, as `u64`'s, would not. +- Comparing a number with limbs boxes the number into limbs, though each value has one + form: limbs lie past every number, on the side their sign says. +- `checked_add`, `checked_sub`, and the saturating ones go through `bigint` for every + value, numbers included; moq-net's `Timestamp::checked_add` is one. + +Measure each against main's translation with `just ts bench --route`, and profile the +`time/` workloads first: what dominates may not be on this list. + +Public API: none; the runtime's internals. diff --git a/quest/m2/ts-wide-fast.md b/quest/m2/ts-wide-fast.md deleted file mode 100644 index 97663628f..000000000 --- a/quest/m2/ts-wide-fast.md +++ /dev/null @@ -1,22 +0,0 @@ -# [S] Wide-integer fast paths - -## Goal - -Two fast paths for [rust2-ts](/ts/README.md)'s 64-bit integers (numbers while -safe, limbs past 2^53, per its [design](/ts/README.md#design)), each kept only if -the [TS benchmark](/ts/README.md#bench) measures it faster, with the wide -differential sweep still passing. - -## Plan - -From [#26](https://github.com/kixelated/rust2/pull/26)'s follow-ups: - -- A fused `from_halves`: Chrome's 8-byte varint decode is 25-45% slower than - `bigint`'s, since it goes through `rt.u64Or(rt.u64Shl(hi, 32), lo)`. -- A product of two numbers past 2^53 boxes both factors into limbs before - multiplying; multiplying their halves directly would cut the allocations - `rescale` measures. - -`just ts bench --route` times each against main's translation in one run. - -Public API: none; the runtime's internals. diff --git a/ts/README.md b/ts/README.md index 7d807418c..3d78cd45a 100644 --- a/ts/README.md +++ b/ts/README.md @@ -172,14 +172,20 @@ they need. numbers in locals, fields, and arguments. It ties unboxed halves on the codec and beats `bigint` there in Node, Bun, and Chrome: varint encode 13-65% faster, frame decode 8-32%, and message decode 22-31%, though Chrome's 8-byte varint decode is - 25-45% slower. A loop of sums and comparisons past 2^32 measured 2-6x faster. Limbs - for every value allocate an object each, which costs what a `bigint` does in V8, so - they lost decode; unboxed halves would lower every value to two. Past 2^53 an - operation allocates limbs: a product past 2^53 divided back down is 1.5-1.9x slower - than `bigint`, and 128-bit arithmetic there goes through `bigint` inside the runtime. - The runtime adds 6 KB to the codec's bundle, 2 KB gzipped. Brands tell `u64` from - `i64` and `u32` from `usize` at no cost, since TypeScript erases them; a required - brand would cast every literal, so a plain number passes for any type. + 25-45% slower; joining a varint's halves in one call, `rt.u64FromHalves`, makes that + decode 1.05-1.2x faster in Chrome. A loop of sums and comparisons past 2^32 measured + 2-6x faster. Limbs for every value allocate an object each, which costs what a + `bigint` does in V8, so they lost decode; unboxed halves would lower every value to + two. Past 2^53 an operation allocates limbs, and 128-bit arithmetic goes through + `bigint` inside the runtime, but a product multiplies 32-bit halves without boxing + either factor, at 128 bits when both are numbers. Converting timestamps between + timescales, products past 2^53 divided back down, measured 2.1-3.1x faster that way + than through boxed factors in `u64`, and 1.6-1.7x in `u128` as moq-net converts them: + 1.4-2.1x `bigint`'s time in `u64`, and 8-12x in `u128`, whose division and + comparisons still go through `bigint`. The runtime adds 6 KB to the codec's bundle, 2 + KB gzipped. Brands tell `u64` from `i64` and `u32` from `usize` at no cost, since + TypeScript erases them; a required brand would cast every literal, so a plain number + passes for any type. - A struct is a plain object, and each function of a type, trait impls included, is its own function in the type's module, so a caller's bundler drops every one it never calls: no bundler drops a class's unused methods or an object's unused properties. A struct that From ffaab043a5fd20ae1db54b89287b26664f34bbfb Mon Sep 17 00:00:00 2001 From: Luke Curley <432854+kixelated@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:32:15 -0700 Subject: [PATCH 5/5] chore(quest): measure bigint for u128 and i128 in ts-wide-bigint Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0115AT2ue6x9cT5e5J9SZtCn --- quest/m2/ts-wide-bigint.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/quest/m2/ts-wide-bigint.md b/quest/m2/ts-wide-bigint.md index 89c4869d1..1da7cf1f0 100644 --- a/quest/m2/ts-wide-bigint.md +++ b/quest/m2/ts-wide-bigint.md @@ -9,6 +9,11 @@ still passing. ## Plan +Decided with the maintainer on 2026-10-25: the quest also measures `u128` and `i128` as +native JS `bigint`s instead of numbers and limbs, on the codec and timestamp workloads, +bundle size included, and keeps whichever wins. `u64` and `i64` stay numbers below 2^53, +since they already come near `bigint` there. + The `time/u128` workloads, moq-net's `Timestamp::convert`, still take 8-12x the hand-written `bigint` route's time after products moved onto halves. What remains there, and elsewhere: