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
// Copyright 2015 The Ramp Developers
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.

use std;
use std::cmp::{Ordering, PartialEq, PartialOrd};
use std::fmt;
use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Neg, Not, Rem, Shl, Shr, Sub};

use std::intrinsics::assume;

use ::std::num::Wrapping;
#[allow(dead_code)]
type Word = Wrapping<usize>;

macro_rules! if_cfg {
    ($(#[cfg($cfg:meta)] $it:item)+ fallback: $els:item) => (
        $(#[cfg($cfg)] $it)+
        #[cfg(not(any($($cfg),*)))] $els
    )
}

#[cfg(target_pointer_width = "32")]
pub type BaseInt = u32;
#[cfg(target_pointer_width = "64")]
pub type BaseInt = u64;

/**
 * Helper newtype for operations.
 *
 * A "Limb" is a single digit in base 2^word size.
 */
#[derive(Copy, Eq, Ord, Hash)]
pub struct Limb(pub BaseInt);

impl Clone for Limb {
    #[inline(always)]
    fn clone(&self) -> Limb {
        *self
    }
}

impl Limb {
    #[cfg(target_pointer_width = "32")]
    pub const BITS: usize = 32;
    #[cfg(target_pointer_width = "64")]
    pub const BITS: usize = 64;

    pub const B: Limb = Limb(1 << (Limb::BITS / 2));

    /// Returns the high half of the limb
    #[inline(always)]
    pub fn high_part(self) -> Limb {
        self >> (Limb::BITS / 2)
    }

    #[inline(always)]
    /// Returns the low half of the limb
    pub fn low_part(self) -> Limb {
        self & (Limb::B - 1)
    }

    /**
     * Performs `self + other`, returning the result and whether or not the addition overflowed
     */
    #[inline(always)]
    pub fn add_overflow(self, other: Limb) -> (Limb, bool) {
        let (val, c) = std::intrinsics::add_with_overflow(self.0, other.0);
        (Limb(val), c)
    }

    /**
     * Performs `self - other`, returning the result and whether or not the subtraction overflowed
     */
    #[inline(always)]
    pub fn sub_overflow(self, other: Limb) -> (Limb, bool) {
        let (val, c) = std::intrinsics::sub_with_overflow(self.0, other.0);
        (Limb(val), c)
    }

    /**
     * Performs `self * other` returning the lower half of the product
     */
    #[inline(always)]
    pub fn mul_lo(self, other: Limb) -> Limb {
        Limb(self.0.wrapping_mul(other.0))
    }

    /**
     * Performs `self * other` returning the higher half of the product
     */
    #[inline(always)]
    pub fn mul_hi(self, other: Limb) -> Limb {
        mul(self, other).0
    }

    /**
     * Performs `self * other` returning the two-limb result as (high, low).
     */
    #[inline(always)]
    pub fn mul_hilo(self, other: Limb) -> (Limb, Limb) {
        mul(self, other)
    }

    #[inline(always)]
    pub fn invert(self) -> Limb {
        debug_assert!(self.0 != 0);
        div(!self, Limb(!0), self).0
    }

    /**
     * Returns whether or not the highest bit in the limb is set.
     *
     * Division algorithms often require the highest limb of the divisor
     * to be `d >= BASE/2`.
     */
    #[inline(always)]
    pub fn high_bit_set(self) -> bool {
        (self & Limb(1 << (Limb::BITS - 1))) != 0
    }

    /**
     * Returns the number of leading zeros in the limb
     */
    #[inline(always)]
    pub fn leading_zeros(self) -> BaseInt {
        self.0.leading_zeros() as BaseInt
    }

    /**
     * Returns the number of trailing zeros in the limb
     */
    #[inline(always)]
    pub fn trailing_zeros(self) -> BaseInt {
        self.0.trailing_zeros() as BaseInt
    }
}

impl Add<Limb> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn add(self, other: Limb) -> Limb {
        Limb(self.0.wrapping_add(other.0))
    }
}

impl Add<BaseInt> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn add(self, other: BaseInt) -> Limb {
        Limb(self.0.wrapping_add(other))
    }
}

impl Add<bool> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn add(self, other: bool) -> Limb {
        Limb(self.0.wrapping_add(other as BaseInt))
    }
}

impl Add<Limb> for BaseInt {
    type Output = Limb;

    #[inline(always)]
    fn add(self, other: Limb) -> Limb {
        Limb(self.wrapping_add(other.0))
    }
}

impl Sub<Limb> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn sub(self, other: Limb) -> Limb {
        Limb(self.0.wrapping_sub(other.0))
    }
}

impl Sub<BaseInt> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn sub(self, other: BaseInt) -> Limb {
        Limb(self.0.wrapping_sub(other))
    }
}

impl Sub<bool> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn sub(self, other: bool) -> Limb {
        Limb(self.0.wrapping_sub(other as BaseInt))
    }
}

impl Sub<Limb> for BaseInt {
    type Output = Limb;

    #[inline(always)]
    fn sub(self, other: Limb) -> Limb {
        Limb(self.wrapping_sub(other.0))
    }
}

impl Mul<Limb> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn mul(self, other: Limb) -> Limb {
        self.mul_lo(other)
    }
}

impl Mul<BaseInt> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn mul(self, other: BaseInt) -> Limb {
        Limb(self.0.wrapping_mul(other))
    }
}

impl Mul<Limb> for BaseInt {
    type Output = Limb;

    #[inline(always)]
    fn mul(self, other: Limb) -> Limb {
        Limb(self.wrapping_mul(other.0))
    }
}

impl Div<Limb> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn div(self, other: Limb) -> Limb {
        debug_assert!(other.0 != 0);
        unsafe {
            assume(other.0 != 0);
        }
        Limb(self.0 / other.0)
    }
}

impl Div<BaseInt> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn div(self, other: BaseInt) -> Limb {
        debug_assert!(other != 0);
        unsafe {
            assume(other != 0);
        }
        Limb(self.0 / other)
    }
}

impl Rem<Limb> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn rem(self, other: Limb) -> Limb {
        debug_assert!(other.0 != 0);
        unsafe {
            assume(other.0 != 0);
        }
        Limb(self.0 % other.0)
    }
}

impl Rem<BaseInt> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn rem(self, other: BaseInt) -> Limb {
        debug_assert!(other != 0);
        unsafe {
            assume(other != 0);
        }
        Limb(self.0 % other)
    }
}

impl Neg for Limb {
    type Output = Limb;

    #[inline(always)]
    fn neg(self) -> Limb {
        Limb(0) - self
    }
}

impl<I> Shl<I> for Limb
where
    BaseInt: Shl<I, Output = BaseInt>,
{
    type Output = Limb;

    #[inline(always)]
    fn shl(self, other: I) -> Limb {
        Limb(self.0 << other)
    }
}

impl<I> Shr<I> for Limb
where
    BaseInt: Shr<I, Output = BaseInt>,
{
    type Output = Limb;

    #[inline(always)]
    fn shr(self, other: I) -> Limb {
        Limb(self.0 >> other)
    }
}

impl Not for Limb {
    type Output = Limb;

    #[inline(always)]
    fn not(self) -> Limb {
        Limb(!self.0)
    }
}

impl BitAnd<Limb> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn bitand(self, other: Limb) -> Limb {
        Limb(self.0 & other.0)
    }
}

impl BitOr<Limb> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn bitor(self, other: Limb) -> Limb {
        Limb(self.0 | other.0)
    }
}

impl BitXor<Limb> for Limb {
    type Output = Limb;

    #[inline(always)]
    fn bitxor(self, other: Limb) -> Limb {
        Limb(self.0 ^ other.0)
    }
}

impl PartialEq<Limb> for Limb {
    #[inline(always)]
    fn eq(&self, other: &Limb) -> bool {
        self.0 == other.0
    }

    #[inline(always)]
    fn ne(&self, other: &Limb) -> bool {
        self.0 != other.0
    }
}

impl PartialOrd<Limb> for Limb {
    #[inline(always)]
    fn partial_cmp(&self, other: &Limb) -> Option<Ordering> {
        self.0.partial_cmp(&other.0)
    }

    #[inline(always)]
    fn lt(&self, other: &Limb) -> bool {
        self.0 < other.0
    }

    #[inline(always)]
    fn le(&self, other: &Limb) -> bool {
        self.0 <= other.0
    }

    #[inline(always)]
    fn gt(&self, other: &Limb) -> bool {
        self.0 > other.0
    }

    #[inline(always)]
    fn ge(&self, other: &Limb) -> bool {
        self.0 >= other.0
    }
}

impl PartialEq<BaseInt> for Limb {
    #[inline(always)]
    fn eq(&self, other: &BaseInt) -> bool {
        self.0 == *other
    }

    #[inline(always)]
    fn ne(&self, other: &BaseInt) -> bool {
        self.0 != *other
    }
}

impl PartialOrd<BaseInt> for Limb {
    #[inline(always)]
    fn partial_cmp(&self, other: &BaseInt) -> Option<Ordering> {
        self.0.partial_cmp(other)
    }

    #[inline(always)]
    fn lt(&self, other: &BaseInt) -> bool {
        self.0 < *other
    }

    #[inline(always)]
    fn le(&self, other: &BaseInt) -> bool {
        self.0 <= *other
    }

    #[inline(always)]
    fn gt(&self, other: &BaseInt) -> bool {
        self.0 > *other
    }

    #[inline(always)]
    fn ge(&self, other: &BaseInt) -> bool {
        self.0 >= *other
    }
}

impl fmt::Debug for Limb {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

impl fmt::Display for Limb {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

pub fn mul(u: Limb, v: Limb) -> (Limb, Limb) {
    if_cfg! {
        #[cfg(all(not(feature="fallbacks"),target_arch="x86_64"))]
        #[inline(always)]
        fn mul_impl(u: Limb, v: Limb) -> (Limb, Limb) {
            let mut high: Limb = Limb(0);
            let mut low: Limb  = Limb(0);
            unsafe {
                asm!(
                    "mul {v}", // multiply u by v and store in high:low
                    v = in(reg) v.0,
                    inout("rax") u.0 => low.0,
                    out("rdx") high.0
                );
            }

            (high, low)
        }

        #[cfg(all(not(feature="fallbacks"),target_arch="x86"))]
        #[inline(always)]
        fn mul_impl(u: Limb, v: Limb) -> (Limb, Limb) {
            let mut high: Limb = Limb(0);
            let mut low: Limb  = Limb(0);
            unsafe {
                asm!(
                    "mul {v}", // multiply u by v and store in high:low
                    v = in(reg) v.0,
                    inout("eax") u.0 => low.0,
                    out("edx") high.0
                );
            }

            (high, low)
        }

        #[cfg(all(  not(feature="fallbacks"),
                    not(target_arch="x86"),
                    target_pointer_width="32",
            ))]
        #[inline(always)]
        fn mul_impl(u: Limb, v: Limb) -> (Limb, Limb) {
            let u = u.0 as u64;
            let v = v.0 as u64;
            let p = u*v;
            (Limb((p>>32) as u32), Limb(p as u32))
        }

        fallback:
        #[inline(always)]
        fn mul_impl(u: Limb, v: Limb) -> (Limb, Limb) {
            fn mul_2_usize_to_2_usize(u:Word, v: Word) -> (Word,Word) {
                // see http://www.hackersdelight.org/hdcodetxt/muldwu.c.txt
                const BITS:usize = Limb::BITS / 2;
                const LO_MASK:Word = Wrapping((1usize << BITS) - 1);

                let u0 = u >> BITS;
                let u1 = u & LO_MASK;
                let v0 = v >> BITS;
                let v1 = v & LO_MASK;

                let t = u1 * v1;
                let w3 = t & LO_MASK;
                let k = t >> BITS;

                let t = u0*v1 + k;
                let w2 = t & LO_MASK;
                let w1 = t >> BITS;

                let t = u1 * v0 + w2;
                let k = t >> BITS;

                (u0*v0+w1+k, (t<<BITS) + w3)
            }

            let (h,l) = mul_2_usize_to_2_usize(
                Wrapping(u.0 as usize),
                Wrapping(v.0 as usize));

            (Limb(h.0 as BaseInt), Limb(l.0 as BaseInt))

        }
    }
    return mul_impl(u, v);
}

/**
 * Performs the two-word addition (ah, al) + (bh, bl), ignoring any overflow.
 */
#[inline(always)]
pub fn add_2(ah: Limb, al: Limb, bh: Limb, bl: Limb) -> (Limb, Limb) {
    if_cfg! {
        #[cfg(all(not(feature="fallbacks"), any(target_arch="x86_64", target_arch="x86")))]
        #[inline(always)]
        fn add_2_impl(ah: Limb, al: Limb, bh: Limb, bl: Limb) -> (Limb, Limb) {
            let mut high: Limb = Limb(0);
            let mut low: Limb  = Limb(0);
            unsafe {
                asm!(
                    "add {0}, {bl}", // adds bl to al and stores in low
                    "adc {1}, {bh}", // adds bh to ah with carry and stores in high
                    inout(reg) al.0 => low.0,
                    inout(reg) ah.0 => high.0,
                    bl = in(reg) bl.0,
                    bh = in(reg) bh.0,
                );
            }

            (high, low)
        }

        #[cfg(all(  not(feature="fallbacks"),
                    not(target_arch="x86"),
                    target_pointer_width="32",
            ))]
        #[inline(always)]
        fn add_2_impl(ah: Limb, al: Limb, bh: Limb, bl: Limb) -> (Limb, Limb) {
            let a = ((ah.0 as u64) << 32) | al.0 as u64;
            let b = ((bh.0 as u64) << 32) | bl.0 as u64;
            let s = a.overflowing_add(b).0;
            (Limb((s>>32) as u32), Limb(s as u32))
        }

        fallback:
        #[inline(always)]
        fn add_2_impl(ah: Limb, al: Limb, bh: Limb, bl: Limb) -> (Limb, Limb) {
            let (low, carry) = al.add_overflow(bl);
            let high = ah + bh + carry;

            (high, low)
        }
    }
    return add_2_impl(ah, al, bh, bl);
}

/**
 * Performs the two-word subtraction (ah, al) - (bh, bl), ignoring any borrow.
 */
#[inline(always)]
pub fn sub_2(ah: Limb, al: Limb, bh: Limb, bl: Limb) -> (Limb, Limb) {
    if_cfg! {
        #[cfg(all(not(feature="fallbacks"), any(target_arch="x86_64", target_arch="x86")))]
        #[inline(always)]
        fn sub_2_impl(ah: Limb, al: Limb, bh: Limb, bl: Limb) -> (Limb, Limb) {
            let mut high: Limb = Limb(0);
            let mut low: Limb  = Limb(0);
            unsafe {
                asm!(
                    "sub {0}, {bl}", // subtracts bl from al and stores in low
                    "sbb {1}, {bh}", // subtracts bh from ah with carry and stores in high
                    inout(reg) al.0 => low.0,
                    inout(reg) ah.0 => high.0,
                    bl = in(reg) bl.0,
                    bh = in(reg) bh.0
                );
            }

            (high, low)
        }

        #[cfg(all(  not(feature="fallbacks"),
                    not(target_arch="x86"),
                    target_pointer_width="32",
            ))]
        #[inline(always)]
        fn sub_2_impl(ah: Limb, al: Limb, bh: Limb, bl: Limb) -> (Limb, Limb) {
            let a = ((ah.0 as u64) << 32) | al.0 as u64;
            let b = ((bh.0 as u64) << 32) | bl.0 as u64;
            let s = a.overflowing_sub(b).0;
            (Limb((s>>32) as u32), Limb(s as u32))
        }

        fallback:
        #[inline(always)]
        fn sub_2_impl(ah: Limb, al: Limb, bh: Limb, bl: Limb) -> (Limb, Limb) {
            let (low, carry) = al.sub_overflow(bl);
            let high = ah - bh - carry;

            (high, low)
        }
    }
    return sub_2_impl(ah, al, bh, bl);
}

/**
 * Divides the two-limb numerator `(nh, nl)` by `d`, returning a single-limb
 * quotient, Q, and remainder, R, as (Q, R).
 *
 * In order to ensure a single-limb result, the following conditions are required:
 *
 * - `nh` < `d`
 * - `d` >= BASE/2
 */
#[inline(always)]
pub fn div(nh: Limb, nl: Limb, d: Limb) -> (Limb, Limb) {
    if_cfg! {
        #[cfg(all(not(feature="fallbacks"),target_arch="x86_64"))]
        #[inline(always)]
        fn div_impl(nh: Limb, nl: Limb, d: Limb) -> (Limb, Limb) {
            let mut q: Limb = Limb(0);
            let mut r: Limb = Limb(0);
            unsafe {
                asm!(
                    "div {d}", // divide nh:nl by d and store the quotient in q and remainder in r
                    d = in(reg) d.0,
                    inout("rax") nl.0 => q.0,
                    inout("rdx") nh.0 => r.0
                );
            }
            (q, r)
        }

        #[cfg(all(not(feature="fallbacks"),target_arch="x86"))]
        #[inline(always)]
        fn div_impl(nh: Limb, nl: Limb, d: Limb) -> (Limb, Limb) {
            let mut q: Limb = Limb(0);
            let mut r: Limb = Limb(0);
            unsafe {
                asm!(
                    "div {d}", // divide nh:nl by d and store the quotient in q and remainder in r
                    d = in(reg) d.0,
                    inout("eax") nl.0 => q.0,
                    inout("edx") nh.0 => r.0
                );
            }
            (q, r)
        }

        #[cfg(all(  not(feature="fallbacks"),
                    not(target_arch="x86"),
                    target_pointer_width="32",
            ))]
        #[inline(always)]
        fn div_impl(nh: Limb, nl: Limb, d: Limb) -> (Limb, Limb) {
            let n = (nh.0 as u64) << 32 | nl.0 as u64;
            let d = d.0 as u64;
            (Limb((n/d) as u32), Limb((n%d) as u32))
        }

        fallback:
        #[inline(always)]
        fn div_impl(nh: Limb, nl: Limb, d: Limb) -> (Limb, Limb) {
            fn div_2_usize_by_usize(u1:Word, u0: Word, v: Word) -> (Word,Word) {
                // See http://www.hackersdelight.org/hdcodetxt/divlu.c.txt (last one)
                // s == 0 in our case, d normalization is already done
                const BITS:usize = Limb::BITS / 2;
                const ONE:Word = Wrapping(1usize);
                const B:Word = Wrapping(1usize << BITS);
                const LO_MASK:Word = Wrapping((1usize << BITS) - 1);

                let vn1 = v >> BITS;
                let vn0 = v & LO_MASK;

                let un32 = u1;
                let un10 = u0;

                let un1 = un10 >> BITS;
                let un0 = un10 & LO_MASK;

                let mut q1 = un32 / vn1;
                let mut rhat = un32 - q1*vn1;

                while q1 >= B || q1*vn0 > B*rhat + un1 {
                    q1 -= ONE;
                    rhat += vn1;
                    if rhat >= B {
                        break;
                    }
                }

                let un21 = un32*B +un1 - q1*v;

                let mut q0 = un21 / vn1;
                let mut rhat = un21 - q0*vn1;
                while q0 >= B || q0*vn0 > B*rhat + un0 {
                    q0 -= ONE;
                    rhat += vn1;
                    if rhat >= B {
                        break;
                    }
                }
                (q1*B + q0, un21*B + un0 - q0*v)
            }

            let (q,r) = div_2_usize_by_usize(
                Wrapping(nh.0 as usize),
                Wrapping(nl.0 as usize),
                Wrapping(d.0 as usize));

            (Limb(q.0 as BaseInt), Limb(r.0 as BaseInt))
        }
    }

    debug_assert!(d.high_bit_set());
    debug_assert!(nh < d);
    unsafe {
        assume(nh < d);
        assume(d.high_bit_set());
    }

    return div_impl(nh, nl, d);
}

/**
 * Divides `(nh, nl)` by `d` using the inverted limb `dinv`. Returns the quotient, Q, and
 * remainder, R, as (Q, R);
 */
#[inline(always)]
pub fn div_preinv(nh: Limb, nl: Limb, d: Limb, dinv: Limb) -> (Limb, Limb) {
    let (qh, ql) = dinv.mul_hilo(nh);
    let (mut qh, ql) = add_2(qh, ql, nh + 1, nl);

    let mut r = nl - qh * d;
    if r > ql {
        qh = qh - 1;
        r = r + d;
    }
    if r >= d {
        qh = qh + 1;
        r = r - d;
    }

    (qh, r)
}

#[test]
fn test_bug_div_1() {
    let (q, r) = div(
        Limb(0),
        Limb(10),
        Limb((usize::max_value() / 2 + 1) as BaseInt),
    );
    assert_eq!((q.0, r.0), (0, 10));
}

#[cfg(target_pointer_width = "64")]
#[test]
fn test_bug_mul_1() {
    let (h, l) = mul(Limb(18446744073709551615), Limb(7868907223611932671));
    assert_eq!((h.0, l.0), (7868907223611932670, 10577836850097618945));
}

#[test]
fn test_add_2() {
    let (h, l) = add_2(Limb(4), Limb(2), Limb(3), Limb(1));
    assert_eq!((h.0, l.0), (7, 3));
}

#[test]
fn test_sub_2() {
    let (h, l) = sub_2(Limb(4), Limb(2), Limb(3), Limb(1));
    assert_eq!((h.0, l.0), (1, 1));
}

#[test]
fn test_div() {
    let (q, r) = div(
        Limb(2),
        Limb(0),
        Limb((usize::max_value() / 2 + 1) as BaseInt),
    );
    assert_eq!((q.0, r.0), (4, 0));
}