Skip to main content

strata_js/
bigint.rs

1//! Pure-Rust Arbitrary Precision Integer Engine for ECMAScript BigInt (GOAL-48).
2
3use std::cmp::Ordering;
4use std::fmt;
5
6/// Arbitrary-precision integer adhering to ECMAScript BigInt semantics.
7#[derive(Clone, PartialEq, Eq, Hash)]
8pub struct JsBigInt {
9    /// True for non-negative (>= 0), false for negative (< 0).
10    pub is_positive: bool,
11    /// Little-endian base 2^64 limbs. Normalized such that the most significant
12    /// limb is non-zero, unless the value is zero, where limbs is empty.
13    pub limbs: Vec<u64>,
14}
15
16impl JsBigInt {
17    /// Creates a BigInt representing zero.
18    pub const fn zero() -> Self {
19        Self {
20            is_positive: true,
21            limbs: Vec::new(),
22        }
23    }
24
25    /// Creates a BigInt representing one.
26    pub fn one() -> Self {
27        Self {
28            is_positive: true,
29            limbs: vec![1],
30        }
31    }
32
33    /// Checks if this BigInt is zero.
34    pub fn is_zero(&self) -> bool {
35        self.limbs.is_empty() || self.limbs.iter().all(|&l| l == 0)
36    }
37
38    /// Creates a BigInt from a signed 64-bit integer.
39    pub fn from_i64(val: i64) -> Self {
40        if val == 0 {
41            return Self::zero();
42        }
43        let is_positive = val >= 0;
44        let abs = if val == i64::MIN {
45            (i64::MAX as u64) + 1
46        } else {
47            val.unsigned_abs()
48        };
49        Self {
50            is_positive,
51            limbs: vec![abs],
52        }
53    }
54
55    /// Creates a BigInt from an unsigned 64-bit integer.
56    pub fn from_u64(val: u64) -> Self {
57        if val == 0 {
58            Self::zero()
59        } else {
60            Self {
61                is_positive: true,
62                limbs: vec![val],
63            }
64        }
65    }
66
67    /// Creates a BigInt from a signed 128-bit integer.
68    pub fn from_i128(val: i128) -> Self {
69        if val == 0 {
70            return Self::zero();
71        }
72        let is_positive = val >= 0;
73        let abs = if val == i128::MIN {
74            (i128::MAX as u128) + 1
75        } else {
76            val.unsigned_abs()
77        };
78        Self::from_u128(abs, is_positive)
79    }
80
81    /// Creates a BigInt from an unsigned 128-bit integer and sign.
82    pub fn from_u128(abs: u128, is_positive: bool) -> Self {
83        if abs == 0 {
84            return Self::zero();
85        }
86        let low = abs as u64;
87        let high = (abs >> 64) as u64;
88        let mut limbs = vec![low];
89        if high > 0 {
90            limbs.push(high);
91        }
92        Self { is_positive, limbs }
93    }
94
95    /// Parses a string into a BigInt, supporting optional sign, base prefixes
96    /// (0x, 0b, 0o), and optional trailing 'n'.
97    pub fn parse(s: &str) -> Result<Self, String> {
98        let trimmed = s.trim();
99        if trimmed.is_empty() {
100            return Err("SyntaxError: Cannot convert empty string to a BigInt".to_string());
101        }
102
103        let without_suffix = trimmed.strip_suffix('n').unwrap_or(trimmed);
104        if without_suffix.is_empty() {
105            return Err("SyntaxError: Invalid BigInt literal".to_string());
106        }
107
108        let (is_positive, body) = if let Some(rest) = without_suffix.strip_prefix('-') {
109            (false, rest)
110        } else if let Some(rest) = without_suffix.strip_prefix('+') {
111            (true, rest)
112        } else {
113            (true, without_suffix)
114        };
115
116        if body.is_empty() {
117            return Err("SyntaxError: Invalid BigInt literal".to_string());
118        }
119
120        let (radix, digits) =
121            if let Some(hex) = body.strip_prefix("0x").or_else(|| body.strip_prefix("0X")) {
122                (16u32, hex)
123            } else if let Some(bin) = body.strip_prefix("0b").or_else(|| body.strip_prefix("0B")) {
124                (2u32, bin)
125            } else if let Some(oct) = body.strip_prefix("0o").or_else(|| body.strip_prefix("0O")) {
126                (8u32, oct)
127            } else {
128                (10u32, body)
129            };
130
131        if digits.is_empty() {
132            return Err("SyntaxError: Invalid BigInt literal".to_string());
133        }
134
135        let mut result = Self::zero();
136        let radix_big = Self::from_u64(radix as u64);
137
138        for ch in digits.chars() {
139            if ch == '_' {
140                continue; // Support numeric separators (e.g. 1_000n)
141            }
142            let digit = ch.to_digit(radix).ok_or_else(|| {
143                format!("SyntaxError: Invalid character '{ch}' in BigInt literal")
144            })?;
145            result = result.mul_abs(&radix_big);
146            result = result.add_abs(&Self::from_u64(digit as u64));
147        }
148
149        result.is_positive = if result.is_zero() { true } else { is_positive };
150        result.normalize();
151        Ok(result)
152    }
153
154    /// Normalizes internal representation by stripping trailing zero limbs.
155    fn normalize(&mut self) {
156        while let Some(&0) = self.limbs.last() {
157            self.limbs.pop();
158        }
159        if self.limbs.is_empty() {
160            self.is_positive = true;
161        }
162    }
163
164    /// Compares absolute magnitudes.
165    pub fn cmp_abs(&self, other: &Self) -> Ordering {
166        if self.limbs.len() != other.limbs.len() {
167            return self.limbs.len().cmp(&other.limbs.len());
168        }
169        for (a, b) in self.limbs.iter().rev().zip(other.limbs.iter().rev()) {
170            if a != b {
171                return a.cmp(b);
172            }
173        }
174        Ordering::Equal
175    }
176
177    /// Adds absolute values.
178    fn add_abs(&self, other: &Self) -> Self {
179        let max_len = self.limbs.len().max(other.limbs.len());
180        let mut limbs = Vec::with_capacity(max_len + 1);
181        let mut carry = 0u64;
182
183        for i in 0..max_len {
184            let a = *self.limbs.get(i).unwrap_or(&0);
185            let b = *other.limbs.get(i).unwrap_or(&0);
186            let sum = (a as u128) + (b as u128) + (carry as u128);
187            limbs.push(sum as u64);
188            carry = (sum >> 64) as u64;
189        }
190        if carry > 0 {
191            limbs.push(carry);
192        }
193
194        let mut res = Self {
195            is_positive: true,
196            limbs,
197        };
198        res.normalize();
199        res
200    }
201
202    /// Subtracts absolute values (assumes self >= other).
203    fn sub_abs(&self, other: &Self) -> Self {
204        let mut limbs = Vec::with_capacity(self.limbs.len());
205        let mut borrow = 0i128;
206
207        for i in 0..self.limbs.len() {
208            let a = *self.limbs.get(i).unwrap_or(&0) as i128;
209            let b = *other.limbs.get(i).unwrap_or(&0) as i128;
210            let diff = a - b - borrow;
211            if diff < 0 {
212                limbs.push((diff + (1i128 << 64)) as u64);
213                borrow = 1;
214            } else {
215                limbs.push(diff as u64);
216                borrow = 0;
217            }
218        }
219
220        let mut res = Self {
221            is_positive: true,
222            limbs,
223        };
224        res.normalize();
225        res
226    }
227
228    /// Multiplies absolute values.
229    fn mul_abs(&self, other: &Self) -> Self {
230        if self.is_zero() || other.is_zero() {
231            return Self::zero();
232        }
233        let mut limbs = vec![0u64; self.limbs.len() + other.limbs.len()];
234
235        for (i, &a) in self.limbs.iter().enumerate() {
236            let mut carry = 0u128;
237            for (j, &b) in other.limbs.iter().enumerate() {
238                let cur = limbs[i + j] as u128;
239                let prod = (a as u128) * (b as u128) + cur + carry;
240                limbs[i + j] = prod as u64;
241                carry = prod >> 64;
242            }
243            if carry > 0 {
244                limbs[i + other.limbs.len()] += carry as u64;
245            }
246        }
247
248        let mut res = Self {
249            is_positive: true,
250            limbs,
251        };
252        res.normalize();
253        res
254    }
255
256    /// Adds two BigInts respecting signs.
257    pub fn add(&self, other: &Self) -> Self {
258        if self.is_positive == other.is_positive {
259            let mut res = self.add_abs(other);
260            res.is_positive = self.is_positive;
261            res
262        } else {
263            match self.cmp_abs(other) {
264                Ordering::Equal => Self::zero(),
265                Ordering::Greater => {
266                    let mut res = self.sub_abs(other);
267                    res.is_positive = self.is_positive;
268                    res
269                }
270                Ordering::Less => {
271                    let mut res = other.sub_abs(self);
272                    res.is_positive = other.is_positive;
273                    res
274                }
275            }
276        }
277    }
278
279    /// Negates a BigInt.
280    pub fn neg(&self) -> Self {
281        if self.is_zero() {
282            self.clone()
283        } else {
284            let mut res = self.clone();
285            res.is_positive = !res.is_positive;
286            res
287        }
288    }
289
290    /// Subtracts two BigInts respecting signs.
291    pub fn sub(&self, other: &Self) -> Self {
292        self.add(&other.neg())
293    }
294
295    /// Multiplies two BigInts respecting signs.
296    pub fn mul(&self, other: &Self) -> Self {
297        if self.is_zero() || other.is_zero() {
298            return Self::zero();
299        }
300        let mut res = self.mul_abs(other);
301        res.is_positive = self.is_positive == other.is_positive;
302        res
303    }
304
305    /// Divides and computes remainder of absolute values using binary restoring division.
306    fn div_rem_abs(&self, other: &Self) -> Result<(Self, Self), String> {
307        if other.is_zero() {
308            return Err("RangeError: Division by zero".to_string());
309        }
310        if self.cmp_abs(other) == Ordering::Less {
311            return Ok((Self::zero(), self.clone()));
312        }
313
314        let mut quotient = Self::zero();
315        let mut remainder = Self::zero();
316
317        // Total bits in self
318        let total_bits = self.bit_length();
319
320        for bit_idx in (0..total_bits).rev() {
321            remainder = remainder.shl(1);
322            if self.test_bit(bit_idx) {
323                remainder = remainder.add_abs(&Self::one());
324            }
325
326            if remainder.cmp_abs(other) != Ordering::Less {
327                remainder = remainder.sub_abs(other);
328                quotient.set_bit(bit_idx);
329            }
330        }
331
332        quotient.normalize();
333        remainder.normalize();
334        Ok((quotient, remainder))
335    }
336
337    /// Integer division.
338    pub fn div(&self, other: &Self) -> Result<Self, String> {
339        let (mut q, _) = self.div_rem_abs(other)?;
340        if !q.is_zero() {
341            q.is_positive = self.is_positive == other.is_positive;
342        }
343        Ok(q)
344    }
345
346    /// Remainder operation.
347    pub fn rem(&self, other: &Self) -> Result<Self, String> {
348        let (_, mut r) = self.div_rem_abs(other)?;
349        if !r.is_zero() {
350            r.is_positive = self.is_positive;
351        }
352        Ok(r)
353    }
354
355    /// Exponentiation (pow) adhering to ECMAScript standard.
356    pub fn pow(&self, exp: &Self) -> Result<Self, String> {
357        if !exp.is_positive && !exp.is_zero() {
358            return Err("RangeError: Exponent must be non-negative".to_string());
359        }
360        if exp.is_zero() {
361            return Ok(Self::one());
362        }
363        if self.is_zero() {
364            return Ok(Self::zero());
365        }
366
367        let mut base = self.clone();
368        let mut exponent = exp.clone();
369        let mut result = Self::one();
370
371        while !exponent.is_zero() {
372            if exponent.test_bit(0) {
373                result = result.mul(&base);
374            }
375            base = base.mul(&base);
376            exponent = exponent.shr(1);
377        }
378
379        Ok(result)
380    }
381
382    /// Bitwise NOT (~).
383    pub fn bit_not(&self) -> Self {
384        // In ECMAScript: ~x === -(x + 1)
385        let one = Self::one();
386        let plus_one = self.add(&one);
387        let mut res = plus_one;
388        if !res.is_zero() {
389            res.is_positive = !res.is_positive;
390        }
391        res
392    }
393
394    /// Bitwise shift left.
395    pub fn shl(&self, shift: usize) -> Self {
396        if self.is_zero() || shift == 0 {
397            return self.clone();
398        }
399        let limb_shift = shift / 64;
400        let bit_shift = (shift % 64) as u32;
401
402        let mut limbs = vec![0u64; limb_shift];
403        let mut carry = 0u64;
404
405        for &limb in &self.limbs {
406            let shifted = if bit_shift == 0 {
407                limb
408            } else {
409                (limb << bit_shift) | carry
410            };
411            limbs.push(shifted);
412            carry = if bit_shift == 0 {
413                0
414            } else {
415                limb >> (64 - bit_shift)
416            };
417        }
418        if carry > 0 {
419            limbs.push(carry);
420        }
421
422        let mut res = Self {
423            is_positive: self.is_positive,
424            limbs,
425        };
426        res.normalize();
427        res
428    }
429
430    /// Bitwise shift right.
431    pub fn shr(&self, shift: usize) -> Self {
432        if self.is_zero() || shift == 0 {
433            return self.clone();
434        }
435        let limb_shift = shift / 64;
436        let bit_shift = (shift % 64) as u32;
437
438        if limb_shift >= self.limbs.len() {
439            return if self.is_positive {
440                Self::zero()
441            } else {
442                Self::from_i64(-1)
443            };
444        }
445
446        let mut limbs = Vec::new();
447        let source = &self.limbs[limb_shift..];
448
449        for i in 0..source.len() {
450            let cur = source[i];
451            let next = source.get(i + 1).copied().unwrap_or(0);
452            let shifted = if bit_shift == 0 {
453                cur
454            } else {
455                (cur >> bit_shift) | (next << (64 - bit_shift))
456            };
457            limbs.push(shifted);
458        }
459
460        let mut res = Self {
461            is_positive: self.is_positive,
462            limbs,
463        };
464        res.normalize();
465        res
466    }
467
468    /// Bit length (index of highest set bit + 1).
469    pub fn bit_length(&self) -> usize {
470        if let Some(&last) = self.limbs.last() {
471            (self.limbs.len() - 1) * 64 + (64 - last.leading_zeros() as usize)
472        } else {
473            0
474        }
475    }
476
477    /// Converts non-negative single limb BigInt to u64 if fits.
478    pub fn to_u64(&self) -> Option<u64> {
479        if !self.is_positive {
480            return None;
481        }
482        if self.limbs.is_empty() {
483            Some(0)
484        } else if self.limbs.len() == 1 {
485            Some(self.limbs[0])
486        } else {
487            None
488        }
489    }
490
491    /// Bitwise AND (&).
492    pub fn bit_and(&self, other: &Self) -> Self {
493        let max_len = self.limbs.len().min(other.limbs.len());
494        let mut limbs = Vec::with_capacity(max_len);
495        for i in 0..max_len {
496            limbs.push(self.limbs[i] & other.limbs[i]);
497        }
498        let is_positive = self.is_positive && other.is_positive;
499        let mut res = Self { is_positive, limbs };
500        res.normalize();
501        res
502    }
503
504    /// Bitwise OR (|).
505    pub fn bit_or(&self, other: &Self) -> Self {
506        let max_len = self.limbs.len().max(other.limbs.len());
507        let mut limbs = Vec::with_capacity(max_len);
508        for i in 0..max_len {
509            let a = self.limbs.get(i).copied().unwrap_or(0);
510            let b = other.limbs.get(i).copied().unwrap_or(0);
511            limbs.push(a | b);
512        }
513        let is_positive = self.is_positive || other.is_positive;
514        let mut res = Self { is_positive, limbs };
515        res.normalize();
516        res
517    }
518
519    /// Bitwise XOR (^).
520    pub fn bit_xor(&self, other: &Self) -> Self {
521        let max_len = self.limbs.len().max(other.limbs.len());
522        let mut limbs = Vec::with_capacity(max_len);
523        for i in 0..max_len {
524            let a = self.limbs.get(i).copied().unwrap_or(0);
525            let b = other.limbs.get(i).copied().unwrap_or(0);
526            limbs.push(a ^ b);
527        }
528        let is_positive = self.is_positive == other.is_positive;
529        let mut res = Self { is_positive, limbs };
530        res.normalize();
531        res
532    }
533
534    /// Tests if a bit at `index` is 1.
535    pub fn test_bit(&self, index: usize) -> bool {
536        let limb_idx = index / 64;
537        let bit_idx = index % 64;
538        if let Some(&limb) = self.limbs.get(limb_idx) {
539            (limb & (1u64 << bit_idx)) != 0
540        } else {
541            false
542        }
543    }
544
545    /// Sets a bit at `index` to 1.
546    pub fn set_bit(&mut self, index: usize) {
547        let limb_idx = index / 64;
548        let bit_idx = index % 64;
549        if limb_idx >= self.limbs.len() {
550            self.limbs.resize(limb_idx + 1, 0);
551        }
552        self.limbs[limb_idx] |= 1u64 << bit_idx;
553    }
554
555    /// Converts to standard decimal string representation.
556    pub fn to_decimal_string(&self) -> String {
557        if self.is_zero() {
558            return "0".to_string();
559        }
560
561        let mut temp = self.clone();
562        temp.is_positive = true;
563        let ten = Self::from_u64(10);
564        let mut digits = Vec::new();
565
566        while !temp.is_zero() {
567            let (q, r) = temp.div_rem_abs(&ten).unwrap();
568            let d = r.limbs.first().copied().unwrap_or(0);
569            digits.push((b'0' + d as u8) as char);
570            temp = q;
571        }
572
573        if !self.is_positive {
574            digits.push('-');
575        }
576
577        digits.iter().rev().collect()
578    }
579}
580
581impl PartialOrd for JsBigInt {
582    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
583        Some(self.cmp(other))
584    }
585}
586
587impl Ord for JsBigInt {
588    fn cmp(&self, other: &Self) -> Ordering {
589        if self.is_positive != other.is_positive {
590            return if self.is_positive {
591                Ordering::Greater
592            } else {
593                Ordering::Less
594            };
595        }
596        let mag = self.cmp_abs(other);
597        if self.is_positive {
598            mag
599        } else {
600            mag.reverse()
601        }
602    }
603}
604
605impl fmt::Debug for JsBigInt {
606    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607        write!(f, "{}n", self.to_decimal_string())
608    }
609}
610
611impl fmt::Display for JsBigInt {
612    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613        write!(f, "{}", self.to_decimal_string())
614    }
615}
616
617impl std::str::FromStr for JsBigInt {
618    type Err = String;
619
620    fn from_str(s: &str) -> Result<Self, Self::Err> {
621        Self::parse(s)
622    }
623}