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
8 changes: 5 additions & 3 deletions crates/clazel-js-number/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ Part of [Clazel](../../README.md). ECMAScript's Number conversions
| `bigint_literal_value(&str) -> Option<BigInt>` | The value of a lexer BigInt literal (`n` suffix, `_` separators, §12.9.3†). |
| `BigInt::to_string_radix(u32)` | BigInt::toString (§6.1.6.2.23†), radix 2 to 36, lowercase; `RangeError` outside that. |

`BigInt` is a sign and a `Big` magnitude (zero is never negative), so the limb
arithmetic exists once. Conversion takes a word-sized chunk of digits at a
`BigInt` is a sign and a `Big` magnitude (zero is never negative, unbounded,
`Vec`-backed). The Number conversions use the fixed-capacity `FixedBig<N>`
instead (64 limbs for StringToNumber's exact path, 32 for the formatters and
the tables), which Kani can reason about. Conversion takes a word-sized chunk of digits at a
time (quadratic), with a bit-extraction path for radix 2, 4, 8, 16 and 32.

† The section numbers are from `phase-7.md`; the spec text is not vendored, so
Expand Down Expand Up @@ -46,7 +48,7 @@ Raising the tier to 1 waits for CI's full verification on the pull request.

- Heap storage for BigInts (item 7.5): this crate parses and prints them.
- Number::toString for a radix other than 10.
- The powers-of-five tables are computed on first use from `Big`, not stored.
- The powers-of-five tables are computed on first use from `FixedBig`, not stored.
A later change can emit them as a checked-in constant, as `cargo xtask
tables` does for IDNA.

Expand Down
233 changes: 10 additions & 223 deletions crates/clazel-js-number/src/bigint.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
//! A small unsigned big integer: little-endian `u64` limbs, no trailing zero
//! limb. It holds the exact values the slow paths need (powers of ten and
//! five, scaled mantissas) and nothing more: add and multiply by a word,
//! shifts, comparison, subtraction, and long division.
//! The unbounded unsigned big integer of BigInt values: little-endian `u64`
//! limbs in a `Vec`, no trailing zero limb. It has what BigInt parsing and
//! printing need: multiply and add a word, divide by a word (with the
//! remainder), comparison, and bit access.
//!
//! Every operation is total. Preconditions that cannot be stated in the type
//! (`sub_assign` needs `self >= other`; `divrem` needs a nonzero divisor)
//! have a defined answer when violated (`sub_assign` gives zero, `divrem` by
//! zero returns `(0, num)`), so no input panics.
//! The exact paths of the Number conversions use the fixed-capacity,
//! array-backed [`crate::fixed::FixedBig`] instead (Kani cannot reason about
//! `Vec` growth, and those paths are bounded). A BigInt has no bound, so it
//! stays `Vec`-backed.
//!
//! Every operation is total: division by zero leaves the value alone.

use std::cmp::Ordering;

Expand All @@ -17,11 +19,6 @@ pub struct Big {
limbs: Vec<u64>,
}

/// `10^19`, the largest power of ten in a `u64`.
const TEN_19: u64 = 10_000_000_000_000_000_000;
/// `5^27`, the largest power of five in a `u64`.
const FIVE_27: u64 = 7_450_580_596_923_828_125;

/// Append the decimal digits of `v`, padded with zeros on the left to at
/// least `width` digits (`v = 0` prints one digit when `width` is 0).
pub fn push_u64(s: &mut String, v: u64, width: usize) {
Expand All @@ -45,12 +42,6 @@ pub fn push_u64(s: &mut String, v: u64, width: usize) {
}
}

/// A mask of the low `bits` bits.
fn low_mask(bits: u32) -> u64 {
1u64.checked_shl(bits)
.map_or(u64::MAX, |b| b.wrapping_sub(1))
}

impl Big {
/// Zero.
#[must_use]
Expand Down Expand Up @@ -171,113 +162,6 @@ impl Big {
rem as u64
}

/// `self *= 10^k`.
pub fn mul_pow10(&mut self, k: u32) {
let mut k = k;
while k >= 19 {
self.mul_small(TEN_19);
k = k.saturating_sub(19);
}
let mut p: u64 = 1;
for _ in 0..k {
p = p.saturating_mul(10);
}
self.mul_small(p);
}

/// `self *= 5^k`.
pub fn mul_pow5(&mut self, k: u32) {
let mut k = k;
while k >= 27 {
self.mul_small(FIVE_27);
k = k.saturating_sub(27);
}
let mut p: u64 = 1;
for _ in 0..k {
p = p.saturating_mul(5);
}
self.mul_small(p);
}

/// `self = floor(self / 5^k)`: floor division composes, so this divides
/// by `5^27` as often as it fits, then by the rest.
pub fn div_pow5(&mut self, k: u32) {
let mut k = k;
while k >= 27 {
self.div_small(FIVE_27);
k = k.saturating_sub(27);
}
let mut p: u64 = 1;
for _ in 0..k {
p = p.saturating_mul(5);
}
self.div_small(p);
}

/// `self << bits`.
#[must_use]
pub fn shl(&self, bits: u64) -> Self {
if self.is_zero() {
return Self::zero();
}
let limbs = usize::try_from(bits / 64).unwrap_or(usize::MAX);
let rem = (bits % 64) as u32;
let mut out = vec![0u64; limbs];
let mut carry: u64 = 0;
for &l in &self.limbs {
if rem == 0 {
out.push(l);
} else {
out.push((l << rem) | carry);
carry = l.checked_shr(64u32.saturating_sub(rem)).unwrap_or(0);
}
}
if carry != 0 {
out.push(carry);
}
let mut b = Self { limbs: out };
b.trim();
b
}

/// `self << 1 | bit`, in place.
fn shl1_or(&mut self, bit: bool) {
let mut carry = u64::from(bit);
for l in &mut self.limbs {
let next = *l >> 63;
*l = (*l << 1) | carry;
carry = next;
}
if carry != 0 {
self.limbs.push(carry);
}
}

/// `self >> bits`, and whether any bit shifted out was set.
#[must_use]
pub fn shr(&self, bits: u64) -> (Self, bool) {
let limbs = usize::try_from(bits / 64).unwrap_or(usize::MAX);
let rem = (bits % 64) as u32;
let mut sticky = false;
for &l in self.limbs.iter().take(limbs) {
sticky |= l != 0;
}
let kept: Vec<u64> = self.limbs.iter().skip(limbs).copied().collect();
let mut out = Vec::with_capacity(kept.len());
if rem == 0 {
out.extend_from_slice(&kept);
} else {
sticky |= kept.first().is_some_and(|&l| l & low_mask(rem) != 0);
for (i, &l) in kept.iter().enumerate() {
let next = kept.get(i.saturating_add(1)).copied().unwrap_or(0);
out.push((l >> rem) | next.checked_shl(64u32.saturating_sub(rem)).unwrap_or(0));
}
}
let mut b = Self { limbs: out };
b.trim();
(b, sticky)
}

/// Numeric comparison.
#[must_use]
pub fn cmp_big(&self, other: &Self) -> Ordering {
Expand All @@ -294,101 +178,4 @@ impl Big {
o => o,
}
}

/// `self += other`.
pub fn add_assign(&mut self, other: &Self) {
let mut carry = false;
let n = self.limbs.len().max(other.limbs.len());
self.limbs.resize(n, 0);
for (i, l) in self.limbs.iter_mut().enumerate() {
let o = other.limbs.get(i).copied().unwrap_or(0);
let (s1, c1) = l.overflowing_add(o);
let (s2, c2) = s1.overflowing_add(u64::from(carry));
*l = s2;
carry = c1 | c2;
}
if carry {
self.limbs.push(1);
}
self.trim();
}

/// `self -= other`. If `other > self` the result is zero.
pub fn sub_assign(&mut self, other: &Self) {
if self.cmp_big(other) == Ordering::Less {
self.limbs.clear();
return;
}
let mut borrow = false;
for (i, l) in self.limbs.iter_mut().enumerate() {
let o = other.limbs.get(i).copied().unwrap_or(0);
let (d1, b1) = l.overflowing_sub(o);
let (d2, b2) = d1.overflowing_sub(u64::from(borrow));
*l = d2;
borrow = b1 | b2;
}
self.trim();
}

/// Quotient and remainder of `num / den`, by binary long division.
/// Division by zero returns `(0, num)`.
#[must_use]
pub fn divrem(num: &Self, den: &Self) -> (Self, Self) {
if den.is_zero() {
return (Self::zero(), num.clone());
}
let nbits = num.bit_len();
let qlimbs = usize::try_from(nbits.div_ceil(64)).unwrap_or(0);
let mut quo = vec![0u64; qlimbs];
let mut rem = Self::zero();
let mut i = nbits;
while i > 0 {
i = i.saturating_sub(1);
rem.shl1_or(num.bit(i));
if rem.cmp_big(den) != Ordering::Less {
rem.sub_assign(den);
let limb = usize::try_from(i / 64).unwrap_or(usize::MAX);
if let Some(q) = quo.get_mut(limb) {
*q |= 1u64 << (i % 64);
}
}
}
let mut q = Self { limbs: quo };
q.trim();
(q, rem)
}

/// The decimal digits, most significant first (`"0"` for zero).
#[must_use]
pub fn to_decimal(&self) -> String {
if self.is_zero() {
return "0".to_string();
}
let mut t = self.clone();
let mut chunks: Vec<u64> = Vec::new();
while !t.is_zero() {
chunks.push(t.div_small(TEN_19));
}
let mut s = String::new();
for (i, c) in chunks.iter().rev().enumerate() {
push_u64(&mut s, *c, if i == 0 { 0 } else { 19 });
}
s
}

/// `5^k`.
#[must_use]
pub fn pow5(k: u32) -> Self {
let mut b = Self::from_u64(1);
b.mul_pow5(k);
b
}

/// `10^k`.
#[must_use]
pub fn pow10(k: u32) -> Self {
let mut b = Self::from_u64(1);
b.mul_pow10(k);
b
}
}
Loading
Loading