quickjs-oxide 0.4.0

A safe Rust JavaScript engine targeting semantic parity with QuickJS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
//! `QuickJS`-compatible arbitrary-precision integer values.
//!
//! This module mirrors the two representations used by `QuickJS` 2026-06-04:
//! values fitting in one signed host limb use an immediate `i64`, while larger
//! values are reference-counted arbitrary-precision integers. Every operation
//! compacts its result back to the immediate representation when possible.
//!
//! `QuickJS` stores heap BigInts as normalized, little-endian two's-complement
//! limbs. `num_bigint::BigInt` is sign/magnitude internally, so the few places
//! where the representation is observable (notably `BigInt.asUintN`) explicitly
//! emulate the upstream signed-limb behavior.

use super::primitive::is_ecmascript_whitespace;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt;
use std::rc::Rc;
use std::str::FromStr;

use num_bigint::{BigInt, BigUint, Sign};
use num_traits::{FromPrimitive, One, ToPrimitive, Zero};

/// `QuickJS` normally limits a BigInt allocation to
/// `(1024 * 1024) / JS_LIMB_BITS` limbs.
///
/// On the 64-bit compatibility target this is 16,384 limbs, or 1,048,576
/// signed representation bits. `js_bigint_extend` can append one sign limb
/// after that guarded allocation, so selected add/sub/neg/shift results may
/// temporarily occupy 16,385 limbs exactly as in the pinned release.
pub const MAX_BIGINT_BITS: u64 = 1024 * 1024;

/// The host limb width used by the `QuickJS` 64-bit value representation.
pub const BIGINT_LIMB_BITS: u64 = 64;

const MAX_BIGINT_LIMBS: u64 = MAX_BIGINT_BITS / BIGINT_LIMB_BITS;

/// A failure produced by the BigInt value layer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BigIntError {
    /// A textual value is not a valid BigInt.
    InvalidSyntax,
    /// A formatting or parsing radix is outside `2..=36`.
    InvalidRadix(u32),
    /// Division or remainder by zero was requested.
    DivisionByZero,
    /// Exponentiation was requested with a negative exponent.
    NegativeExponent,
    /// The result would exceed the upstream BigInt allocation limit.
    BigIntTooLarge,
    /// An operation tried to allocate an input-sized BigInt whose normalized
    /// representation came from QuickJS's one-limb extension bypass.
    AllocationTooLarge,
    /// A left shift would exceed the upstream BigInt allocation limit.
    ShiftTooLarge,
}

impl fmt::Display for BigIntError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidSyntax => formatter.write_str("invalid BigInt syntax"),
            Self::InvalidRadix(radix) => {
                write!(
                    formatter,
                    "invalid BigInt radix {radix}; expected 2 through 36"
                )
            }
            Self::DivisionByZero => formatter.write_str("BigInt division by zero"),
            Self::NegativeExponent => formatter.write_str("BigInt negative exponent"),
            Self::BigIntTooLarge => formatter.write_str("BigInt is too large"),
            Self::AllocationTooLarge => formatter.write_str("BigInt is too large to allocate"),
            Self::ShiftTooLarge => formatter.write_str("BigInt shift is too large"),
        }
    }
}

impl std::error::Error for BigIntError {}

#[derive(Clone, Eq, Hash, PartialEq)]
enum BigIntRepr {
    Short(i64),
    Heap(Rc<BigInt>),
}

/// An ECMAScript BigInt using the same short/heap split as `QuickJS`.
///
/// The representation is private so callers cannot construct a non-normalized
/// heap value that should have been a short BigInt.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct JsBigInt(BigIntRepr);

impl JsBigInt {
    /// Test the tagged representation identity observed by QuickJS's raw
    /// `JSValue` equality shortcuts. Heap values must share the same cell;
    /// numeric equality alone is deliberately insufficient.
    #[must_use]
    pub fn same_representation(&self, other: &Self) -> bool {
        match (&self.0, &other.0) {
            (BigIntRepr::Short(left), BigIntRepr::Short(right)) => left == right,
            (BigIntRepr::Heap(left), BigIntRepr::Heap(right)) => Rc::ptr_eq(left, right),
            (BigIntRepr::Short(_), BigIntRepr::Heap(_))
            | (BigIntRepr::Heap(_), BigIntRepr::Short(_)) => false,
        }
    }

    /// Construct zero in the short representation.
    #[must_use]
    pub const fn zero() -> Self {
        Self(BigIntRepr::Short(0))
    }

    /// Construct one in the short representation.
    #[must_use]
    pub const fn one() -> Self {
        Self(BigIntRepr::Short(1))
    }

    /// Construct and normalize a `num_bigint::BigInt`.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::BigIntTooLarge`] when the signed limb
    /// representation exceeds the `QuickJS` allocation limit.
    pub fn from_bigint(value: BigInt) -> Result<Self, BigIntError> {
        if signed_limb_len(&value) > MAX_BIGINT_LIMBS {
            return Err(BigIntError::BigIntTooLarge);
        }
        Ok(Self::normalize(value))
    }

    /// Parse plain decimal text (an optional `-` and digits) with no size
    /// limit: a value another engine already holds, which may be one limb
    /// past the allocation guard as `js_bigint_extend` leaves it.
    pub(crate) fn from_decimal_unchecked(text: &str) -> Option<Self> {
        BigInt::parse_bytes(text.as_bytes(), 10).map(Self::normalize)
    }

    /// Convert an exactly integral finite binary64 value to a BigInt.
    ///
    /// This is the Number-only branch of QuickJS's BigInt constructor. The
    /// caller retains responsibility for selecting the distinct non-integer
    /// and non-finite JavaScript errors.
    #[must_use]
    pub fn from_integral_f64(value: f64) -> Option<Self> {
        if !value.is_finite() || value.fract() != 0.0 {
            return None;
        }
        BigInt::from_f64(value).map(Self::normalize)
    }

    /// Parse the string form accepted by the ECMAScript `BigInt` constructor.
    ///
    /// Leading and trailing ECMAScript whitespace is ignored. The empty string
    /// is zero. Decimal text may have a leading `+` or `-`; unsigned `0b`, `0o`,
    /// and `0x` prefixes are accepted. Numeric separators and a trailing `n`
    /// are deliberately rejected, as they are not part of `StringToBigInt`.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::InvalidSyntax`] for malformed input and an
    /// allocation-size error for values beyond the upstream limit.
    pub fn parse_js_string(source: &str) -> Result<Self, BigIntError> {
        let source = source.trim_matches(|character: char| {
            u16::try_from(character).is_ok_and(is_ecmascript_whitespace)
        });
        if source.is_empty() {
            return Ok(Self::zero());
        }

        let bytes = source.as_bytes();
        match bytes[0] {
            b'+' | b'-' => {
                let negative = bytes[0] == b'-';
                let digits = &source[1..];
                // Signed non-decimal prefixes are rejected by StringToBigInt.
                parse_digits(digits, 10, negative)
            }
            _ if bytes.len() >= 2 && bytes[0] == b'0' => {
                let radix = match bytes[1] {
                    b'b' | b'B' => Some(2),
                    b'o' | b'O' => Some(8),
                    b'x' | b'X' => Some(16),
                    _ => None,
                };
                if let Some(radix) = radix {
                    parse_digits(&source[2..], radix, false)
                } else {
                    parse_digits(source, 10, false)
                }
            }
            _ => parse_digits(source, 10, false),
        }
    }

    /// Parse an optionally signed digit sequence in `radix`.
    ///
    /// Unlike [`Self::parse_js_string`], this low-level entry point does not
    /// trim whitespace or recognize a base prefix.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::InvalidRadix`],
    /// [`BigIntError::InvalidSyntax`], or an allocation-size error.
    pub fn parse_radix(source: &str, radix: u32) -> Result<Self, BigIntError> {
        validate_radix(radix)?;
        let (negative, digits) = match source.as_bytes().first().copied() {
            Some(b'-') => (true, &source[1..]),
            Some(b'+') => (false, &source[1..]),
            _ => (false, source),
        };
        parse_digits(digits, radix, negative)
    }

    /// Format the integer with lowercase digits in `radix`.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::InvalidRadix`] unless `radix` is in `2..=36`.
    pub fn to_string_radix(&self, radix: u32) -> Result<String, BigIntError> {
        validate_radix(radix)?;
        Ok(match &self.0 {
            BigIntRepr::Short(value) => short_to_string_radix(*value, radix),
            BigIntRepr::Heap(value) => value.to_str_radix(radix),
        })
    }

    /// Whether this value uses the `JS_TAG_SHORT_BIG_INT`-like fast path.
    #[must_use]
    pub const fn is_short(&self) -> bool {
        matches!(self.0, BigIntRepr::Short(_))
    }

    /// Return the immediate value, or `None` for a heap BigInt.
    #[must_use]
    pub const fn as_i64(&self) -> Option<i64> {
        match self.0 {
            BigIntRepr::Short(value) => Some(value),
            BigIntRepr::Heap(_) => None,
        }
    }

    /// Return a cloned arbitrary-precision value for external integrations.
    #[must_use]
    pub fn to_bigint(&self) -> BigInt {
        match &self.0 {
            BigIntRepr::Short(value) => BigInt::from(*value),
            BigIntRepr::Heap(value) => value.as_ref().clone(),
        }
    }

    /// Convert this integer to the nearest IEEE-754 binary64 value.
    ///
    /// This is the conversion used by the `Number` constructor's `ToNumeric`
    /// path. It is deliberately separate from ordinary `ToNumber`, which must
    /// continue to reject BigInt primitives. `num-bigint` retains sticky lower
    /// bits before the final hardware conversion, yielding round-to-nearest,
    /// ties-to-even and signed infinity on overflow like pinned QuickJS.
    #[must_use]
    pub fn to_f64(&self) -> f64 {
        match &self.0 {
            BigIntRepr::Short(value) => *value as f64,
            BigIntRepr::Heap(value) => value
                .to_f64()
                .expect("an arbitrary-precision integer always has an f64 image"),
        }
    }

    /// Compare exactly with a Number, as IsLessThan requires (`None` for NaN).
    #[must_use]
    pub fn cmp_f64(&self, number: f64) -> Option<Ordering> {
        const TWO_POW_63: f64 = 9_223_372_036_854_775_808.0;
        if number.is_nan() {
            return None;
        }
        if (-TWO_POW_63..TWO_POW_63).contains(&number) {
            let ordering = match &self.0 {
                BigIntRepr::Short(value) => value.cmp(&(number.trunc() as i64)),
                // A heap value lies outside i64 and so beyond this Number.
                BigIntRepr::Heap(value) if value.sign() == Sign::Minus => Ordering::Less,
                BigIntRepr::Heap(_) => Ordering::Greater,
            };
            return Some(ordering.then(0.0.partial_cmp(&number.fract())?));
        }
        // |number| >= 2^63 is integral or infinite and beyond every short
        // value; a heap value of the opposite sign is likewise decided.
        match &self.0 {
            BigIntRepr::Heap(value)
                if number.is_finite() && (value.sign() == Sign::Minus) == (number < 0.0) =>
            {
                let number_bits = ((number.to_bits() >> 52) & 0x7ff) - 1022;
                let magnitude = value.bits().cmp(&number_bits).then_with(|| {
                    let number = BigUint::from_f64(number.abs()).expect("finite Number");
                    value.magnitude().cmp(&number)
                });
                Some(if number < 0.0 {
                    magnitude.reverse()
                } else {
                    magnitude
                })
            }
            _ => Some(if number > 0.0 {
                Ordering::Less
            } else {
                Ordering::Greater
            }),
        }
    }

    /// The unsigned magnitude bit length (`0` for zero).
    #[must_use]
    pub fn magnitude_bits(&self) -> u64 {
        match &self.0 {
            BigIntRepr::Short(value) => {
                let magnitude = value.unsigned_abs();
                u64::from(u64::BITS - magnitude.leading_zeros())
            }
            BigIntRepr::Heap(value) => value.bits(),
        }
    }

    /// Number of normalized signed 64-bit limbs used by `QuickJS`.
    #[must_use]
    pub fn signed_limb_len(&self) -> u64 {
        match &self.0 {
            BigIntRepr::Short(_) => 1,
            BigIntRepr::Heap(value) => signed_limb_len(value),
        }
    }

    pub fn exceeds_allocation_limit(&self) -> bool {
        self.signed_limb_len() > MAX_BIGINT_LIMBS
    }

    /// Whether this value is zero.
    #[must_use]
    pub fn is_zero(&self) -> bool {
        match &self.0 {
            BigIntRepr::Short(value) => *value == 0,
            BigIntRepr::Heap(value) => value.is_zero(),
        }
    }

    /// Whether this value is negative.
    #[must_use]
    pub fn is_negative(&self) -> bool {
        match &self.0 {
            BigIntRepr::Short(value) => *value < 0,
            BigIntRepr::Heap(value) => value.sign() == Sign::Minus,
        }
    }

    /// Add two BigInts, promoting on short overflow and compacting the result.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::BigIntTooLarge`] if the result exceeds the
    /// upstream allocation limit.
    pub fn add(&self, rhs: &Self) -> Result<Self, BigIntError> {
        let short_result = match (&self.0, &rhs.0) {
            (BigIntRepr::Short(left), BigIntRepr::Short(right)) => left.checked_add(*right),
            _ => None,
        };
        if let Some(result) = short_result {
            return Ok(Self::from(result));
        }
        self.ensure_operands_allocatable(rhs)?;
        self.checked_extending_binary(rhs, |left, right| left + right)
    }

    /// Subtract two BigInts, promoting on short overflow and compacting the
    /// result.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::BigIntTooLarge`] if the result exceeds the
    /// upstream allocation limit.
    pub fn sub(&self, rhs: &Self) -> Result<Self, BigIntError> {
        let short_result = match (&self.0, &rhs.0) {
            (BigIntRepr::Short(left), BigIntRepr::Short(right)) => left.checked_sub(*right),
            _ => None,
        };
        if let Some(result) = short_result {
            return Ok(Self::from(result));
        }
        self.ensure_operands_allocatable(rhs)?;
        self.checked_extending_binary(rhs, |left, right| left - right)
    }

    /// Apply the pinned QuickJS 2026-06-04 BigInt `--` operation.
    ///
    /// QuickJS handles ordinary short values in its VM fast path. At
    /// `i64::MIN` and for every heap BigInt it enters `js_unary_arith_slow`,
    /// where unsigned opcode-enum arithmetic turns the intended `-1` limb
    /// into `UINT32_MAX` before `js_bigint_add`. This observable release quirk
    /// is deliberately confined to update-decrement; binary subtraction keeps
    /// mathematical BigInt semantics.
    pub fn update_decrement(&self) -> Result<Self, BigIntError> {
        if let BigIntRepr::Short(value) = self.0
            && value != i64::MIN
        {
            return Ok(Self::from(value - 1));
        }
        self.add(&Self::from(i64::from(u32::MAX)))
    }

    /// Multiply two BigInts, promoting on short overflow and compacting the
    /// result.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::BigIntTooLarge`] if the result exceeds the
    /// upstream allocation limit.
    pub fn mul(&self, rhs: &Self) -> Result<Self, BigIntError> {
        let short_result = match (&self.0, &rhs.0) {
            (BigIntRepr::Short(left), BigIntRepr::Short(right)) => left.checked_mul(*right),
            _ => None,
        };
        if let Some(result) = short_result {
            return Ok(Self::from(result));
        }
        self.ensure_operands_allocatable(rhs)?;
        let allocated_limbs = self
            .signed_limb_len()
            .checked_add(rhs.signed_limb_len())
            .ok_or(BigIntError::AllocationTooLarge)?;
        if allocated_limbs > MAX_BIGINT_LIMBS {
            return Err(BigIntError::AllocationTooLarge);
        }
        self.checked_binary(rhs, |left, right| left * right)
    }

    /// Divide with truncation toward zero, as required for ECMAScript BigInt.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::DivisionByZero`] when `rhs` is zero.
    pub fn div(&self, rhs: &Self) -> Result<Self, BigIntError> {
        if rhs.is_zero() {
            return Err(BigIntError::DivisionByZero);
        }
        let short_result = match (&self.0, &rhs.0) {
            (BigIntRepr::Short(left), BigIntRepr::Short(right)) => left.checked_div(*right),
            _ => None,
        };
        if let Some(result) = short_result {
            return Ok(Self::from(result));
        }
        if self
            .signed_limb_len()
            .checked_add(2)
            .is_none_or(|allocated_limbs| allocated_limbs > MAX_BIGINT_LIMBS)
        {
            return Err(BigIntError::AllocationTooLarge);
        }
        // The only overflowing i64 division is MIN / -1. The arbitrary-
        // precision path naturally promotes it instead of panicking.
        self.checked_binary(rhs, |left, right| left / right)
    }

    /// Compute a remainder whose sign follows the dividend.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::DivisionByZero`] when `rhs` is zero.
    pub fn rem(&self, rhs: &Self) -> Result<Self, BigIntError> {
        if rhs.is_zero() {
            return Err(BigIntError::DivisionByZero);
        }
        if let (BigIntRepr::Short(left), BigIntRepr::Short(right)) = (&self.0, &rhs.0) {
            // Rust reports MIN % -1 as overflow even though the mathematical
            // result is zero.
            if *left == i64::MIN && *right == -1 {
                return Ok(Self::zero());
            }
            return Ok(Self::from(left % right));
        }
        if self
            .signed_limb_len()
            .checked_add(2)
            .is_none_or(|allocated_limbs| allocated_limbs > MAX_BIGINT_LIMBS)
        {
            return Err(BigIntError::AllocationTooLarge);
        }
        self.checked_binary(rhs, |left, right| left % right)
    }

    /// Raise this value to a non-negative BigInt exponent.
    ///
    /// `0`, `1`, and `-1` retain the same constant-result shortcuts as
    /// `js_bigint_pow`, even when the exponent itself is too large to fit a
    /// machine integer.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::NegativeExponent`] for a negative exponent,
    /// [`BigIntError::BigIntTooLarge`] when the mathematical exponent exceeds
    /// the upstream limit, and [`BigIntError::AllocationTooLarge`] when an
    /// intermediate or final allocation crosses the nominal limb guard.
    pub fn pow(&self, exponent: &Self) -> Result<Self, BigIntError> {
        if exponent.is_negative() {
            return Err(BigIntError::NegativeExponent);
        }
        if exponent.is_zero() {
            return Ok(Self::one());
        }
        if exponent.is_one() {
            if self.exceeds_allocation_limit() {
                return Err(BigIntError::AllocationTooLarge);
            }
            return Ok(self.clone());
        }
        if self.is_zero() || self.is_one() {
            return Ok(self.clone());
        }
        if self.is_negative_one() {
            return Ok(if exponent.is_odd() {
                Self::from(-1)
            } else {
                Self::one()
            });
        }

        let exponent = exponent
            .to_u32()
            .filter(|value| *value <= i32::MAX as u32)
            .ok_or(BigIntError::BigIntTooLarge)?;

        // js_bigint_pow has an exact-allocation shortcut for one-limb powers
        // of two. Besides being faster, this is observable at the allocation
        // boundary because the generic multiplier reserves both input widths.
        if let Some(base) = self.as_i64() {
            let magnitude = base.unsigned_abs();
            if magnitude.is_power_of_two() {
                let base_shift = u64::from(magnitude.trailing_zeros());
                let result_shift = u64::from(exponent) * base_shift;
                if result_shift > MAX_BIGINT_BITS {
                    return Err(BigIntError::BigIntTooLarge);
                }
                let mut result = BigInt::one()
                    << usize::try_from(result_shift)
                        .expect("bounded QuickJS BigInt power shift fits usize");
                if base.is_negative() && exponent & 1 != 0 {
                    result = -result;
                }
                return Self::from_bigint(result).map_err(|error| match error {
                    BigIntError::BigIntTooLarge => BigIntError::AllocationTooLarge,
                    error => error,
                });
            }
        }

        // The generic upstream algorithm starts with `a`, then scans the
        // remaining exponent bits from most to least significant. Matching
        // that order avoids an observable final `1 * result` allocation near
        // the 16,384-limb boundary.
        if self.exceeds_allocation_limit() {
            return Err(BigIntError::AllocationTooLarge);
        }
        let highest_bit = u32::BITS - exponent.leading_zeros();
        let mut result = self.clone();
        for bit in (0..highest_bit - 1).rev() {
            result = result.mul(&result)?;
            if exponent & (1 << bit) != 0 {
                result = result.mul(self)?;
            }
        }
        Ok(result)
    }

    /// Arithmetic negation, promoting `i64::MIN` to a heap BigInt.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::BigIntTooLarge`] if the result exceeds the
    /// upstream allocation limit.
    pub fn neg(&self) -> Result<Self, BigIntError> {
        let short_result = match &self.0 {
            BigIntRepr::Short(value) => value.checked_neg(),
            BigIntRepr::Heap(_) => None,
        };
        if let Some(result) = short_result {
            return Ok(Self::from(result));
        }
        if self.exceeds_allocation_limit() {
            return Err(BigIntError::AllocationTooLarge);
        }
        let result = -self.as_bigint().as_ref();
        if signed_limb_len(&result) > MAX_BIGINT_LIMBS + 1 {
            return Err(BigIntError::AllocationTooLarge);
        }
        Ok(Self::normalize(result))
    }

    /// Infinite-width two's-complement bitwise AND.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::AllocationTooLarge`] when either operand came
    /// from QuickJS's unguarded one-sign-limb extension.
    pub fn bit_and(&self, rhs: &Self) -> Result<Self, BigIntError> {
        if let (BigIntRepr::Short(left), BigIntRepr::Short(right)) = (&self.0, &rhs.0) {
            return Ok(Self::from(left & right));
        }
        self.ensure_operands_allocatable(rhs)?;
        Ok(self.unchecked_binary(rhs, |left, right| left & right))
    }

    /// Infinite-width two's-complement bitwise OR.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::AllocationTooLarge`] when either operand came
    /// from QuickJS's unguarded one-sign-limb extension.
    pub fn bit_or(&self, rhs: &Self) -> Result<Self, BigIntError> {
        if let (BigIntRepr::Short(left), BigIntRepr::Short(right)) = (&self.0, &rhs.0) {
            return Ok(Self::from(left | right));
        }
        self.ensure_operands_allocatable(rhs)?;
        Ok(self.unchecked_binary(rhs, |left, right| left | right))
    }

    /// Infinite-width two's-complement bitwise XOR.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::AllocationTooLarge`] when either operand came
    /// from QuickJS's unguarded one-sign-limb extension.
    pub fn bit_xor(&self, rhs: &Self) -> Result<Self, BigIntError> {
        if let (BigIntRepr::Short(left), BigIntRepr::Short(right)) = (&self.0, &rhs.0) {
            return Ok(Self::from(left ^ right));
        }
        self.ensure_operands_allocatable(rhs)?;
        Ok(self.unchecked_binary(rhs, |left, right| left ^ right))
    }

    /// Infinite-width two's-complement bitwise NOT.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::AllocationTooLarge`] when the operand came from
    /// QuickJS's unguarded one-sign-limb extension.
    pub fn bit_not(&self) -> Result<Self, BigIntError> {
        if self.exceeds_allocation_limit() {
            return Err(BigIntError::AllocationTooLarge);
        }
        Ok(match &self.0 {
            BigIntRepr::Short(value) => Self::from(!value),
            BigIntRepr::Heap(value) => Self::normalize(!value.as_ref()),
        })
    }

    /// ECMAScript BigInt left shift. A negative count shifts right.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::ShiftTooLarge`] when a non-zero left-shift result
    /// would exceed the `QuickJS` allocation limit.
    pub fn shl(&self, count: &Self) -> Result<Self, BigIntError> {
        self.shift(count, true)
    }

    /// ECMAScript BigInt arithmetic right shift. A negative count shifts left.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::ShiftTooLarge`] when a reversed (left) shift
    /// would exceed the `QuickJS` allocation limit.
    pub fn shr(&self, count: &Self) -> Result<Self, BigIntError> {
        self.shift(count, false)
    }

    /// `QuickJS` 2026-06-04 behavior for `BigInt.asIntN(bits, value)`.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::AllocationTooLarge`] when truncation would
    /// allocate the 16,385th nominal limb. The pinned release still returns
    /// an already-extended input unchanged once `bits` reaches its storage
    /// width, so that early return remains deliberately ahead of the guard.
    pub fn as_int_n(&self, bits: u64) -> Result<Self, BigIntError> {
        self.as_n(bits, true)
    }

    /// `QuickJS` 2026-06-04 behavior for `BigInt.asUintN(bits, value)`.
    ///
    /// This intentionally preserves the upstream signed-limb behavior instead
    /// of silently substituting the ECMA-262 result. In this release, a short
    /// negative value is returned unchanged for `bits >= 64`; heap truncation
    /// at a multiple of 64 can likewise produce a negative value. These are
    /// observable compatibility requirements for the selected baseline.
    ///
    /// # Errors
    ///
    /// Returns [`BigIntError::AllocationTooLarge`] at the same guarded
    /// truncation boundary as [`Self::as_int_n`].
    pub fn as_uint_n(&self, bits: u64) -> Result<Self, BigIntError> {
        self.as_n(bits, false)
    }

    fn normalize(value: BigInt) -> Self {
        if let Some(value) = value.to_i64() {
            Self(BigIntRepr::Short(value))
        } else {
            Self(BigIntRepr::Heap(Rc::new(value)))
        }
    }

    fn as_bigint(&self) -> Cow<'_, BigInt> {
        match &self.0 {
            BigIntRepr::Short(value) => Cow::Owned(BigInt::from(*value)),
            BigIntRepr::Heap(value) => Cow::Borrowed(value.as_ref()),
        }
    }

    fn checked_binary(
        &self,
        rhs: &Self,
        operation: impl FnOnce(&BigInt, &BigInt) -> BigInt,
    ) -> Result<Self, BigIntError> {
        let left = self.as_bigint();
        let right = rhs.as_bigint();
        Self::from_bigint(operation(left.as_ref(), right.as_ref())).map_err(|error| match error {
            BigIntError::BigIntTooLarge => BigIntError::AllocationTooLarge,
            error => error,
        })
    }

    fn checked_extending_binary(
        &self,
        rhs: &Self,
        operation: impl FnOnce(&BigInt, &BigInt) -> BigInt,
    ) -> Result<Self, BigIntError> {
        let left = self.as_bigint();
        let right = rhs.as_bigint();
        let result = operation(left.as_ref(), right.as_ref());
        if signed_limb_len(&result) > MAX_BIGINT_LIMBS + 1 {
            return Err(BigIntError::AllocationTooLarge);
        }
        Ok(Self::normalize(result))
    }

    fn ensure_operands_allocatable(&self, rhs: &Self) -> Result<(), BigIntError> {
        if self.exceeds_allocation_limit() || rhs.exceeds_allocation_limit() {
            Err(BigIntError::AllocationTooLarge)
        } else {
            Ok(())
        }
    }

    fn unchecked_binary(
        &self,
        rhs: &Self,
        operation: impl FnOnce(&BigInt, &BigInt) -> BigInt,
    ) -> Self {
        let left = self.as_bigint();
        let right = rhs.as_bigint();
        let result = operation(left.as_ref(), right.as_ref());
        debug_assert!(signed_limb_len(&result) <= MAX_BIGINT_LIMBS);
        Self::normalize(result)
    }

    fn is_one(&self) -> bool {
        matches!(self.0, BigIntRepr::Short(1))
    }

    fn is_negative_one(&self) -> bool {
        matches!(self.0, BigIntRepr::Short(-1))
    }

    fn is_odd(&self) -> bool {
        match &self.0 {
            BigIntRepr::Short(value) => value & 1 != 0,
            BigIntRepr::Heap(value) => value.magnitude().bit(0),
        }
    }

    fn to_u32(&self) -> Option<u32> {
        match &self.0 {
            BigIntRepr::Short(value) => u32::try_from(*value).ok(),
            BigIntRepr::Heap(value) => value.to_u32(),
        }
    }

    fn shift(&self, count: &Self, operator_shifts_left: bool) -> Result<Self, BigIntError> {
        let shifts_left = operator_shifts_left != count.is_negative();
        let count = count
            .magnitude_to_u64()
            .unwrap_or(u64::MAX)
            .min(i32::MAX as u64);
        if shifts_left {
            // js_bigint_shl returns zero before attempting an allocation.
            if self.is_zero() {
                return Ok(Self::zero());
            }
            let allocated_limbs = self
                .signed_limb_len()
                .checked_add(count / BIGINT_LIMB_BITS)
                .ok_or(BigIntError::ShiftTooLarge)?;
            if allocated_limbs > MAX_BIGINT_LIMBS {
                return Err(BigIntError::ShiftTooLarge);
            }
            let count = usize::try_from(count).map_err(|_| BigIntError::ShiftTooLarge)?;
            let result = self.as_bigint().as_ref() << count;
            if signed_limb_len(&result) > MAX_BIGINT_LIMBS + 1 {
                return Err(BigIntError::ShiftTooLarge);
            }
            Ok(Self::normalize(result))
        } else {
            let limb_offset = count / BIGINT_LIMB_BITS;
            if limb_offset >= self.signed_limb_len() {
                return Ok(self.right_shift_saturation());
            }
            if self.signed_limb_len() - limb_offset > MAX_BIGINT_LIMBS {
                return Err(BigIntError::ShiftTooLarge);
            }
            let count = usize::try_from(count).expect("bounded BigInt shift fits usize");
            Ok(Self::normalize(self.as_bigint().as_ref() >> count))
        }
    }

    fn right_shift_saturation(&self) -> Self {
        if self.is_negative() {
            Self::from(-1)
        } else {
            Self::zero()
        }
    }

    fn magnitude_to_u64(&self) -> Option<u64> {
        match &self.0 {
            BigIntRepr::Short(value) => Some(value.unsigned_abs()),
            BigIntRepr::Heap(value) => value.magnitude().to_u64(),
        }
    }

    fn as_n(&self, bits: u64, signed: bool) -> Result<Self, BigIntError> {
        if bits == 0 {
            return Ok(Self::zero());
        }

        // This early return is representation-dependent in upstream. In
        // particular, asUintN(128, -1n) returns -1n in QuickJS 2026-06-04.
        let storage_bits = self.signed_limb_len() * BIGINT_LIMB_BITS;
        if bits >= storage_bits {
            return Ok(self.clone());
        }

        let allocated_limbs = bits
            .checked_add(BIGINT_LIMB_BITS - 1)
            .ok_or(BigIntError::AllocationTooLarge)?
            / BIGINT_LIMB_BITS;
        if allocated_limbs > MAX_BIGINT_LIMBS {
            return Err(BigIntError::AllocationTooLarge);
        }

        // At this point bits is within the nominal allocation guard.
        let bits_usize = usize::try_from(bits).expect("bounded BigInt bit width fits usize");
        let modulus = BigInt::one() << bits_usize;
        let mut truncated = self.as_bigint().as_ref() % &modulus;
        if truncated.sign() == Sign::Minus {
            truncated += &modulus;
        }

        // js_bigint_asUintN writes a whole signed limb when bits is a multiple
        // of JS_LIMB_BITS. If that limb's top bit is set, normalization observes
        // a negative result even for asUintN. Preserve that release behavior.
        let interpret_as_signed = signed || bits & (BIGINT_LIMB_BITS - 1) == 0;
        if interpret_as_signed && truncated.bit(bits - 1) {
            truncated -= modulus;
        }
        Ok(Self::normalize(truncated))
    }
}

impl Default for JsBigInt {
    fn default() -> Self {
        Self::zero()
    }
}

impl From<i64> for JsBigInt {
    fn from(value: i64) -> Self {
        Self(BigIntRepr::Short(value))
    }
}

impl From<i32> for JsBigInt {
    fn from(value: i32) -> Self {
        Self::from(i64::from(value))
    }
}

impl From<u32> for JsBigInt {
    fn from(value: u32) -> Self {
        Self::from(i64::from(value))
    }
}

impl From<u64> for JsBigInt {
    fn from(value: u64) -> Self {
        if let Ok(value) = i64::try_from(value) {
            Self::from(value)
        } else {
            Self::normalize(BigInt::from(value))
        }
    }
}

impl From<i128> for JsBigInt {
    fn from(value: i128) -> Self {
        Self::normalize(BigInt::from(value))
    }
}

impl From<u128> for JsBigInt {
    fn from(value: u128) -> Self {
        Self::normalize(BigInt::from(value))
    }
}

impl TryFrom<BigInt> for JsBigInt {
    type Error = BigIntError;

    fn try_from(value: BigInt) -> Result<Self, Self::Error> {
        Self::from_bigint(value)
    }
}

impl FromStr for JsBigInt {
    type Err = BigIntError;

    fn from_str(source: &str) -> Result<Self, Self::Err> {
        Self::parse_js_string(source)
    }
}

impl Ord for JsBigInt {
    fn cmp(&self, other: &Self) -> Ordering {
        match (&self.0, &other.0) {
            (BigIntRepr::Short(left), BigIntRepr::Short(right)) => left.cmp(right),
            (BigIntRepr::Heap(left), BigIntRepr::Heap(right)) => left.cmp(right),
            // A normalized heap value lies outside i64, so its sign decides.
            (BigIntRepr::Short(_), BigIntRepr::Heap(heap)) => match heap.sign() {
                Sign::Minus => Ordering::Greater,
                _ => Ordering::Less,
            },
            (BigIntRepr::Heap(heap), BigIntRepr::Short(_)) => match heap.sign() {
                Sign::Minus => Ordering::Less,
                _ => Ordering::Greater,
            },
        }
    }
}

impl PartialOrd for JsBigInt {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Display for JsBigInt {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            BigIntRepr::Short(value) => value.fmt(formatter),
            BigIntRepr::Heap(value) => value.fmt(formatter),
        }
    }
}

impl fmt::Debug for JsBigInt {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.0 {
            BigIntRepr::Short(value) => formatter.debug_tuple("ShortBigInt").field(value).finish(),
            BigIntRepr::Heap(value) => formatter.debug_tuple("BigInt").field(value).finish(),
        }
    }
}

fn validate_radix(radix: u32) -> Result<(), BigIntError> {
    if (2..=36).contains(&radix) {
        Ok(())
    } else {
        Err(BigIntError::InvalidRadix(radix))
    }
}

fn parse_digits(digits: &str, radix: u32, negative: bool) -> Result<JsBigInt, BigIntError> {
    validate_radix(radix)?;
    if digits.is_empty()
        || !digits
            .as_bytes()
            .iter()
            .all(|byte| is_radix_digit(*byte, radix))
    {
        return Err(BigIntError::InvalidSyntax);
    }

    // js_bigint_from_string discards leading zeroes before its conservative
    // source-length guard, so an arbitrarily long spelling of zero stays zero.
    let significant_digits = digits.trim_start_matches('0');
    if significant_digits.is_empty() {
        return Ok(JsBigInt::zero());
    }
    let digit_count = u64::try_from(significant_digits.len()).unwrap_or(u64::MAX);
    if digit_count > MAX_BIGINT_BITS {
        return Err(BigIntError::AllocationTooLarge);
    }

    // `js_bigint_from_string` allocates from a conservative source-width
    // estimate before it parses any digits. The extra sign limb makes an
    // estimate of exactly MAX_BIGINT_BITS fail even when the normalized value
    // would fit in 16,384 limbs. This is observable at the first failing
    // lengths for bases 2, 8, 10 and 16, so checking only the final value's
    // signed limb length is insufficient.
    let log2_radix = u64::from(u32::BITS - (radix - 1).leading_zeros());
    let estimated_bits = if radix == 10 {
        (digit_count * 27).div_ceil(8)
    } else {
        digit_count * log2_radix
    };
    let estimated_limbs = estimated_bits / BIGINT_LIMB_BITS + 1;
    if estimated_limbs > MAX_BIGINT_LIMBS {
        return Err(BigIntError::AllocationTooLarge);
    }

    let magnitude = BigUint::parse_bytes(significant_digits.as_bytes(), radix)
        .ok_or(BigIntError::InvalidSyntax)?;
    let sign = if negative && !magnitude.is_zero() {
        Sign::Minus
    } else if magnitude.is_zero() {
        Sign::NoSign
    } else {
        Sign::Plus
    };
    JsBigInt::from_bigint(BigInt::from_biguint(sign, magnitude))
}

fn is_radix_digit(byte: u8, radix: u32) -> bool {
    let value = match byte {
        b'0'..=b'9' => u32::from(byte - b'0'),
        b'a'..=b'z' => u32::from(byte - b'a') + 10,
        b'A'..=b'Z' => u32::from(byte - b'A') + 10,
        _ => return false,
    };
    value < radix
}

fn short_to_string_radix(value: i64, radix: u32) -> String {
    const DIGITS: &[u8; 36] = b"0123456789abcdefghijklmnopqrstuvwxyz";

    if value == 0 {
        return "0".to_owned();
    }

    let negative = value < 0;
    let mut magnitude = value.unsigned_abs();
    let radix = u64::from(radix);
    let mut reversed = Vec::with_capacity(65);
    while magnitude != 0 {
        let digit = usize::try_from(magnitude % radix).expect("radix digit fits usize");
        reversed.push(DIGITS[digit]);
        magnitude /= radix;
    }
    if negative {
        reversed.push(b'-');
    }
    reversed.reverse();
    String::from_utf8(reversed).expect("BigInt formatting only emits ASCII")
}

fn signed_limb_len(value: &BigInt) -> u64 {
    let signed_bits = match value.sign() {
        Sign::NoSign => 1,
        Sign::Plus => value.bits() + 1,
        // -m needs bits(m - 1) + 1 two's-complement bits; m - 1 only loses a
        // bit when m is a power of two, so no copy of the magnitude is needed.
        Sign::Minus => {
            let magnitude = value.magnitude();
            let bits = magnitude.bits();
            if magnitude.trailing_zeros() == Some(bits - 1) {
                bits
            } else {
                bits + 1
            }
        }
    };
    signed_bits.div_ceil(BIGINT_LIMB_BITS).max(1)
}

#[cfg(test)]
mod tests {
    use super::{BIGINT_LIMB_BITS, BigIntError, JsBigInt, MAX_BIGINT_BITS, MAX_BIGINT_LIMBS};

    fn bigint(source: &str) -> JsBigInt {
        JsBigInt::parse_js_string(source).unwrap()
    }

    #[test]
    fn normalizes_short_values_and_promotes_overflow() {
        let max = JsBigInt::from(i64::MAX);
        let min = JsBigInt::from(i64::MIN);
        assert!(max.is_short());
        assert!(min.is_short());

        let above_max = max.add(&JsBigInt::one()).unwrap();
        let below_min = min.sub(&JsBigInt::one()).unwrap();
        assert!(!above_max.is_short());
        assert!(!below_min.is_short());
        assert!(max < above_max && min < above_max && below_min < min && below_min < max);
        assert!(above_max > max && below_min < above_max && max > below_min);
        assert_eq!(above_max.to_string(), "9223372036854775808");
        assert_eq!(below_min.to_string(), "-9223372036854775809");

        assert_eq!(above_max.sub(&JsBigInt::one()).unwrap(), max);
        assert_eq!(below_min.add(&JsBigInt::one()).unwrap(), min);
        assert!(above_max.sub(&JsBigInt::one()).unwrap().is_short());
    }

    #[test]
    fn update_decrement_preserves_pinned_unsigned_opcode_quirk() {
        assert_eq!(
            JsBigInt::from(4).update_decrement().unwrap(),
            JsBigInt::from(3)
        );
        assert_eq!(
            JsBigInt::from(i64::MIN).update_decrement().unwrap(),
            bigint("-9223372032559808513")
        );
        assert_eq!(
            bigint("9223372036854775808").update_decrement().unwrap(),
            bigint("9223372041149743103")
        );
        assert_eq!(
            bigint("-9223372036854775809").update_decrement().unwrap(),
            bigint("-9223372032559808514")
        );
        assert_eq!(
            bigint("9223372036854775808").sub(&JsBigInt::one()).unwrap(),
            JsBigInt::from(i64::MAX)
        );
    }

    #[test]
    fn signed_limb_width_matches_quickjs_twos_complement_normalization() {
        assert_eq!(JsBigInt::from(i64::MAX).signed_limb_len(), 1);
        assert_eq!(JsBigInt::from(i64::MIN).signed_limb_len(), 1);
        assert_eq!(bigint("9223372036854775808").signed_limb_len(), 2);
        assert_eq!(bigint("-9223372036854775809").signed_limb_len(), 2);
        assert_eq!(
            bigint("170141183460469231731687303715884105727").signed_limb_len(),
            2
        );
        assert_eq!(
            bigint("170141183460469231731687303715884105728").signed_limb_len(),
            3
        );
        assert_eq!(
            bigint("-170141183460469231731687303715884105728").signed_limb_len(),
            2
        );
        assert_eq!(
            bigint("-170141183460469231731687303715884105729").signed_limb_len(),
            3
        );
    }

    #[test]
    fn copy_free_signed_limb_len_matches_decremented_magnitude_formula() {
        use num_bigint::{BigInt, Sign};
        fn reference(value: &BigInt) -> u64 {
            let bits = match value.sign() {
                Sign::NoSign => 1,
                Sign::Plus => value.bits() + 1,
                Sign::Minus => (value.magnitude() - 1u8).bits() + 1,
            };
            bits.div_ceil(BIGINT_LIMB_BITS).max(1)
        }
        let mut samples = vec![BigInt::from(0)];
        for shift in 0..300_u32 {
            let power = BigInt::from(1) << shift;
            samples.extend([&power - 1, power.clone(), &power + 1]);
        }
        let mut state = BigInt::from(0x9e37_79b9_7f4a_7c15_u64);
        for _ in 0..200 {
            state = (&state * 6_364_136_223_846_793_005_u64 + 1_442_695_040_888_963_407_u64)
                % (BigInt::from(1) << 400_u32);
            samples.push(&state >> (state.bits() % 397));
        }
        for magnitude in samples {
            for value in [magnitude.clone(), -magnitude] {
                assert_eq!(super::signed_limb_len(&value), reference(&value), "{value}");
            }
        }
    }

    #[test]
    fn cmp_f64_matches_exact_arbitrary_precision_comparison() {
        use num_bigint::BigInt;
        use num_traits::FromPrimitive;
        use std::cmp::Ordering;
        fn reference(left: &JsBigInt, number: f64) -> Option<Ordering> {
            if number.is_nan() {
                return None;
            }
            if number.is_infinite() {
                return Some(if number > 0.0 {
                    Ordering::Less
                } else {
                    Ordering::Greater
                });
            }
            let truncated = BigInt::from_f64(number.trunc()).unwrap();
            Some(
                left.to_bigint()
                    .cmp(&truncated)
                    .then(0.0.partial_cmp(&number.fract()).unwrap()),
            )
        }
        let mut values = vec![JsBigInt::from(i64::MIN), JsBigInt::from(i64::MAX)];
        for text in [
            "0",
            "1",
            "9007199254740993",
            "9223372036854775808",
            "1000000000000000000000000000000",
        ] {
            for sign in ["", "-"] {
                let value = bigint(&format!("{sign}{text}"));
                values.extend([value.sub(&JsBigInt::one()).unwrap(), value.clone()]);
                values.push(value.add(&JsBigInt::one()).unwrap());
            }
        }
        let mut numbers = vec![
            f64::NAN,
            f64::INFINITY,
            -0.0,
            0.5,
            1.5,
            1e20,
            1e30,
            f64::MAX,
        ];
        numbers.extend([2f64.powi(53), 2f64.powi(63), 2f64.powi(64), 2f64.powi(99)]);
        numbers.extend(values.iter().map(JsBigInt::to_f64));
        for number in numbers.clone() {
            let next = f64::from_bits(number.to_bits() + 1);
            numbers.extend([next, f64::from_bits(number.to_bits().saturating_sub(1))]);
        }
        for value in &values {
            for number in numbers.iter().flat_map(|number| [*number, -*number]) {
                assert_eq!(
                    value.cmp_f64(number),
                    reference(value, number),
                    "{value} vs {number}"
                );
            }
        }
    }

    #[test]
    fn parses_string_to_bigint_forms_and_formats_all_radices() {
        assert_eq!(bigint(""), JsBigInt::zero());
        assert_eq!(bigint("\u{00a0}  +123 \u{feff}"), JsBigInt::from(123));
        assert_eq!(bigint("-00123"), JsBigInt::from(-123));
        assert_eq!(bigint("0b101010"), JsBigInt::from(42));
        assert_eq!(bigint("0O77"), JsBigInt::from(63));
        assert_eq!(bigint("0xabcdef"), JsBigInt::from(0x00ab_cdef));

        let large = bigint("1267650600228229401496703205376");
        assert_eq!(
            large.to_string_radix(10).unwrap(),
            "1267650600228229401496703205376"
        );
        assert_eq!(
            large.to_string_radix(8).unwrap(),
            "2000000000000000000000000000000000"
        );
        assert_eq!(
            large.to_string_radix(16).unwrap(),
            "10000000000000000000000000"
        );
        assert_eq!(
            bigint("-1267650600228229401496703205376")
                .to_string_radix(36)
                .unwrap(),
            "-3ewfdnca0n6ld1ggvfgg"
        );

        assert_eq!(JsBigInt::parse_radix("z", 36).unwrap(), JsBigInt::from(35));
        assert_eq!(
            JsBigInt::parse_radix("+ff", 16).unwrap(),
            JsBigInt::from(255)
        );
        assert_eq!(
            JsBigInt::parse_radix("-ff", 16).unwrap(),
            JsBigInt::from(-255)
        );
    }

    #[test]
    fn parsing_preserves_the_upstream_conservative_allocation_guard() {
        for (prefix, digit, first_failing_length) in [
            ("0b", '1', 1_048_576),
            ("0o", '7', 349_526),
            ("", '9', 310_689),
            ("0x", 'f', 262_144),
        ] {
            let source = format!("{prefix}{}", digit.to_string().repeat(first_failing_length));
            assert_eq!(
                JsBigInt::parse_js_string(&source),
                Err(BigIntError::AllocationTooLarge),
                "radix spelling starting with {prefix:?} crossed the wrong allocation boundary"
            );
        }

        let leading_zeroes = format!("0x{}1", "0".repeat(262_144));
        assert_eq!(
            JsBigInt::parse_js_string(&leading_zeroes).unwrap(),
            JsBigInt::one(),
            "leading zeroes must be discarded before the conservative guard"
        );
    }

    #[test]
    fn rejects_invalid_string_to_bigint_forms() {
        for source in ["+", "-", "-0x1", "+0x1", "0x", "1_0", "1n", "\0a", " 12 r "] {
            assert_eq!(
                JsBigInt::parse_js_string(source),
                Err(BigIntError::InvalidSyntax)
            );
        }
        assert_eq!(
            JsBigInt::parse_radix("2", 2),
            Err(BigIntError::InvalidSyntax)
        );
        assert_eq!(
            JsBigInt::parse_radix("1", 1),
            Err(BigIntError::InvalidRadix(1))
        );
        assert_eq!(
            JsBigInt::one().to_string_radix(37),
            Err(BigIntError::InvalidRadix(37))
        );
    }

    #[test]
    fn arithmetic_matches_upstream_large_integer_vectors() {
        let three_to_100 = JsBigInt::from(3).pow(&JsBigInt::from(100)).unwrap();
        assert_eq!(
            three_to_100.to_string(),
            "515377520732011331036461129765621272702107522001"
        );

        let dividend = bigint("3213213213213213432453243");
        let divisor = bigint("123434343439");
        assert_eq!(
            dividend.div(&divisor).unwrap().to_string(),
            "26031760073331"
        );
        assert_eq!(dividend.rem(&divisor).unwrap().to_string(), "26953727934");
        let negative = dividend.neg().unwrap();
        assert_eq!(
            negative.div(&divisor).unwrap().to_string(),
            "-26031760073331"
        );
        assert_eq!(negative.rem(&divisor).unwrap().to_string(), "-26953727934");

        assert_eq!(
            JsBigInt::from(-2)
                .pow(&JsBigInt::from(127))
                .unwrap()
                .to_string(),
            "-170141183460469231731687303715884105728"
        );
        assert_eq!(
            JsBigInt::from(7)
                .pow(&JsBigInt::from(20))
                .unwrap()
                .to_string(),
            "79792266297612001"
        );
    }

    #[test]
    fn division_promotes_min_overflow_and_reports_zero() {
        let promoted = JsBigInt::from(i64::MIN).div(&JsBigInt::from(-1)).unwrap();
        assert_eq!(promoted.to_string(), "9223372036854775808");
        assert!(!promoted.is_short());
        assert_eq!(
            JsBigInt::from(i64::MIN).rem(&JsBigInt::from(-1)).unwrap(),
            JsBigInt::zero()
        );
        assert_eq!(
            JsBigInt::one().div(&JsBigInt::zero()),
            Err(BigIntError::DivisionByZero)
        );
        assert_eq!(
            JsBigInt::one().rem(&JsBigInt::zero()),
            Err(BigIntError::DivisionByZero)
        );
    }

    #[test]
    fn pow_handles_sign_shortcuts_and_explicit_errors() {
        assert_eq!(
            JsBigInt::from(123).pow(&JsBigInt::zero()).unwrap(),
            JsBigInt::one()
        );
        assert_eq!(
            JsBigInt::from(-1)
                .pow(&bigint("999999999999999999999999999999999999999"))
                .unwrap(),
            JsBigInt::from(-1)
        );
        assert_eq!(
            JsBigInt::from(2).pow(&JsBigInt::from(-1)),
            Err(BigIntError::NegativeExponent)
        );
        assert_eq!(
            JsBigInt::from(2).pow(&bigint("2147483648")),
            Err(BigIntError::BigIntTooLarge)
        );

        let half_width_base = JsBigInt::one()
            .shl(&JsBigInt::from(MAX_BIGINT_BITS / 2 - 2))
            .unwrap()
            .add(&JsBigInt::one())
            .unwrap();
        assert_eq!(
            half_width_base.pow(&JsBigInt::from(2)).unwrap(),
            half_width_base.mul(&half_width_base).unwrap()
        );

        let max_power_of_two = JsBigInt::from(2)
            .pow(&JsBigInt::from(MAX_BIGINT_BITS - 2))
            .unwrap();
        assert_eq!(max_power_of_two.signed_limb_len(), MAX_BIGINT_LIMBS);
        assert_eq!(
            JsBigInt::from(2).pow(&JsBigInt::from(MAX_BIGINT_BITS - 1)),
            Err(BigIntError::AllocationTooLarge)
        );
        assert_eq!(
            JsBigInt::from(-2).pow(&JsBigInt::from(MAX_BIGINT_BITS)),
            Err(BigIntError::AllocationTooLarge)
        );
        assert_eq!(
            JsBigInt::from(2).pow(&JsBigInt::from(MAX_BIGINT_BITS + 1)),
            Err(BigIntError::BigIntTooLarge)
        );
        assert!(
            JsBigInt::from(-2)
                .pow(&JsBigInt::from(MAX_BIGINT_BITS - 1))
                .unwrap()
                .is_negative()
        );
    }

    #[test]
    fn shifts_match_arithmetic_and_negative_count_semantics() {
        let value = bigint("0x5a4653ca673768565b41f775");
        assert_eq!(
            value.shl(&JsBigInt::from(78)).unwrap().to_string(),
            "8443945299673273647701379149826607537748959488376832"
        );
        assert_eq!(
            value.shr(&JsBigInt::from(78)).unwrap(),
            JsBigInt::from(92441)
        );
        assert_eq!(
            value.neg().unwrap().shr(&JsBigInt::from(78)).unwrap(),
            JsBigInt::from(-92442)
        );
        assert_eq!(
            JsBigInt::from(8).shl(&JsBigInt::from(-1)).unwrap(),
            JsBigInt::from(4)
        );
        assert_eq!(
            JsBigInt::from(8).shr(&JsBigInt::from(-2)).unwrap(),
            JsBigInt::from(32)
        );
    }

    #[test]
    fn excessive_left_shift_is_an_explicit_error_but_right_shift_saturates() {
        let huge = JsBigInt::from(MAX_BIGINT_BITS + 1);
        assert_eq!(JsBigInt::one().shl(&huge), Err(BigIntError::ShiftTooLarge));
        assert_eq!(JsBigInt::zero().shl(&huge).unwrap(), JsBigInt::zero());
        assert_eq!(JsBigInt::one().shr(&huge).unwrap(), JsBigInt::zero());
        assert_eq!(JsBigInt::from(-1).shr(&huge).unwrap(), JsBigInt::from(-1));
        assert_eq!(
            JsBigInt::one().shr(&huge.neg().unwrap()),
            Err(BigIntError::ShiftTooLarge)
        );
    }

    #[test]
    fn shift_preserves_quickjs_unguarded_sign_limb_extension() {
        let boundary_count = JsBigInt::from(MAX_BIGINT_BITS - 1);
        let boundary = JsBigInt::one().shl(&boundary_count).unwrap();
        assert_eq!(boundary.signed_limb_len(), MAX_BIGINT_LIMBS + 1);
        assert_eq!(boundary.shr(&boundary_count).unwrap(), JsBigInt::one());

        assert_eq!(
            boundary.shl(&JsBigInt::zero()),
            Err(BigIntError::ShiftTooLarge)
        );
        assert_eq!(
            boundary.shr(&JsBigInt::zero()),
            Err(BigIntError::ShiftTooLarge)
        );
        assert_eq!(
            boundary.bit_and(&JsBigInt::from(-1)),
            Err(BigIntError::AllocationTooLarge)
        );
        assert_eq!(boundary.bit_not(), Err(BigIntError::AllocationTooLarge));
        assert_eq!(
            boundary.add(&JsBigInt::zero()),
            Err(BigIntError::AllocationTooLarge)
        );
        assert_eq!(boundary.neg(), Err(BigIntError::AllocationTooLarge));

        assert_eq!(
            JsBigInt::one().shl(&JsBigInt::from(MAX_BIGINT_BITS)),
            Err(BigIntError::ShiftTooLarge)
        );
        assert_eq!(
            JsBigInt::zero().shl(&JsBigInt::from(u64::MAX)).unwrap(),
            JsBigInt::zero()
        );

        let near_boundary = JsBigInt::one()
            .shl(&JsBigInt::from(MAX_BIGINT_BITS - 2))
            .unwrap();
        assert_eq!(near_boundary.add(&JsBigInt::zero()).unwrap(), near_boundary);
        assert_eq!(
            near_boundary.bit_and(&JsBigInt::from(-1)).unwrap(),
            near_boundary
        );
        assert_eq!(
            near_boundary.mul(&JsBigInt::zero()),
            Err(BigIntError::AllocationTooLarge)
        );
        assert_eq!(
            near_boundary.div(&JsBigInt::one()),
            Err(BigIntError::AllocationTooLarge)
        );
        assert_eq!(
            near_boundary.rem(&JsBigInt::one()),
            Err(BigIntError::AllocationTooLarge)
        );
        assert_eq!(near_boundary.pow(&JsBigInt::one()).unwrap(), near_boundary);
        let added_boundary = near_boundary.add(&near_boundary).unwrap();
        assert_eq!(added_boundary, boundary);

        let negative_boundary = JsBigInt::from(-1)
            .shl(&JsBigInt::from(MAX_BIGINT_BITS - 1))
            .unwrap();
        assert_eq!(negative_boundary.neg().unwrap(), boundary);
        assert_eq!(
            boundary.pow(&JsBigInt::one()),
            Err(BigIntError::AllocationTooLarge)
        );
        assert_eq!(boundary.pow(&JsBigInt::zero()).unwrap(), JsBigInt::one());
    }

    #[test]
    fn bitwise_operations_use_infinite_twos_complement() {
        assert_eq!(
            JsBigInt::from(0x5a65_3ca6).bit_not().unwrap(),
            JsBigInt::from(-1_516_584_103)
        );
        let left = JsBigInt::from(0x5a46_3ca6);
        let right = JsBigInt::from(0x6737_6856);
        assert_eq!(left.bit_or(&right).unwrap(), JsBigInt::from(2_138_537_206));
        assert_eq!(left.bit_and(&right).unwrap(), JsBigInt::from(1_107_699_718));
        assert_eq!(left.bit_xor(&right).unwrap(), JsBigInt::from(1_030_837_488));

        let huge = bigint("1208925819614629174706176"); // 2^80
        assert_eq!(
            huge.bit_or(&JsBigInt::from(-1)).unwrap(),
            JsBigInt::from(-1)
        );
        assert_eq!(huge.bit_and(&JsBigInt::from(-1)).unwrap(), huge);
    }

    #[test]
    fn comparison_is_numeric_across_storage_classes() {
        let short = JsBigInt::from(i64::MAX);
        let heap = short.add(&JsBigInt::one()).unwrap();
        assert!(short < heap);
        assert!(bigint("-9223372036854775809") < JsBigInt::from(i64::MIN));
        assert_eq!(
            bigint("123456789012345678901234567890"),
            bigint("123456789012345678901234567890")
        );
    }

    #[test]
    fn conversion_to_f64_rounds_ties_to_even_and_overflows_like_quickjs() {
        assert_eq!(JsBigInt::from(42).to_f64(), 42.0);
        assert_eq!(bigint("9007199254740993").to_f64(), 9_007_199_254_740_992.0);
        assert_eq!(bigint("9007199254740995").to_f64(), 9_007_199_254_740_996.0);
        assert_eq!(
            bigint("-9007199254740995").to_f64(),
            -9_007_199_254_740_996.0
        );

        let two_to_1023 = JsBigInt::one().shl(&JsBigInt::from(1023)).unwrap();
        assert_eq!(two_to_1023.to_f64(), 2.0_f64.powi(1023));
        let two_to_1024 = two_to_1023.shl(&JsBigInt::one()).unwrap();
        assert_eq!(two_to_1024.to_f64(), f64::INFINITY);
        assert_eq!(two_to_1024.neg().unwrap().to_f64(), f64::NEG_INFINITY);
    }

    #[test]
    fn as_int_n_truncates_and_sign_extends() {
        assert_eq!(JsBigInt::from(257).as_int_n(8).unwrap(), JsBigInt::one());
        assert_eq!(JsBigInt::from(255).as_int_n(8).unwrap(), JsBigInt::from(-1));
        assert_eq!(
            JsBigInt::from(-129).as_int_n(8).unwrap(),
            JsBigInt::from(127)
        );
        assert_eq!(
            bigint("18446744073709551616").as_int_n(65).unwrap(),
            bigint("-18446744073709551616")
        );
        assert_eq!(
            bigint("36893488147419103231").as_int_n(65).unwrap(),
            JsBigInt::from(-1)
        );
        assert_eq!(
            bigint("999999999999999999999").as_int_n(0).unwrap(),
            JsBigInt::zero()
        );
    }

    #[test]
    fn quickjs_2026_as_uint_n_preserves_signed_limb_quirks() {
        // These results were verified against qjs 2026-06-04. They differ from
        // ECMA-262/Node, but observable baseline parity takes precedence here.
        assert_eq!(
            JsBigInt::from(-1).as_uint_n(64).unwrap(),
            JsBigInt::from(-1)
        );
        assert_eq!(
            JsBigInt::from(-1).as_uint_n(128).unwrap(),
            JsBigInt::from(-1)
        );
        assert_eq!(
            bigint("9223372036854775808").as_uint_n(64).unwrap(),
            JsBigInt::from(i64::MIN)
        );
        assert_eq!(
            bigint("18446744073709551615").as_uint_n(64).unwrap(),
            JsBigInt::from(-1)
        );
        assert_eq!(
            bigint("-18446744073709551616").as_uint_n(128).unwrap(),
            bigint("-18446744073709551616")
        );
        // Non-limb-aligned truncation clears the spare sign bits and is
        // positive, matching js_bigint_asUintN's logical shift path.
        assert_eq!(
            bigint("-18446744073709551616").as_uint_n(65).unwrap(),
            bigint("18446744073709551616")
        );
    }

    #[test]
    fn as_n_preserves_the_extended_limb_allocation_gap() {
        let extended = JsBigInt::one()
            .shl(&JsBigInt::from(MAX_BIGINT_BITS - 1))
            .unwrap();
        assert_eq!(extended.signed_limb_len(), MAX_BIGINT_LIMBS + 1);

        assert_eq!(
            extended.as_uint_n(MAX_BIGINT_BITS - 1).unwrap(),
            JsBigInt::zero()
        );
        assert_eq!(
            extended.as_int_n(MAX_BIGINT_BITS - 1).unwrap(),
            JsBigInt::zero()
        );

        let at_nominal_limit = extended.as_uint_n(MAX_BIGINT_BITS).unwrap();
        let exact_negative = JsBigInt::normalize(-extended.to_bigint());
        assert_eq!(at_nominal_limit, exact_negative);
        assert_eq!(extended.as_int_n(MAX_BIGINT_BITS).unwrap(), exact_negative);

        for bits in MAX_BIGINT_BITS + 1..MAX_BIGINT_BITS + BIGINT_LIMB_BITS {
            assert_eq!(
                extended.as_uint_n(bits),
                Err(BigIntError::AllocationTooLarge)
            );
            assert_eq!(
                extended.as_int_n(bits),
                Err(BigIntError::AllocationTooLarge)
            );
        }
        assert_eq!(
            extended
                .as_uint_n(MAX_BIGINT_BITS + BIGINT_LIMB_BITS)
                .unwrap(),
            extended
        );
        assert_eq!(
            extended
                .as_int_n(MAX_BIGINT_BITS + BIGINT_LIMB_BITS + 1)
                .unwrap(),
            extended
        );
        assert_eq!(extended.as_uint_n(u64::MAX).unwrap(), extended);
    }

    #[test]
    fn integral_f64_conversion_preserves_the_exact_binary_value() {
        assert_eq!(JsBigInt::from_integral_f64(-0.0).unwrap(), JsBigInt::zero());
        assert_eq!(
            JsBigInt::from_integral_f64(9_007_199_254_740_991.0).unwrap(),
            bigint("9007199254740991")
        );
        assert_eq!(
            JsBigInt::from_integral_f64(9_007_199_254_740_992.0).unwrap(),
            bigint("9007199254740992")
        );
        assert_eq!(
            JsBigInt::from_integral_f64(9_007_199_254_740_994.0).unwrap(),
            bigint("9007199254740994")
        );

        let max_finite = JsBigInt::one()
            .shl(&JsBigInt::from(1024))
            .unwrap()
            .sub(&JsBigInt::one().shl(&JsBigInt::from(971)).unwrap())
            .unwrap();
        assert_eq!(JsBigInt::from_integral_f64(f64::MAX).unwrap(), max_finite);
        assert_eq!(
            JsBigInt::from_integral_f64(f64::MIN).unwrap(),
            max_finite.neg().unwrap()
        );

        assert!(JsBigInt::from_integral_f64(1.5).is_none());
        assert!(JsBigInt::from_integral_f64(f64::NAN).is_none());
        assert!(JsBigInt::from_integral_f64(f64::INFINITY).is_none());
        assert!(JsBigInt::from_integral_f64(f64::NEG_INFINITY).is_none());
    }

    #[test]
    fn arbitrary_precision_is_not_capped_at_i128() {
        let value = JsBigInt::from(3).pow(&JsBigInt::from(1000)).unwrap();
        assert!(value.magnitude_bits() > 128);
        let text = value.to_string();
        assert_eq!(text.len(), 478);
        assert!(text.starts_with("1322070819480806636890455259752144365965"));
        assert_eq!(JsBigInt::parse_js_string(&text).unwrap(), value);
    }
}