Skip to content

Commit be65e21

Browse files
hearnadamkommander
authored andcommitted
perf(rust): BigInt in the value word under 31 bits, in its heap slot up to 128
Every BigInt result was a heap slot, a box, a digit vector and a hash. Under 31 bits it is now in the id of its Value::Big, with no object; up to 128 bits it is in place in one heap slot, with machine arithmetic; larger, the slot holds a boxed num_bigint as before. Each value has exactly one form, so equality and Map keys still compare ids. JavaScriptCore has only the heap form (its inline BigInt32 was never enabled, and was removed in 2026). 64-bit FNV hash, 100k rounds: 640M to 409M instructions, 44.6 to about 17 ms. Checked against Bun on 8,385 results across the 31-, 64- and 128-bit boundaries.
1 parent 64eeda9 commit be65e21

7 files changed

Lines changed: 225 additions & 38 deletions

File tree

‎rust/crates/psychoscript/src/builtins/bigint.rs‎

Lines changed: 213 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,23 @@
11
//! BigInt: the reference's `bigintGlobal` (`src/stdlib/number.ts`), its BigInt operators
22
//! (`src/runtime/operations.ts`) and the size cap (`src/runtime/limits.ts`).
33
//!
4-
//! A BigInt is a `Kind::BigInt` heap object, which `Value::Big` refers to and programs never see as an object. The
5-
//! interner gives each value one object, so `===`, `Object.is` and Map keys compare ids. It is a weak table, as the
6-
//! strings' interner is: the sweep drops a freed BigInt from it, and one it gives out while a cycle runs survives the
7-
//! cycle (`Vm::gc_shade_big`).
4+
//! A BigInt has one of three forms, by its size, and each value has exactly one, so `===`, `Object.is` and Map keys
5+
//! compare the ids of `Value::Big`:
6+
//! - under 31 bits, it is in the id itself (`INLINE`): no object, nothing to collect. Counters, small constants and
7+
//! `BigInt(i & 255)` are these.
8+
//! - up to 128 bits, a `Kind::BigInt` heap object holding the integer in place (`BigNum::Small`), with machine
9+
//! arithmetic: no allocation beyond the heap slot, which a collected one gives back. 64-bit hashes and ids are these.
10+
//! - larger, the same object holding a boxed `num_bigint::BigInt`.
11+
//!
12+
//! JavaScriptCore, which Bun runs on, has only the heap form: every BigInt is one cell with its digits in it (its
13+
//! inline 32-bit form was never enabled, and was removed in 2026). The middle form here is that cell; the first goes
14+
//! further.
15+
//!
16+
//! Programs never see the heap object as an object. The interner gives each heap value one object. It is a weak table,
17+
//! as the strings' interner is: the sweep drops a freed BigInt from it, and one it gives out while a cycle runs
18+
//! survives the cycle (`Vm::gc_shade_big`).
819
20+
use std::borrow::Cow;
921
use std::cmp::Ordering;
1022

1123
use num_bigint::BigInt;
@@ -37,10 +49,73 @@ pub struct Interned {
3749
collided: Vec<(u64, Id)>,
3850
}
3951

40-
fn hash_of(n: &BigInt) -> u64 {
52+
/// Set in the id of a `Value::Big` that holds its integer, of under 31 bits, in its other bits. Heap ids stay far
53+
/// below it (`MAX_OBJECTS`).
54+
pub const INLINE: Id = 1 << 31;
55+
const INLINE_MIN: i128 = -(1 << 30);
56+
const INLINE_MAX: i128 = (1 << 30) - 1;
57+
58+
/// Whether `id` is a heap object's, which the collector traces.
59+
#[inline(always)]
60+
pub fn on_heap(id: Id) -> bool {
61+
id & INLINE == 0
62+
}
63+
64+
#[inline(always)]
65+
fn inline_of(id: Id) -> Option<i128> {
66+
(id & INLINE != 0).then_some((((id << 1) as i32) >> 1) as i128)
67+
}
68+
69+
/// A heap BigInt's integer: in place up to 128 bits (as two words, so it aligns as the rest of an object does), else
70+
/// boxed. One that fits in place is never boxed, and one that fits in an id is never on the heap.
71+
pub enum BigNum {
72+
Small([u64; 2]),
73+
Large(Box<BigInt>),
74+
}
75+
76+
impl BigNum {
77+
/// The form of `n`, or `None` for one that belongs in an id.
78+
pub(crate) fn heap_form(n: BigInt) -> Option<BigNum> {
79+
match n.to_i128() {
80+
Some(s) if (INLINE_MIN..=INLINE_MAX).contains(&s) => None,
81+
Some(s) => Some(BigNum::small(s)),
82+
None => Some(BigNum::Large(Box::new(n))),
83+
}
84+
}
85+
86+
fn small(n: i128) -> BigNum {
87+
BigNum::Small([n as u64, (n >> 64) as u64])
88+
}
89+
90+
fn get(&self) -> BigRef<'_> {
91+
match self {
92+
BigNum::Small([lo, hi]) => BigRef::Small(((*hi as i128) << 64) | *lo as i128),
93+
BigNum::Large(n) => BigRef::Large(n),
94+
}
95+
}
96+
97+
pub(crate) fn to_big(&self) -> BigInt {
98+
match self.get() {
99+
BigRef::Small(s) => BigInt::from(s),
100+
BigRef::Large(n) => n.clone(),
101+
}
102+
}
103+
}
104+
105+
/// A BigInt's integer, read without copying it.
106+
#[derive(Clone, Copy, PartialEq)]
107+
pub(crate) enum BigRef<'a> {
108+
Small(i128),
109+
Large(&'a BigInt),
110+
}
111+
112+
fn hash_of(n: BigRef) -> u64 {
41113
use std::hash::{Hash, Hasher};
42114
let mut h = FxHasher::default();
43-
n.hash(&mut h);
115+
match n {
116+
BigRef::Small(s) => s.hash(&mut h),
117+
BigRef::Large(n) => n.hash(&mut h),
118+
}
44119
h.finish()
45120
}
46121

@@ -55,8 +130,8 @@ impl Interned {
55130
}
56131

57132
/// Drops the freed BigInt `id` of value `n`.
58-
pub(crate) fn forget(&mut self, id: Id, n: &BigInt) {
59-
let h = hash_of(n);
133+
pub(crate) fn forget(&mut self, id: Id, n: &BigNum) {
134+
let h = hash_of(n.get());
60135
if self.by_hash.get(&h) == Some(&id) {
61136
self.by_hash.remove(&h);
62137
if let Some(i) = self.collided.iter().position(|e| e.0 == h) {
@@ -76,37 +151,80 @@ enum Fail {
76151
}
77152

78153
impl Vm {
79-
/// The value of BigInt `id`.
80-
pub fn big(&self, id: Id) -> &BigInt {
154+
/// The integer of BigInt `id`, in whichever form it has.
155+
#[inline]
156+
pub(crate) fn big_ref(&self, id: Id) -> BigRef<'_> {
157+
if let Some(s) = inline_of(id) {
158+
return BigRef::Small(s);
159+
}
81160
match &self.heap[id as usize].kind {
82-
Kind::BigInt(n) => n,
83-
_ => &BigInt::ZERO,
161+
Kind::BigInt(n) => n.get(),
162+
_ => BigRef::Small(0),
84163
}
85164
}
86165

87-
fn find_big(&self, h: u64, n: &BigInt) -> Option<Id> {
166+
/// The integer of BigInt `id` when it is at most 128 bits: the operators' fast path.
167+
#[inline]
168+
fn small_of(&self, id: Id) -> Option<i128> {
169+
match self.big_ref(id) {
170+
BigRef::Small(s) => Some(s),
171+
BigRef::Large(_) => None,
172+
}
173+
}
174+
175+
/// The value of BigInt `id`, for the paths that need the arbitrary-precision form: a copy unless it is one.
176+
pub fn big(&self, id: Id) -> Cow<'_, BigInt> {
177+
match self.big_ref(id) {
178+
BigRef::Small(s) => Cow::Owned(BigInt::from(s)),
179+
BigRef::Large(n) => Cow::Borrowed(n),
180+
}
181+
}
182+
183+
/// Whether BigInt `id` is `0n`.
184+
pub(crate) fn big_is_zero(&self, id: Id) -> bool {
185+
self.big_ref(id) == BigRef::Small(0)
186+
}
187+
188+
fn find_big(&self, h: u64, n: BigRef) -> Option<Id> {
88189
let first = *self.bigints.by_hash.get(&h)?;
89-
if self.big(first) == n {
190+
if self.big_ref(first) == n {
90191
return Some(first);
91192
}
92193
let mut others = self.bigints.collided.iter();
93194
others
94-
.find(|(c, id)| *c == h && self.big(*id) == n)
195+
.find(|(c, id)| *c == h && self.big_ref(*id) == n)
95196
.map(|e| e.1)
96197
}
97198

98-
/// The BigInt `n`, unchecked against the cap.
99-
pub fn big_val(&mut self, n: BigInt) -> Value {
100-
let h = hash_of(&n);
101-
if let Some(id) = self.find_big(h, &n) {
199+
/// The one heap object of `n`, which is in its heap form.
200+
fn heap_big(&mut self, n: BigNum) -> Value {
201+
let h = hash_of(n.get());
202+
if let Some(id) = self.find_big(h, n.get()) {
102203
self.gc_shade_big(id);
103204
return Value::Big(id);
104205
}
105-
let id = self.alloc(Obj::new(None, Kind::BigInt(Box::new(n))));
206+
let id = self.alloc(Obj::new(None, Kind::BigInt(n)));
106207
self.bigints.add(h, id);
107208
Value::Big(id)
108209
}
109210

211+
/// The BigInt `n` of at most 128 bits: in its id when it fits there, which makes no object.
212+
#[inline]
213+
pub fn big_small(&mut self, n: i128) -> Value {
214+
if (INLINE_MIN..=INLINE_MAX).contains(&n) {
215+
return Value::Big(INLINE | (n as u32 & !INLINE));
216+
}
217+
self.heap_big(BigNum::small(n))
218+
}
219+
220+
/// The BigInt `n`, unchecked against the cap.
221+
pub fn big_val(&mut self, n: BigInt) -> Value {
222+
match n.to_i128() {
223+
Some(s) => self.big_small(s),
224+
None => self.heap_big(BigNum::Large(Box::new(n))),
225+
}
226+
}
227+
110228
/// The BigInt `n`, or the RangeError of a value past the cap.
111229
pub fn checked_big(&mut self, n: BigInt) -> Res {
112230
if !fits(&n) {
@@ -119,8 +237,8 @@ impl Vm {
119237
pub(crate) fn intern_restored(&mut self, from: usize) -> bool {
120238
for id in from..self.heap.len() {
121239
if let Kind::BigInt(n) = &self.heap[id].kind {
122-
let h = hash_of(n);
123-
if self.find_big(h, n).is_some() {
240+
let h = hash_of(n.get());
241+
if self.find_big(h, n.get()).is_some() {
124242
return false;
125243
}
126244
self.bigints.add(h, id as Id);
@@ -144,7 +262,12 @@ impl Vm {
144262
let (Value::Big(x), Value::Big(y)) = (*a, *b) else {
145263
return Err(self.type_error(MIX));
146264
};
147-
let r = big_op(op, self.big(x), self.big(y));
265+
if let (Some(a), Some(b)) = (self.small_of(x), self.small_of(y))
266+
&& let Some(r) = small_op(op, a, b)
267+
{
268+
return Ok(self.big_small(r));
269+
}
270+
let r = big_op(op, &self.big(x), &self.big(y));
148271
match r {
149272
Ok(n) => self.checked_big(n),
150273
Err(f) => Err(self.fail(f)),
@@ -155,7 +278,18 @@ impl Vm {
155278
#[cold]
156279
#[inline(never)]
157280
pub(crate) fn big_unary(&mut self, op: u8, id: Id) -> Res {
158-
let x = self.big(id);
281+
if let Some(a) = self.small_of(id) {
282+
let r = match op {
283+
code::NEG => a.checked_neg(),
284+
code::BIT_NOT => Some(!a),
285+
code::INC => a.checked_add(1),
286+
_ => a.checked_sub(1),
287+
};
288+
if let Some(r) = r {
289+
return Ok(self.big_small(r));
290+
}
291+
}
292+
let x = &*self.big(id);
159293
let n = match op {
160294
code::NEG => -x,
161295
code::BIT_NOT => !x,
@@ -175,6 +309,11 @@ impl Vm {
175309
/// How primitives one of which is a BigInt order, by their mathematical values; `None` for NaN or a string that
176310
/// is no integer.
177311
fn big_compare(&mut self, a: &Value, b: &Value) -> Result<Option<Ordering>, Value> {
312+
if let (Value::Big(x), Value::Big(y)) = (*a, *b)
313+
&& let (Some(x), Some(y)) = (self.small_of(x), self.small_of(y))
314+
{
315+
return Ok(Some(x.cmp(&y)));
316+
}
178317
let (x, y) = (self.numeric(a)?, self.numeric(b)?);
179318
Ok(match (x, y) {
180319
(Numeric::Big(x), Numeric::Big(y)) => Some(x.cmp(&y)),
@@ -192,22 +331,25 @@ impl Vm {
192331
/// A comparison operand: a BigInt, a string read as one (StringToBigInt), or ToNumber of anything else.
193332
fn numeric(&mut self, v: &Value) -> Result<Numeric, Value> {
194333
Ok(match v {
195-
Value::Big(id) => Numeric::Big(self.big(*id).clone()),
334+
Value::Big(id) => Numeric::Big(self.big(*id).into_owned()),
196335
Value::Str(s) => text_numeric(self.atoms.get(*s)),
197336
v => Numeric::Num(self.number_of(v)?),
198337
})
199338
}
200339

201340
/// The decimal text of BigInt `id`.
202341
pub fn big_text(&self, id: Id) -> String {
203-
self.big(id).to_str_radix(10)
342+
match self.big_ref(id) {
343+
BigRef::Small(s) => s.to_string(),
344+
BigRef::Large(n) => n.to_str_radix(10),
345+
}
204346
}
205347

206348
/// ToBigInt of a primitive: numbers are refused, unlike `BigInt(n)`.
207349
fn bigint_of(&mut self, v: &Value) -> Res {
208350
match v {
209351
Value::Big(_) => Ok(*v),
210-
Value::Bool(b) => Ok(self.big_val(BigInt::from(*b as u8))),
352+
Value::Bool(b) => Ok(self.big_small(*b as i128)),
211353
Value::Str(s) => {
212354
let s = *s;
213355
self.string_to_big(s)
@@ -246,6 +388,29 @@ fn max_decimal_digits() -> usize {
246388
(MAX_BIGINT_BITS as f64 * 2f64.log10()).ceil() as usize + 1
247389
}
248390

391+
/// A binary operator on integers of at most 128 bits, in machine arithmetic; `None` for a result that may not fit,
392+
/// and for whatever fails or is rare, which `big_op` then computes.
393+
#[inline]
394+
fn small_op(op: u8, a: i128, b: i128) -> Option<i128> {
395+
match op {
396+
code::ADD => a.checked_add(b),
397+
code::SUB => a.checked_sub(b),
398+
code::MUL => a.checked_mul(b),
399+
code::DIV => a.checked_div(b),
400+
code::MOD => a.checked_rem(b),
401+
code::BIT_AND => Some(a & b),
402+
code::BIT_OR => Some(a | b),
403+
code::BIT_XOR => Some(a ^ b),
404+
// A left shift that keeps every bit: the value and the shift are both small.
405+
code::SHL if (0..64).contains(&b) && (-(1i128 << 62)..(1i128 << 62)).contains(&a) => {
406+
Some(a << b)
407+
}
408+
// A right shift floors, as an arithmetic shift does; past the value's bits it leaves its sign.
409+
code::SHR if b >= 0 => Some(a >> b.min(127)),
410+
_ => None,
411+
}
412+
}
413+
249414
fn big_op(op: u8, x: &BigInt, y: &BigInt) -> Result<BigInt, Fail> {
250415
Ok(match op {
251416
code::ADD => x + y,
@@ -462,6 +627,10 @@ fn bigint_call(vm: &mut Vm, _this: Value, args: &[Value], _: Id) -> Res {
462627
return vm.bigint_of(&v);
463628
};
464629
if n.is_finite() && n.fract() == 0.0 {
630+
// Every integer below 2^63 converts exactly.
631+
if n.abs() < 9223372036854775808.0 {
632+
return Ok(vm.big_small(n as i64 as i128));
633+
}
465634
return Ok(vm.big_val(BigInt::from_f64(n).unwrap_or_default()));
466635
}
467636
let text = crate::value::num_to_string(n);
@@ -489,7 +658,19 @@ fn wrap(vm: &mut Vm, args: &[Value], signed: bool) -> Res {
489658
let Value::Big(id) = vm.bigint_of(&value)? else {
490659
return Ok(Value::Undef);
491660
};
492-
let n = vm.big(id);
661+
// At most 128 bits wrapped to at most 64: machine arithmetic, the mask applied to the two's complement.
662+
if let Some(s) = vm.small_of(id)
663+
&& width <= 64.0
664+
{
665+
let w = width as u32;
666+
let mask = (1i128 << w) - 1;
667+
let mut r = s & mask;
668+
if signed && w > 0 && r >> (w - 1) != 0 {
669+
r -= mask + 1;
670+
}
671+
return Ok(vm.big_small(r));
672+
}
673+
let n = &*vm.big(id);
493674
if width > MAX_BIGINT_BITS as f64 {
494675
if !signed && n.is_negative() {
495676
return Err(vm.range_error(TOO_BIG));
@@ -549,7 +730,10 @@ fn to_string(vm: &mut Vm, this: Value, args: &[Value], _: Id) -> Res {
549730
if !(2.0..=36.0).contains(&base) {
550731
return Err(vm.range_error("toString() radix must be between 2 and 36."));
551732
}
552-
let text = vm.big(id).to_str_radix(base as u32);
733+
let text = match base as u32 {
734+
10 => vm.big_text(id),
735+
radix => vm.big(id).to_str_radix(radix),
736+
};
553737
Ok(vm.string_val(text))
554738
})
555739
}

‎rust/crates/psychoscript/src/builtins/string.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1339,7 +1339,7 @@ fn number_ctor(vm: &mut Vm, this: Value, args: &[Value], _: Id) -> Res {
13391339
}
13401340
fuel::with_primitives(vm, &[Hint::Number], [args[0]], false, |vm, [v]| {
13411341
if let Value::Big(id) = v {
1342-
return Ok(Value::Num(super::bigint::big_to_f64(vm.big(id))));
1342+
return Ok(Value::Num(super::bigint::big_to_f64(&vm.big(id))));
13431343
}
13441344
Ok(Value::Num(vm.number_of(&v)?))
13451345
})

‎rust/crates/psychoscript/src/collector.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,7 @@ impl Marker<'_> {
685685
{
686686
*k = BLACK;
687687
match self.vm.cells[c as usize].get() {
688+
Value::Big(id) if !crate::builtins::bigint::on_heap(id) => {}
688689
Value::Obj(id) | Value::Big(id) => self.mark(Ref::Obj(id)),
689690
Value::Str(s) => self.mark_str(s),
690691
_ => {}
@@ -830,6 +831,7 @@ impl Vm {
830831
return;
831832
};
832833
match v.get() {
834+
Value::Big(id) if !crate::builtins::bigint::on_heap(id) => {}
833835
Value::Obj(id) | Value::Big(id) => {
834836
if self.heap.marks.color.get(id as usize) == Some(&WHITE) {
835837
self.heap.marks.color[id as usize] = GREY;

0 commit comments

Comments
 (0)