inlean-runtime 0.2.0

Runtime support for Rust code generated from Lean by inlean
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
//! Arithmetic on natural numbers of any size.
//!
//! A number is a slice of 64-bit limbs, least significant first, without leading zero
//! limbs; zero is the empty slice. The algorithms are the schoolbook ones: simple, and fast
//! enough for numbers of a few hundred digits.

use std::cmp::Ordering;

/// How many limbs a number holds without an allocation: enough for the product of two
/// 256-bit numbers.
const INLINE: usize = 8;

/// The limbs of a number being computed: a vector that stays on the stack while it is short.
pub struct Limbs {
    inline: [u64; INLINE],
    /// The length while the limbs are inline; `heap` holds them once they outgrow that.
    len: usize,
    spilled: bool,
    heap: Vec<u64>,
}

impl Limbs {
    pub fn new() -> Limbs {
        Limbs { inline: [0; INLINE], len: 0, spilled: false, heap: Vec::new() }
    }

    pub fn zeros(len: usize) -> Limbs {
        let mut limbs = Limbs::new();
        match len <= INLINE {
            // The inline limbs start as zeros.
            true => limbs.len = len,
            false => limbs.resize(len, 0),
        }
        limbs
    }

    pub fn push(&mut self, limb: u64) {
        if !self.spilled && self.len < INLINE {
            self.inline[self.len] = limb;
            self.len += 1;
        } else {
            self.spill(1).push(limb);
        }
    }

    pub fn pop(&mut self) -> Option<u64> {
        if self.spilled {
            return self.heap.pop();
        }
        self.len = self.len.checked_sub(1)?;
        Some(self.inline[self.len])
    }

    #[cfg(test)]
    pub fn truncate(&mut self, len: usize) {
        match self.spilled {
            true => self.heap.truncate(len),
            false => self.len = self.len.min(len),
        }
    }

    pub fn resize(&mut self, len: usize, limb: u64) {
        if !self.spilled && len <= INLINE {
            if len > self.len {
                self.inline[self.len..len].fill(limb);
            }
            self.len = len;
        } else {
            self.spill(len).resize(len, limb);
        }
    }

    pub fn extend_from_slice(&mut self, limbs: &[u64]) {
        if !self.spilled && self.len + limbs.len() <= INLINE {
            self.inline[self.len..self.len + limbs.len()].copy_from_slice(limbs);
            self.len += limbs.len();
        } else {
            self.spill(limbs.len()).extend_from_slice(limbs);
        }
    }

    /// Moves the limbs to the heap, with room for `more`.
    fn spill(&mut self, more: usize) -> &mut Vec<u64> {
        if !self.spilled {
            self.heap = Vec::with_capacity(self.len + more);
            self.heap.extend_from_slice(&self.inline[..self.len]);
            self.spilled = true;
        }
        &mut self.heap
    }
}

impl std::ops::Deref for Limbs {
    type Target = [u64];

    fn deref(&self) -> &[u64] {
        match self.spilled {
            true => &self.heap,
            false => &self.inline[..self.len],
        }
    }
}

impl std::ops::DerefMut for Limbs {
    fn deref_mut(&mut self) -> &mut [u64] {
        match self.spilled {
            true => &mut self.heap,
            false => &mut self.inline[..self.len],
        }
    }
}

impl From<&[u64]> for Limbs {
    fn from(limbs: &[u64]) -> Limbs {
        let mut out = Limbs::new();
        out.extend_from_slice(limbs);
        out
    }
}

impl FromIterator<u64> for Limbs {
    fn from_iter<I: IntoIterator<Item = u64>>(limbs: I) -> Limbs {
        let mut out = Limbs::new();
        for limb in limbs {
            out.push(limb);
        }
        out
    }
}

fn trim(mut limbs: Limbs) -> Limbs {
    while limbs.last() == Some(&0) {
        limbs.pop();
    }
    limbs
}

pub fn compare(a: &[u64], b: &[u64]) -> Ordering {
    a.len().cmp(&b.len()).then_with(|| a.iter().rev().cmp(b.iter().rev()))
}

pub fn add(a: &[u64], b: &[u64]) -> Limbs {
    let (long, short) = if a.len() >= b.len() { (a, b) } else { (b, a) };
    let mut out = Limbs::zeros(long.len() + 1);
    let limbs: &mut [u64] = &mut out;
    limbs[..long.len()].copy_from_slice(long);
    let mut carry = false;
    for (i, limb) in limbs.iter_mut().enumerate() {
        if i >= short.len() && !carry {
            break;
        }
        let (sum, c1) = limb.overflowing_add(short.get(i).copied().unwrap_or(0));
        let (sum, c2) = sum.overflowing_add(carry as u64);
        carry = c1 || c2;
        *limb = sum;
    }
    trim(out)
}

/// `a - b`, for `a >= b`.
pub fn sub(a: &[u64], b: &[u64]) -> Limbs {
    let mut out = Limbs::from(a);
    let mut borrow = false;
    for (i, limb) in out.iter_mut().enumerate() {
        if i >= b.len() && !borrow {
            break;
        }
        let (diff, b1) = limb.overflowing_sub(b.get(i).copied().unwrap_or(0));
        let (diff, b2) = diff.overflowing_sub(borrow as u64);
        borrow = b1 || b2;
        *limb = diff;
    }
    trim(out)
}

pub fn mul(a: &[u64], b: &[u64]) -> Limbs {
    if a.is_empty() || b.is_empty() {
        return Limbs::new();
    }
    let mut product = Limbs::zeros(a.len() + b.len());
    let out: &mut [u64] = &mut product;
    for (i, &x) in a.iter().enumerate() {
        let mut carry = 0u128;
        for (j, &y) in b.iter().enumerate() {
            let t = x as u128 * y as u128 + out[i + j] as u128 + carry;
            out[i + j] = t as u64;
            carry = t >> 64;
        }
        out[i + b.len()] = carry as u64;
    }
    trim(product)
}

/// Quotient and remainder by one nonzero limb.
pub fn divrem_small(a: &[u64], b: u64) -> (Limbs, u64) {
    let mut digits = Limbs::zeros(a.len());
    let quotient: &mut [u64] = &mut digits;
    let mut remainder = 0u64;
    for i in (0..a.len()).rev() {
        if remainder == 0 {
            // No carry from above: a division of machine words.
            quotient[i] = a[i] / b;
            remainder = a[i] % b;
            continue;
        }
        let current = ((remainder as u128) << 64) | a[i] as u128;
        quotient[i] = (current / b as u128) as u64;
        remainder = (current % b as u128) as u64;
    }
    (trim(digits), remainder)
}

/// Quotient and remainder of the two-limb number `high`, `low` by `divisor`, for a divisor
/// with its top bit set and `high` below it, so that the quotient fits a limb. Two divisions
/// of machine words, where dividing a `u128` is a call into a general routine.
fn div_two_by_one(high: u64, low: u64, divisor: u64) -> (u64, u64) {
    const HALF: u64 = 1 << 32;
    let (d1, d0) = (divisor >> 32, divisor & (HALF - 1));
    let (l1, l0) = (low >> 32, low & (HALF - 1));
    // One half-limb digit of the quotient of `top`, `next` by the divisor.
    let digit = |top: u64, next: u64| {
        let mut q = top / d1;
        let mut r = top % d1;
        while q >= HALF || q * d0 > (r << 32 | next) {
            q -= 1;
            r += d1;
            if r >= HALF {
                break;
            }
        }
        q
    };
    let q1 = digit(high, l1);
    let middle = (high << 32 | l1).wrapping_sub(q1.wrapping_mul(divisor));
    let q0 = digit(middle, l0);
    let remainder = (middle << 32 | l0).wrapping_sub(q0.wrapping_mul(divisor));
    (q1 << 32 | q0, remainder)
}

/// Quotient and remainder, for nonzero `b`. Knuth's algorithm D.
pub fn divrem(a: &[u64], b: &[u64]) -> (Limbs, Limbs) {
    if compare(a, b) == Ordering::Less {
        return (Limbs::new(), Limbs::from(a));
    }
    if let [single] = b {
        let (quotient, remainder) = divrem_small(a, *single);
        return (quotient, if remainder == 0 { Limbs::new() } else { Limbs::from(&[remainder][..]) });
    }
    // Normalize so that the divisor's top bit is set; the quotient is unchanged.
    let shift = b[b.len() - 1].leading_zeros() as usize;
    let normalized = |x: &[u64], extra: usize| {
        let mut out = Limbs::zeros(x.len() + extra);
        let mut carry = 0u64;
        for (limb, &value) in out.iter_mut().zip(x) {
            *limb = if shift == 0 { value } else { (value << shift) | carry };
            carry = if shift == 0 { 0 } else { value >> (64 - shift) };
        }
        if extra != 0 {
            out[x.len()] = carry;
        }
        out
    };
    // `a` is not below `b`, so it has at least as many limbs, and one more for the shift.
    let divisor = normalized(b, 0);
    let mut dividend = normalized(a, 1);
    // Plain slices from here on: the loops below index them heavily.
    let (b, a): (&[u64], &mut [u64]) = (&divisor, &mut dividend);
    let n = b.len();
    let m = a.len() - n - 1;
    let mut digits = Limbs::zeros(m + 1);
    let quotient: &mut [u64] = &mut digits;
    for j in (0..=m).rev() {
        // Estimate the quotient digit from the top two limbs, then correct it.
        let (mut digit, mut rest) = if a[j + n] < b[n - 1] {
            let (digit, rest) = div_two_by_one(a[j + n], a[j + n - 1], b[n - 1]);
            (digit as u128, rest as u128)
        } else {
            // The estimate does not fit a limb; the correction below brings it down.
            let top = ((a[j + n] as u128) << 64) | a[j + n - 1] as u128;
            (top / b[n - 1] as u128, top % b[n - 1] as u128)
        };
        while digit >> 64 != 0 || digit * b[n - 2] as u128 > ((rest << 64) | a[j + n - 2] as u128) {
            digit -= 1;
            rest += b[n - 1] as u128;
            if rest >> 64 != 0 {
                break;
            }
        }
        // a[j..=j+n] -= digit * b
        let mut carry = 0u128;
        let mut borrow = false;
        for i in 0..n {
            let product = digit * b[i] as u128 + carry;
            carry = product >> 64;
            let (diff, b1) = a[i + j].overflowing_sub(product as u64);
            let (diff, b2) = diff.overflowing_sub(borrow as u64);
            a[i + j] = diff;
            borrow = b1 || b2;
        }
        let (diff, b1) = a[j + n].overflowing_sub(carry as u64);
        let (diff, b2) = diff.overflowing_sub(borrow as u64);
        a[j + n] = diff;
        if b1 || b2 {
            // The estimate was one too large: add the divisor back.
            digit -= 1;
            let mut carry = false;
            for i in 0..n {
                let (sum, c1) = a[i + j].overflowing_add(b[i]);
                let (sum, c2) = sum.overflowing_add(carry as u64);
                a[i + j] = sum;
                carry = c1 || c2;
            }
            a[j + n] = a[j + n].wrapping_add(carry as u64);
        }
        quotient[j] = digit as u64;
    }
    let remainder = shr(&a[..n], shift);
    (trim(digits), remainder)
}

pub fn shl(a: &[u64], bits: usize) -> Limbs {
    if a.is_empty() {
        return Limbs::new();
    }
    let (limbs, bits) = (bits / 64, bits % 64);
    let mut shifted = Limbs::zeros(limbs + a.len() + 1);
    let out = &mut shifted[limbs..];
    if bits == 0 {
        out[..a.len()].copy_from_slice(a);
    } else {
        let mut carry = 0u64;
        for (limb, &x) in out.iter_mut().zip(a) {
            *limb = (x << bits) | carry;
            carry = x >> (64 - bits);
        }
        out[a.len()] = carry;
    }
    trim(shifted)
}

pub fn shr(a: &[u64], bits: usize) -> Limbs {
    let (limbs, bits) = (bits / 64, bits % 64);
    if limbs >= a.len() {
        return Limbs::new();
    }
    let a = &a[limbs..];
    if bits == 0 {
        return trim(Limbs::from(a));
    }
    let mut out = Limbs::zeros(a.len());
    for (i, limb) in out.iter_mut().enumerate() {
        let high = a.get(i + 1).copied().unwrap_or(0);
        *limb = (a[i] >> bits) | (high << (64 - bits));
    }
    trim(out)
}

pub fn bitwise(a: &[u64], b: &[u64], op: fn(u64, u64) -> u64) -> Limbs {
    let len = a.len().max(b.len());
    trim((0..len).map(|i| op(a.get(i).copied().unwrap_or(0), b.get(i).copied().unwrap_or(0))).collect())
}

/// The number of bits in the binary representation; zero for zero.
pub fn bit_length(a: &[u64]) -> usize {
    match a.last() {
        Some(top) => a.len() * 64 - top.leading_zeros() as usize,
        None => 0,
    }
}

/// `n` for a number that is 2^n.
pub fn power_of_two(a: &[u64]) -> Option<usize> {
    let (top, rest) = a.split_last()?;
    (top.is_power_of_two() && rest.iter().all(|&limb| limb == 0)).then(|| rest.len() * 64 + top.trailing_zeros() as usize)
}

/// `a` modulo 2^bits, for an `a` that has more bits than that.
pub fn low_bits(a: &[u64], bits: usize) -> Limbs {
    let mut out = Limbs::from(&a[..bits.div_ceil(64)]);
    if bits % 64 != 0 {
        *out.last_mut().unwrap() &= (1 << (bits % 64)) - 1;
    }
    trim(out)
}

pub fn pow(base: &[u64], mut exponent: usize) -> Limbs {
    if base == [2] {
        return shl(&[1], exponent);
    }
    let mut result = Limbs::from(&[1u64][..]);
    let mut square = Limbs::from(base);
    while exponent != 0 {
        if exponent & 1 == 1 {
            result = mul(&result, &square);
        }
        exponent >>= 1;
        if exponent != 0 {
            square = mul(&square, &square);
        }
    }
    result
}

pub fn gcd(a: &[u64], b: &[u64]) -> Limbs {
    let (mut a, mut b) = (Limbs::from(a), Limbs::from(b));
    while !b.is_empty() {
        let (_, remainder) = divrem(&a, &b);
        a = b;
        b = remainder;
    }
    a
}

/// 10^19, the largest power of ten in one limb.
const CHUNK: u64 = 10_000_000_000_000_000_000;
const CHUNK_DIGITS: usize = 19;

pub fn to_decimal(a: &[u64]) -> String {
    if a.is_empty() {
        return "0".to_owned();
    }
    let mut chunks = Vec::new();
    let mut rest = Limbs::from(a);
    while !rest.is_empty() {
        let (quotient, remainder) = divrem_small(&rest, CHUNK);
        chunks.push(remainder);
        rest = quotient;
    }
    let mut out = chunks.pop().unwrap_or(0).to_string();
    for chunk in chunks.iter().rev() {
        out.push_str(&format!("{chunk:019}"));
    }
    out
}

/// Parses a nonempty string of decimal digits.
pub fn from_decimal(digits: &str) -> Option<Limbs> {
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let mut out: Limbs = Limbs::new();
    let bytes = digits.as_bytes();
    let mut start = 0;
    while start < bytes.len() {
        // The first chunk takes the odd digits so that every later chunk is full.
        let len = match (bytes.len() - start) % CHUNK_DIGITS {
            0 => CHUNK_DIGITS,
            partial => partial,
        };
        let chunk: u64 = digits[start..start + len].parse().ok()?;
        out = add(&mul(&out, &[10u64.pow(len as u32)]), &[chunk]);
        start += len;
    }
    Some(trim(out))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// SplitMix64, fixed seed.
    struct Rng(u64);

    impl Rng {
        fn next(&mut self) -> u64 {
            self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
            let mut z = self.0;
            z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
            z ^ (z >> 31)
        }

        /// `len` limbs with a nonzero top limb.
        fn number(&mut self, len: usize) -> Vec<u64> {
            let mut out: Vec<u64> = (0..len).map(|_| self.next()).collect();
            if let Some(top) = out.last_mut() {
                *top |= 1 << (self.next() % 64);
            }
            out
        }
    }

    /// Reference arithmetic on plain vectors, without `Limbs` or any shortcut.
    fn ref_trim(mut v: Vec<u64>) -> Vec<u64> {
        while v.last() == Some(&0) {
            v.pop();
        }
        v
    }

    fn ref_add(a: &[u64], b: &[u64]) -> Vec<u64> {
        let mut out = vec![0u64; a.len().max(b.len()) + 1];
        let mut carry = 0u128;
        for (i, slot) in out.iter_mut().enumerate() {
            let sum = a.get(i).copied().unwrap_or(0) as u128 + b.get(i).copied().unwrap_or(0) as u128 + carry;
            *slot = sum as u64;
            carry = sum >> 64;
        }
        ref_trim(out)
    }

    fn ref_mul(a: &[u64], b: &[u64]) -> Vec<u64> {
        let mut out = vec![0u64; a.len() + b.len() + 1];
        for (i, &x) in a.iter().enumerate() {
            let mut carry = 0u128;
            for j in 0..=b.len() {
                let y = b.get(j).copied().unwrap_or(0);
                let t = x as u128 * y as u128 + out[i + j] as u128 + carry;
                out[i + j] = t as u64;
                carry = t >> 64;
            }
            out[i + b.len() + 1] = carry as u64;
        }
        ref_trim(out)
    }

    /// `a` shifted left one bit at a time.
    fn ref_shl(a: &[u64], bits: usize) -> Vec<u64> {
        let mut out = a.to_vec();
        for _ in 0..bits {
            out = ref_add(&out, &out);
        }
        out
    }

    /// The number 2^k, built without `shl` or `pow`.
    fn ref_pow2(k: usize) -> Vec<u64> {
        let mut out = vec![0u64; k / 64 + 1];
        out[k / 64] = 1 << (k % 64);
        out
    }

    fn v(limbs: &Limbs) -> Vec<u64> {
        limbs.to_vec()
    }

    #[test]
    fn limbs_grow_and_shrink_across_the_inline_capacity() {
        let mut limbs = Limbs::new();
        let mut model: Vec<u64> = Vec::new();
        for i in 0..20u64 {
            limbs.push(i * 3 + 1);
            model.push(i * 3 + 1);
            assert_eq!(&*limbs, &model[..]);
        }
        while let Some(top) = model.pop() {
            assert_eq!(limbs.pop(), Some(top));
            assert_eq!(&*limbs, &model[..]);
        }
        assert_eq!(limbs.pop(), None);

        // Exactly the capacity stays inline; one more moves to the heap, keeping the contents.
        for len in [0, 1, INLINE - 1, INLINE, INLINE + 1, 2 * INLINE, 3 * INLINE + 5] {
            let source: Vec<u64> = (1..=len as u64).collect();
            let from = Limbs::from(&source[..]);
            assert_eq!(&*from, &source[..]);
            let collected: Limbs = source.iter().copied().collect();
            assert_eq!(&*collected, &source[..]);
            let zeros = Limbs::zeros(len);
            assert_eq!(&*zeros, &vec![0u64; len][..]);
        }
    }

    #[test]
    fn limbs_resize_truncate_and_extend() {
        for start in [0, 3, INLINE, INLINE + 2] {
            for target in [0, 1, INLINE - 1, INLINE, INLINE + 1, 17] {
                let mut limbs: Limbs = (1..=start as u64).collect();
                let mut model: Vec<u64> = (1..=start as u64).collect();
                limbs.resize(target, 7);
                model.resize(target, 7);
                assert_eq!(&*limbs, &model[..], "resize {start} -> {target}");
                limbs.extend_from_slice(&[9, 8, 7, 6, 5]);
                model.extend_from_slice(&[9, 8, 7, 6, 5]);
                assert_eq!(&*limbs, &model[..], "extend after resize {start} -> {target}");
                limbs.truncate(target / 2);
                model.truncate(target / 2);
                assert_eq!(&*limbs, &model[..], "truncate after resize {start} -> {target}");
                for slot in limbs.iter_mut() {
                    *slot ^= 1;
                }
                for slot in model.iter_mut() {
                    *slot ^= 1;
                }
                assert_eq!(&*limbs, &model[..]);
                limbs.push(42);
                model.push(42);
                assert_eq!(&*limbs, &model[..]);
            }
        }
        // Truncating past the length changes nothing.
        let mut limbs = Limbs::from(&[1u64, 2, 3][..]);
        limbs.truncate(10);
        assert_eq!(&*limbs, &[1, 2, 3]);
    }

    /// Results of 7, 8, 9 and 16 or more limbs, on both sides of the inline capacity.
    #[test]
    fn arithmetic_results_across_the_inline_capacity() {
        let mut rng = Rng(0x5eed);
        let lens = [0usize, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 16, 17, 24, 33];
        for &la in &lens {
            for &lb in &lens {
                let (a, b) = (rng.number(la), rng.number(lb));
                let sum = add(&a, &b);
                assert_eq!(v(&sum), ref_add(&a, &b), "add {la}+{lb}");
                let product = mul(&a, &b);
                assert_eq!(v(&product), ref_mul(&a, &b), "mul {la}*{lb}");
                if !b.is_empty() {
                    let (q, r) = divrem(&product, &b);
                    assert_eq!(v(&q), a, "div {la}*{lb}");
                    assert!(r.is_empty(), "rem {la}*{lb}");
                    // A remainder that is not zero, and a quotient that crosses the capacity.
                    let shifted = add(&product, &a.get(..1).map_or(vec![], |x| x.to_vec()));
                    let (q, r) = divrem(&shifted, &b);
                    let back = add(&mul(&q, &b), &r);
                    assert_eq!(v(&back), v(&shifted), "q*b+r {la} {lb}");
                    assert_eq!(compare(&r, &b), Ordering::Less, "r < b {la} {lb}");
                }
                if la >= lb && compare(&a, &b) != Ordering::Less {
                    let diff = sub(&a, &b);
                    assert_eq!(v(&add(&diff, &b)), a, "sub {la}-{lb}");
                }
            }
        }
        // All-ones operands: carries run through every limb and the result grows by one.
        for len in [6usize, 7, 8, 9, 15, 16, 17] {
            let ones = vec![u64::MAX; len];
            let sum = add(&ones, &[1]);
            assert_eq!(sum.len(), len + 1);
            assert_eq!(v(&sum), ref_pow2(64 * len));
            assert_eq!(v(&mul(&ones, &ones)), ref_mul(&ones, &ones));
            assert_eq!(v(&sub(&sum, &[1])), ones);
        }
    }

    #[test]
    fn shifts_across_the_inline_capacity() {
        let mut rng = Rng(7);
        for len in [1usize, 2, 7, 8, 9, 16] {
            let a = rng.number(len);
            for bits in [0usize, 1, 63, 64, 65, 127, 128, 200, 448, 511, 512, 513, 1000] {
                let left = shl(&a, bits);
                assert_eq!(v(&left), ref_shl(&a, bits), "shl {len} limbs by {bits}");
                assert_eq!(v(&shr(&left, bits)), a, "shr back {len} limbs by {bits}");
                let (q, _) = divrem(&a, &ref_pow2(bits));
                assert_eq!(v(&shr(&a, bits)), v(&q), "shr {len} limbs by {bits} against division");
            }
        }
        assert!(shl(&[], 1000).is_empty());
        assert!(shr(&[1, 2, 3], 192).is_empty());
    }

    #[test]
    fn power_of_two_recognises_exactly_the_powers() {
        for k in [0usize, 1, 62, 63, 64, 65, 127, 128, 255, 256, 511, 512, 1000] {
            assert_eq!(power_of_two(&ref_pow2(k)), Some(k));
            assert_eq!(power_of_two(&ref_add(&ref_pow2(k), &[1])), if k == 0 { Some(1) } else { None });
            if k > 0 {
                let below = sub(&ref_pow2(k), &[1]);
                assert_eq!(power_of_two(&below), if k == 1 { Some(0) } else { None }, "2^{k} - 1");
            }
        }
        assert_eq!(power_of_two(&[]), None);
        assert_eq!(power_of_two(&[3]), None);
        assert_eq!(power_of_two(&[1, 1]), None);
        assert_eq!(power_of_two(&[0, 6]), None);
    }

    /// `low_bits` and `shr` agree with Knuth division by the same power of two.
    #[test]
    fn low_bits_and_shr_agree_with_division() {
        let mut rng = Rng(99);
        for len in [1usize, 2, 4, 7, 8, 9, 16, 17] {
            let a = rng.number(len);
            for k in [1usize, 5, 63, 64, 65, 100, 128, 191, 192, 255, 256, 448, 511, 512, 1023] {
                if bit_length(&a) <= k {
                    continue;
                }
                let divisor = ref_pow2(k);
                let (q, r) = divrem(&a, &divisor);
                assert_eq!(v(&low_bits(&a, k)), v(&r), "{len} limbs mod 2^{k}");
                assert_eq!(v(&shr(&a, k)), v(&q), "{len} limbs div 2^{k}");
            }
        }
        // Low bits that are all zero trim to nothing.
        assert!(low_bits(&[0, 0, 5], 128).is_empty());
        assert_eq!(v(&low_bits(&[u64::MAX, u64::MAX], 65)), vec![u64::MAX, 1]);
    }

    #[test]
    fn pow_of_two_agrees_with_repeated_multiplication() {
        for exponent in [0usize, 1, 2, 63, 64, 65, 127, 128, 256, 511, 512, 513, 1100] {
            let mut expected = vec![1u64];
            for _ in 0..exponent {
                expected = ref_mul(&expected, &[2]);
            }
            assert_eq!(v(&pow(&[2], exponent)), expected, "2^{exponent}");
        }
        // Other bases take the general path; 4^n is 2^(2n).
        for exponent in [0usize, 1, 31, 32, 100, 300] {
            assert_eq!(v(&pow(&[4], exponent)), ref_pow2(2 * exponent), "4^{exponent}");
        }
        let three = pow(&[3], 200);
        let mut expected = vec![1u64];
        for _ in 0..200 {
            expected = ref_mul(&expected, &[3]);
        }
        assert_eq!(v(&three), expected);
    }

    /// Quotient and remainder by shifting and subtracting one bit at a time.
    fn ref_divrem(a: &[u64], b: &[u64]) -> (Vec<u64>, Vec<u64>) {
        let b = ref_trim(b.to_vec());
        assert!(!b.is_empty());
        let bits = a.len() * 64;
        let mut quotient = vec![0u64; a.len()];
        let mut rest: Vec<u64> = Vec::new();
        for i in (0..bits).rev() {
            // rest = 2 * rest + bit i of a
            rest = ref_add(&rest, &rest);
            if a[i / 64] >> (i % 64) & 1 == 1 {
                rest = ref_add(&rest, &[1]);
            }
            if compare(&rest, &b) != Ordering::Less {
                rest = ref_sub(&rest, &b);
                quotient[i / 64] |= 1 << (i % 64);
            }
        }
        (ref_trim(quotient), rest)
    }

    fn ref_sub(a: &[u64], b: &[u64]) -> Vec<u64> {
        let mut out = vec![0u64; a.len()];
        let mut borrow = 0i128;
        for (i, slot) in out.iter_mut().enumerate() {
            let d = a[i] as i128 - b.get(i).copied().unwrap_or(0) as i128 - borrow;
            borrow = (d < 0) as i128;
            *slot = d.rem_euclid(1 << 64) as u64;
        }
        assert_eq!(borrow, 0, "ref_sub of a larger number");
        ref_trim(out)
    }

    /// `divrem` against the reference and against its defining equation.
    fn check_divrem(a: &[u64], b: &[u64], what: &str) {
        let (q, r) = divrem(a, b);
        let (rq, rr) = ref_divrem(a, b);
        assert_eq!(v(&q), rq, "quotient: {what}");
        assert_eq!(v(&r), rr, "remainder: {what}");
        assert_eq!(compare(&r, b), Ordering::Less, "remainder below divisor: {what}");
        assert_eq!(v(&add(&mul(&q, b), &r)), ref_trim(a.to_vec()), "q * b + r: {what}");
    }

    /// Divisors with the top bit set and `high` below them, the preconditions, against `u128`.
    #[test]
    fn div_two_by_one_agrees_with_u128_division() {
        let check = |high: u64, low: u64, divisor: u64| {
            assert!(divisor >> 63 == 1 && high < divisor);
            let n = (high as u128) << 64 | low as u128;
            let expected = ((n / divisor as u128) as u64, (n % divisor as u128) as u64);
            assert_eq!(div_two_by_one(high, low, divisor), expected, "{high:#x}:{low:#x} / {divisor:#x}");
        };
        // Divisors whose halves are at their extremes, and the largest and smallest `high`.
        let divisors = [
            1u64 << 63,
            (1 << 63) | 1,
            (1 << 63) | 0xffff_ffff,
            (1 << 63) | (1 << 32),
            0x8000_0001_0000_0000,
            0xffff_ffff_0000_0000,
            0xffff_ffff_0000_0001,
            0xffff_fffe_ffff_ffff,
            u64::MAX - 1,
            u64::MAX,
            0x8000_0000_ffff_ffff,
            0xc000_0000_0000_0000,
        ];
        let lows = [0u64, 1, 0xffff_ffff, 1 << 32, (1 << 63) - 1, 1 << 63, u64::MAX - 1, u64::MAX];
        for &d in &divisors {
            let highs = [0u64, 1, 0xffff_ffff, 1 << 32, d >> 1, d >> 32, (d >> 32) << 32, d - 2, d - 1];
            for &high in &highs {
                if high < d {
                    for &low in &lows {
                        check(high, low, d);
                    }
                }
            }
        }
        let mut rng = Rng(0xd1);
        for i in 0..200_000 {
            let d = rng.next() | 1 << 63;
            let d = match i % 5 {
                0 => d & !0xffff_ffff,
                1 => d | 0xffff_ffff,
                _ => d,
            };
            let high = match i % 7 {
                0 => d - 1,
                1 => d - 1 - (rng.next() % 1000).min(d - 1),
                2 => rng.next() % (1 << 32),
                _ => rng.next() % d,
            };
            let low = match i % 3 {
                0 => u64::MAX,
                _ => rng.next(),
            };
            check(high, low, d);
        }
    }

    /// Division by one limb: the word division when nothing carries, and the two-word one.
    #[test]
    fn divrem_small_agrees_with_the_reference() {
        let mut rng = Rng(31);
        let divisors = [1u64, 2, 3, 7, 10, 1 << 32, (1 << 32) + 1, (1 << 63) - 1, 1 << 63, u64::MAX - 1, u64::MAX];
        for len in [1usize, 2, 3, 7, 8, 9, 17] {
            for &d in &divisors {
                let shapes = [rng.number(len), vec![u64::MAX; len], { let mut x = vec![0u64; len]; x[len - 1] = 1; x }, {
                    // Limbs below the divisor, so that every step carries.
                    (0..len).map(|_| rng.next() % d).collect::<Vec<u64>>()
                }];
                for a in shapes {
                    let (q, r) = divrem_small(&a, d);
                    let (rq, rr) = ref_divrem(&a, &[d]);
                    assert_eq!(v(&q), rq, "{a:?} / {d}");
                    assert_eq!(ref_trim(vec![r]), rr, "{a:?} % {d}");
                }
            }
        }
    }

    /// Knuth's division on random operands of every length, with and without normalization.
    #[test]
    fn divrem_agrees_with_the_reference() {
        let mut rng = Rng(0x0dd);
        for la in [1usize, 2, 3, 4, 5, 8, 9, 12] {
            for lb in 1..=la {
                for i in 0..12 {
                    let a = rng.number(la);
                    let mut b = rng.number(lb);
                    match i % 4 {
                        // The divisor normalized already, or with one bit set in its top limb.
                        0 => *b.last_mut().unwrap() |= 1 << 63,
                        1 => *b.last_mut().unwrap() = 1,
                        _ => {}
                    }
                    check_divrem(&a, &b, &format!("{la} by {lb} limbs, case {i}"));
                }
            }
        }
    }

    /// Steps whose top remainder limb equals the divisor's top limb, so that the first
    /// estimate of the digit is 2^64 or more and comes down in the correction.
    #[test]
    fn divrem_with_an_estimate_that_does_not_fit_a_limb() {
        let mut rng = Rng(0xe57);
        for n in [2usize, 3, 4, 8, 9] {
            for i in 0..60 {
                let mut b = rng.number(n);
                if i % 2 == 0 {
                    *b.last_mut().unwrap() |= 1 << 63;
                }
                // A remainder just below the divisor: the same top limbs, smaller low ones.
                let delta = match i % 3 {
                    0 => vec![1u64],
                    1 => vec![rng.next() % 1000 + 1],
                    _ => vec![rng.next(), rng.next() % 4],
                };
                if compare(&b, &delta) != Ordering::Greater {
                    continue;
                }
                let below = ref_sub(&b, &delta);
                // Dividends of the remainder followed by one or two random limbs.
                for extra in 1..=2usize {
                    let mut a: Vec<u64> = (0..extra).map(|_| rng.next()).collect();
                    a.extend_from_slice(&below);
                    check_divrem(&a, &b, &format!("{n} limbs, delta {delta:?}, {extra} extra"));
                }
                // The normalized case built directly: top limbs equal and the rest smaller.
                if b[n - 1] >> 63 == 1 && b[n - 2] > 0 {
                    let mut a = vec![rng.next()];
                    a.extend_from_slice(&b[..n - 1]);
                    a[n - 1] = b[n - 2] - 1;
                    a.push(b[n - 1]);
                    check_divrem(&a, &b, &format!("{n} limbs, equal tops"));
                }
            }
        }
    }

    /// Digits whose estimate passes the two-limb test but is still one too large, so that
    /// the divisor is added back: `u = q * b - 1` for a divisor whose lowest limb is all ones.
    #[test]
    fn divrem_adds_back() {
        let mut rng = Rng(0xadd);
        for i in 0..400 {
            let n = 3 + i % 4;
            let mut b = rng.number(n);
            b[0] = u64::MAX;
            *b.last_mut().unwrap() |= 1 << 63;
            if i % 5 == 0 {
                b[n - 2] = 0;
            }
            let qhat = match i % 4 {
                0 => 2 + rng.next() % 1000,
                1 => rng.next() | 1 << 63,
                2 => u64::MAX,
                _ => rng.next().max(2),
            };
            let product = ref_mul(&b, &[qhat]);
            let u = ref_sub(&product, &[1]);
            // The estimate of the digit from the top limbs passes the test with the second
            // limb of the divisor: `qhat` times the top two divisor limbs is at most the top
            // limbs of `u`.
            let top_u = ref_trim(u[1..].to_vec());
            assert_ne!(compare(&ref_mul(&b[1..], &[qhat]), &top_u), Ordering::Greater);
            let (q, r) = divrem(&u, &b);
            assert_eq!(v(&q), ref_trim(vec![qhat - 1]), "q, case {i}");
            assert_eq!(v(&r), ref_sub(&b, &[1]), "r, case {i}");
            check_divrem(&u, &b, &format!("add back, case {i}"));
            // The same with a quotient of several digits, each over the add-back case.
            let mut wide = vec![rng.next(); 2];
            wide.extend_from_slice(&u);
            check_divrem(&wide, &b, &format!("add back below, case {i}"));
        }
    }

    /// Carries and borrows that stop early and that run through every limb.
    #[test]
    fn add_and_sub_carry_and_borrow_runs() {
        for len in [1usize, 2, 7, 8, 9, 16, 17] {
            for k in 0..len {
                // Ones below limb `k`: adding one carries exactly to it.
                let mut a = vec![u64::MAX; k];
                a.extend(std::iter::repeat_n(5u64, len - k));
                assert_eq!(v(&add(&a, &[1])), ref_add(&a, &[1]), "carry to {k} of {len}");
                assert_eq!(v(&add(&[1], &a)), ref_add(&a, &[1]), "carry to {k} of {len}, swapped");
                // Zeros below limb `k`: subtracting one borrows exactly from it.
                let mut b = vec![0u64; k];
                b.extend(std::iter::repeat_n(5u64, len - k));
                assert_eq!(v(&sub(&b, &[1])), ref_sub(&b, &[1]), "borrow from {k} of {len}");
                assert_eq!(v(&sub(&b, &b)), Vec::<u64>::new());
                let short: Vec<u64> = b[..=k].to_vec();
                assert_eq!(v(&sub(&b, &short)), ref_sub(&b, &short));
            }
        }
        // Results that lose their top limbs are trimmed.
        assert_eq!(v(&sub(&[0, 0, 1], &[1, u64::MAX, 0])), vec![u64::MAX]);
        assert_eq!(v(&sub(&[5, 7], &[5, 7])), Vec::<u64>::new());
    }

    /// A number made of zeros inline and on the heap, after other values used the storage.
    #[test]
    fn zeros_are_zero() {
        for len in [0usize, 1, INLINE - 1, INLINE, INLINE + 1, 40] {
            let z = Limbs::zeros(len);
            assert_eq!(z.len(), len);
            assert!(z.iter().all(|&x| x == 0));
        }
        let mut rng = Rng(3);
        for _ in 0..100 {
            let (la, lb) = (1 + (rng.next() % 12) as usize, 1 + (rng.next() % 12) as usize);
            let (a, b) = (rng.number(la), rng.number(lb));
            let _ = mul(&a, &b);
            let z = Limbs::zeros(INLINE);
            assert!(z.iter().all(|&x| x == 0));
        }
    }
}