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
//! This module implements a double width integer type based on the largest built-in integer (u128)

use core::ops::{Add, Rem, Shl, Shr, ShlAssign, ShrAssign, AddAssign, Sub, SubAssign, Mul, Div};
use num_traits::Zero;

/// Alias of the builtin integer type with max width
#[allow(non_camel_case_types)]
pub type umax = u128;

#[allow(non_camel_case_types)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
/// A double width integer type based on the largest built-in integer (u128)
/// 
/// It's used to support double-width operations on u128. Although it can be considered as u256,
/// it's not as feature-rich as other crates since it's only designed to support this crate.
pub struct udouble {
    pub hi: umax,
    pub lo: umax
}

impl udouble {
    pub fn widening_add(lhs: umax, rhs: umax) -> Self {
        let (sum, carry) = lhs.overflowing_add(rhs);
        udouble { hi: carry as umax, lo: sum }
    }

    /// Calculate multiplication of two [umax] integers with result represented in double width integer
    // equivalent to umul_ppmm, can be implemented efficiently with carrying_mul and widening_mul implemented (rust#85532)
    pub fn widening_mul(lhs: umax, rhs: umax) -> Self {
        const HALF_BITS: u32 = umax::BITS >> 1;
        let halves = |x| (x >> HALF_BITS, x & !(0 as umax) >> HALF_BITS);
        let ((x1, x0), (y1, y0)) = (halves(lhs), halves(rhs));
        let (z2, z0) = (x1 * y1, x0 * y0);
        // it's possible to use Karatsuba multiplication, but overflow checking is much easier here
        let (z1, c1) = (x1 * y0).overflowing_add(x0 * y1);
        let (lo, c0) = umax::overflowing_add(z0, z1 << HALF_BITS);
        Self { hi: z2 + (z1 >> HALF_BITS) + c0 as umax + ((c1 as umax) << HALF_BITS), lo }
    }

    pub fn overflowing_add(&self, rhs: Self) -> (Self, bool) {
        let (lo, carry) = self.lo.overflowing_add(rhs.lo);
        let (hi, of1) = self.hi.overflowing_add(rhs.hi);
        let (hi, of2) = hi.overflowing_add(carry as umax);
        (Self { lo, hi }, of1 || of2)
    }

    pub fn overflowing_mul(&self, rhs: Self) -> (Self, bool) {
        let c2 = self.hi != 0 && rhs.hi != 0;
        let Self {lo: z0, hi: c0} = Self::widening_mul(self.lo, rhs.lo);
        let (z1x, c1x) = u128::overflowing_mul(self.lo, rhs.hi);
        let (z1y, c1y) = u128::overflowing_mul(self.hi, rhs.lo);
        let (z1z, c1z) = u128::overflowing_add(z1x, z1y);
        let (z1, cs1) = z1z.overflowing_add(c0);
        let (z1, cs2) = z1.overflowing_add(c1z as umax);
        (Self { hi: z1, lo: z0 }, c1x | c1y | cs1 | cs2 | c2)
    }
}

impl From<umax> for udouble {
    fn from(v: umax) -> Self {
        Self { lo: v, hi: 0 }
    }
}

impl Add for udouble {
    type Output = udouble;

    // equivalent to add_ssaaaa
    fn add(self, rhs: Self) -> Self::Output {
        let (lo, carry) = self.lo.overflowing_add(rhs.lo);
        let hi = self.hi + rhs.hi + carry as umax;
        Self { lo, hi }
    }
}

impl Add<umax> for udouble {
    type Output = udouble;
    fn add(self, rhs: umax) -> Self::Output {
        let (lo, carry) = self.lo.overflowing_add(rhs);
        let hi = if carry { self.hi + 1 } else { self.hi };
        Self { lo, hi }
    }
}

impl AddAssign for udouble {
    fn add_assign(&mut self, rhs: Self) {
        let (lo, carry) = self.lo.overflowing_add(rhs.lo);
        self.lo = lo;
        self.hi += rhs.hi + carry as umax;
    }
}

impl AddAssign<umax> for udouble {
    fn add_assign(&mut self, rhs: umax) {
        let (lo, carry) = self.lo.overflowing_add(rhs);
        self.lo = lo;
        if carry { self.hi += 1 }
    }
}

impl Sub for udouble {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        let carry = self.lo < rhs.lo;
        let lo = self.lo.wrapping_sub(rhs.lo);
        let hi = self.hi - rhs.hi - carry as umax;
        Self { lo, hi }
    }
}

impl SubAssign for udouble {
    fn sub_assign(&mut self, rhs: Self) {
        let carry = self.lo < rhs.lo;
        self.lo = self.lo.wrapping_sub(rhs.lo);
        self.hi -= rhs.hi + carry as umax;
    }
}

impl Zero for udouble {
    fn zero() -> Self {
        Self { lo: 0, hi: 0}
    }

    fn is_zero(&self) -> bool {
        self.lo == 0 && self.hi == 0
    }
}

impl Shl<u32> for udouble {
    type Output = Self;
    fn shl(self, rhs: u32) -> Self::Output {
        match rhs {
            0 => self,
            s if s >= umax::BITS => Self {
                hi: self.lo << (s - umax::BITS),
                lo: 0,
            },
            s => Self {
                lo: self.lo << s,
                hi: (self.hi << s) | (self.lo >> (umax::BITS - s)),
            }
        }
    }
}

impl ShlAssign<u32> for udouble {
    fn shl_assign(&mut self, rhs: u32) {
        match rhs {
            0 => {},
            s if s >= umax::BITS => {
                self.hi = self.lo << (s - umax::BITS);
                self.lo = 0;
            },
            s => {
                self.hi <<= s;
                self.hi |= self.lo >> (umax::BITS - s);
                self.lo <<= s;
            }
        }
    }
}

impl Shr<u32> for udouble {
    type Output = Self;
    fn shr(self, rhs: u32) -> Self::Output {
        match rhs {
            0 => self,
            s if s >= umax::BITS => Self {
                lo: self.hi >> (rhs - umax::BITS),
                hi: 0,
            },
            s => Self {
                hi: self.hi >> s,
                lo: (self.lo >> s) | (self.hi << (umax::BITS - s)),
            }
        }
    }
}

impl ShrAssign<u32> for udouble {
    fn shr_assign(&mut self, rhs: u32) {
        match rhs {
            0 => {},
            s if s >= umax::BITS => {
                self.lo = self.hi >> (rhs - umax::BITS);
                self.hi = 0;
            },
            s => {
                self.lo >>= s;
                self.lo |= self.hi << (umax::BITS - s);
                self.hi >>= s;
            }
        }
    }
}

impl udouble {
    pub fn leading_zeros(self) -> u32 {
        if self.hi == 0 {
            self.lo.leading_zeros() + umax::BITS
        } else {
            self.hi.leading_zeros()
        }
    }

    // similar to udiv_qrnnd
    pub fn div_rem(self, other: Self) -> (Self, Self) {
        let mut n = self; // numerator
        let mut d = other; // denominator
        let mut q = Self::zero(); // quotient

        let nbits = 2 * umax::BITS - n.leading_zeros();
        let dbits = 2 * umax::BITS - d.leading_zeros();
        assert!(dbits != 0, "division by zero");

        // Early return in case we are dividing by a larger number than us
        if nbits < dbits {
            return (q, n);
        }

        // Bitwise long division
        let mut shift = nbits - dbits;
        d <<= shift;
        loop {
            if n >= d {
                q += 1;
                n -= d;
            }
            if shift == 0 { break; }

            d >>= 1;
            q <<= 1;
            shift -= 1;
        }
        (q, n)
    }
}

impl Mul for udouble {
    type Output = Self;
    fn mul(self, rhs: Self) -> Self::Output {
        let (m, overflow) = self.overflowing_mul(rhs);
        assert!(!overflow, "multiplication overflow!");
        m
    }
}

impl Div for udouble {
    type Output = Self;
    fn div(self, rhs: Self) -> Self::Output {
        self.div_rem(rhs).0
    }
}

impl Rem for udouble {
    type Output = Self;
    fn rem(self, rhs: Self) -> Self::Output {
        self.div_rem(rhs).1
    }
}

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

    #[test]
    fn test_construction() {
        // construct zero
        assert!(udouble { lo: 0, hi: 0 }.is_zero());

        // from widening operators
        assert_eq!(udouble { hi: 0, lo: 2 }, udouble::widening_add(1, 1));
        assert_eq!(udouble { hi: 1, lo: umax::MAX - 1 }, udouble::widening_add(umax::MAX, umax::MAX));

        assert_eq!(udouble { hi: 0, lo: 1 }, udouble::widening_mul(1, 1));
        assert_eq!(udouble { hi: 1 << 32, lo: 0 }, udouble::widening_mul(1 << 80, 1 << 80));
        assert_eq!(udouble { hi: 1 << 32, lo: 2 << 120 | 1 << 80 }, udouble::widening_mul(1 << 80 | 1 << 40, 1 << 80 | 1 << 40));
        assert_eq!(udouble { hi: umax::MAX - 1, lo: 1 }, udouble::widening_mul(umax::MAX, umax::MAX));
    }

    #[test]
    fn test_ops() {
        const ONE: udouble = udouble { hi: 0, lo: 1 };
        const TWO: udouble = udouble { hi: 0, lo: 2 };
        const MAX: udouble = udouble { hi: 0, lo: umax::MAX };
        const ONEZERO: udouble = udouble { hi: 1, lo: 0 };
        const ONEMAX: udouble = udouble { hi: 1, lo: umax::MAX };
        const TWOZERO: udouble = udouble { hi: 2, lo: 0 };

        assert_eq!(ONE + MAX, ONEZERO);
        assert_eq!(ONE + ONEMAX, TWOZERO);
        assert_eq!(ONEZERO - ONE, MAX);
        assert_eq!(ONEZERO - MAX, ONE);
        assert_eq!(TWOZERO - ONE, ONEMAX);
        assert_eq!(TWOZERO - ONEMAX, ONE);

        assert_eq!(ONE << umax::BITS, ONEZERO);
        assert_eq!((MAX << 1) + 1, ONEMAX);
        assert_eq!(ONEZERO >> umax::BITS, ONE);
        assert_eq!(ONEMAX >> 1, MAX);

        assert_eq!(ONE * MAX, MAX);
        assert_eq!(ONE * ONEMAX, ONEMAX);
        assert_eq!(TWO * ONEMAX, ONEMAX + ONEMAX);
        assert_eq!(MAX / ONE, MAX);
        assert_eq!(MAX / MAX, ONE);
        assert_eq!(ONE / MAX, udouble::zero());
        assert_eq!(ONEMAX / ONE, ONEMAX);
        assert_eq!(ONEMAX / ONEMAX, ONE);
        assert_eq!(ONEMAX / MAX, TWO);
        assert_eq!(ONEMAX / TWO, MAX);
        assert_eq!(ONE % MAX, ONE);
        assert_eq!(TWO % MAX, TWO);
        assert_eq!(ONEMAX % MAX, ONE);
        assert_eq!(ONEMAX % TWO, ONE);

        let (m, overflow) = ONEMAX.overflowing_mul(MAX);
        assert_eq!(m, udouble { lo: 1, hi: umax::MAX - 2});
        assert!(overflow);
    }

    #[test]
    fn test_assign_ops() {
        for _ in 0..10 {
            let x = udouble { hi: random::<u32>() as umax, lo: random() };
            let y = udouble { hi: random::<u32>() as umax, lo: random() };
            let mut z = x;

            z += y; assert_eq!(z, x + y);
            z -= y; assert_eq!(z, x);
        }
    }
}