bigdecimal 0.4.10

Arbitrary precision decimal numbers
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
//! Radix definitions
//!
//! Empty structs used to make generic algorithms over kind of radix
//!
#![allow(dead_code)]
#![allow(non_camel_case_types)]

use crate::*;
use crate::stdlib::fmt;

use num_traits::{WrappingAdd, WrappingSub, AsPrimitive};


/// All the information needed to specify a bigdecimal's radix, and methods operating on integers
pub trait RadixType: Copy + Clone + Default + fmt::Debug {
    /// the inner type of values
    type Base
        : 'static
        + Copy
        + fmt::Debug
        + num_integer::Integer
        + num_traits::PrimInt
        + num_traits::FromPrimitive
        + num_traits::AsPrimitive<Self::BaseDouble>
        + num_traits::Zero
        + num_traits::One
        + num_traits::WrappingSub
        + num_traits::Pow<u8, Output = Self::Base>
        + AddAssign
        + From<bool>
        + From<u8>;

    /// double wide unsigned type (capable of storing product of two BigDigits)
    type BaseDouble
        : 'static
        + Copy
        + num_integer::Integer
        + num_traits::PrimInt
        + num_traits::FromPrimitive
        + num_traits::AsPrimitive<Self::Base>
        + num_traits::Zero
        + num_traits::One
        + num_traits::WrappingAdd
        + num_traits::WrappingSub
        + AddAssign
        + From<u8>
        + From<Self::Base>;

    /// signed version of base (used for diffs)
    type SignedBase
        : 'static
        + Copy
        + num_integer::Integer
        + num_traits::PrimInt
        + num_traits::FromPrimitive
        + num_traits::Zero
        + num_traits::One
        + num_traits::Signed;

    /// Value of the RADIX
    const RADIX: Self::BaseDouble;

    /// Check contents of iterable contains values less than the radix
    fn validate_digits<'a, I: IntoIterator<Item = &'a Self::Base>>(i: I) -> bool {
        i.into_iter().map(|&d| d.into()).all(|d| Self::BaseDouble::zero() <= d && d < Self::RADIX)
    }

    /// True if n is the maximum value for this radix (RADIX - 1)
    fn max() -> Self::Base {
        (Self::RADIX - One::one()).as_()
    }

    /// True if n is the maximum value for this radix (RADIX - 1)
    fn is_max(n: Self::Base) -> bool {
        n == Self::max()
    }

    /// Split single-width BigDigit base-type value into valid BigDigits for
    /// this Radix
    fn split_single(n: Self::Base) -> (Self::Base, Self::Base) {
        let (hi, lo) = num_integer::div_rem(n.as_(), Self::RADIX);
        return (hi.as_(), lo.as_());
    }

    /// Split double-wide value into valid BigDigit and overflow for this Radix
    fn split_doublewide(n: Self::BaseDouble) -> (Self::BaseDouble, Self::Base) {
        let (hi, lo) = num_integer::div_rem(n, Self::RADIX);
        return (hi, lo.as_());
    }

    /// Split double-wide bigdigit into high and low bigdigits.
    ///
    /// This assumes n will fit in two bigdigits, which is not guaranteed.
    /// Use split_doublewide.
    ///
    fn split_wide_digit(n: Self::BaseDouble) -> (Self::Base, Self::Base) {
        let (hi, lo) = num_integer::div_rem(n, Self::RADIX);
        debug_assert!(hi < Self::RADIX);
        return (hi.as_(), lo.as_());
    }

    /// Perform n + carry, returning sum and storing overflow back in carry
    fn add_carry(n: Self::Base, carry: &mut Self::Base) -> Self::Base {
        let (hi, lo) = Self::expanding_add(n, *carry);
        *carry = hi;
        lo
    }

    /// Perform n += carry, returning overflow in carry
    fn addassign_carry(n: &mut Self::Base, carry: &mut Self::Base) {
        let (hi, lo) = Self::expanding_add(*n, *carry);
        *carry = hi;
        *n = lo;
    }

    /// Perform n += a + carry, returning overflow in carry
    fn addassign_with_carry(n: &mut Self::Base, a: Self::Base, carry: &mut Self::Base) {
        let sum = n.as_() + a.as_() + carry.as_();
        let (hi, lo) = Self::split_wide_digit(sum);
        *carry = hi;
        *n = lo;
    }

    /// Perform a + b, returning tuple of (high, low) digits
    fn add_expand_doublewide(a: Self::Base, b: Self::BaseDouble) -> (Self::Base, Self::Base) {
        let a: Self::BaseDouble = a.into();
        Self::split_wide_digit(a + b)
    }

    /// Perform a + b, returning tuple of (high, low) digits
    fn expanding_add(a: Self::Base, b: Self::Base) -> (Self::Base, Self::Base) {
        let a: Self::BaseDouble = a.into();
        let b: Self::BaseDouble = b.into();
        Self::split_wide_digit(a + b)
    }

    /// Perform a * b, returning tuple of (high, low) digits
    fn expanding_mul(a: Self::Base, b: Self::Base) -> (Self::Base, Self::Base) {
        let a: Self::BaseDouble = a.into();
        let b: Self::BaseDouble = b.into();
        Self::split_wide_digit(a * b)
    }

    /// Perform a * b + c, returning tuple of (high, low) digits
    fn fused_mul_add(a: Self::Base, b: Self::Base, c: Self::Base) -> (Self::Base, Self::Base) {
        let a: Self::BaseDouble = a.into();
        let b: Self::BaseDouble = b.into();
        let c: Self::BaseDouble = c.into();
        Self::split_wide_digit(a * b + c)
    }

    /// Perform a * b + c + d, returning tuple of (high, low) digits
    fn carrying_mul_add(
        a: Self::Base,
        b: Self::Base,
        c: Self::Base,
        d: Self::Base,
    ) -> (Self::Base, Self::Base) {
        let a: Self::BaseDouble = a.into();
        let b: Self::BaseDouble = b.into();
        let c: Self::BaseDouble = c.into();
        let d: Self::BaseDouble = d.into();
        Self::split_wide_digit(a * b + c + d)
    }

    /// Perform c += a * b + carry, returning overflow in carry
    fn carrying_mul_add_inplace(
        a: Self::Base,
        b: Self::Base,
        c: &mut Self::Base,
        carry: &mut Self::Base,
    ) {
        let a: Self::BaseDouble = a.into();
        let b: Self::BaseDouble = b.into();
        let (hi, lo) = Self::split_wide_digit(a * b + (*c).into() + (*carry).into());
        *c = lo;
        *carry = hi;
    }

    /// Add c into little-endian slice of digits, storing overflow in c
    ///
    /// Starts adding at index 0.
    ///
    fn add_carry_into_slice(dest: &mut [Self::Base], c: &mut Self::Base) {
        Self::add_carry_into(dest.iter_mut(), c)
    }

    /// Iterate over digits in 'dest', adding the carry value until it becomes zero.
    ///
    /// If iterator runs out of digits while carry has a value (i.e. the sum overflows),
    /// the carry value will not be zero.
    ///
    fn add_carry_into<'a, I: Iterator<Item=&'a mut Self::Base>>(dest: I, c: &mut Self::Base) {
        for d in dest {
            if c.is_zero() {
                return;
            }

            let (overflow, sum) = Self::expanding_add(*c, *d);
            *d = sum;
            *c = overflow;
        }
    }

    /// a = a * b + c, storing
    fn mulassign_add_carry(
        a: &mut Self::Base,
        b: Self::Base,
        carry: &mut Self::Base,
    ) {
        let (hi, lo) = Self::expanding_mul(*a, b);
        *a = Self::add_carry(lo, carry);
        *carry += hi;
    }

    /// return value of (lhs - rhs + carry - borrow)
    fn sub_with_carry_borrow(
        lhs: Self::Base,
        rhs: Self::Base,
        carry: &mut Self::Base,
        borrow: &mut Self::Base,
    ) -> Self::Base {
        let mut result = Self::BaseDouble::from(lhs);
        result = result
                    .wrapping_sub(&Self::BaseDouble::from(rhs))
                    .wrapping_add(&(*carry).as_())
                    .wrapping_sub(&(*borrow).as_());

        *borrow = Self::Base::from(result >= (Self::RADIX << 1));
        result = result.wrapping_add(&(borrow.as_() * Self::RADIX));
        debug_assert!(result < (Self::RADIX << 1));

        *carry = Self::Base::from(result >= Self::RADIX);
        result = result - carry.as_() * Self::RADIX;

        return result.as_();
    }
}

/// Radix=*10* / storage=*u8*
#[derive(Copy, Clone, Debug, Default)]
pub struct RADIX_10_u8;

/// Radix=*10,000* storage=*i16*
#[derive(Copy, Clone, Debug, Default)]
pub struct RADIX_10p4_i16;

/// Radix=*1,000,000,000* storage=*u32*
#[derive(Copy, Clone, Debug, Default)]
pub struct RADIX_10p9_u32;

/// Radix=*10,000,000,000,000,000,000* storage=*u64*
#[derive(Copy, Clone, Debug, Default)]
pub struct RADIX_10p19_u64;

/// Radix = 2^<sup>32</sup>
#[derive(Copy, Clone, Debug, Default)]
pub struct RADIX_u32;

/// Radix = 2^<sup>64</sup>
#[derive(Copy, Clone, Debug, Default)]
pub struct RADIX_u64;


pub(crate) trait RadixPowerOfTen: RadixType {
    const DIGITS: usize;

    /// convert number of digits to number of big-digits
    fn divceil_digit_count(digit_count: usize) -> usize {
        use num_integer::Integer;
        Integer::div_ceil(&digit_count, &Self::DIGITS)
    }

    /// convert number of digits to number of big-digits
    fn divmod_digit_count(digit_count: usize) -> (usize, usize) {
        use num_integer::Integer;
        Integer::div_rem(&digit_count, &Self::DIGITS)
    }
}

impl RadixPowerOfTen for RADIX_10p19_u64 {
    const DIGITS: usize = 19;
}
impl RadixPowerOfTen for RADIX_10p9_u32 {
    const DIGITS: usize = 9;
}
impl RadixPowerOfTen for RADIX_10_u8 {
    const DIGITS: usize = 1;
}
impl RadixPowerOfTen for RADIX_10p4_i16 {
    const DIGITS: usize = 4;
}

impl RADIX_10p19_u64 {
    /// Divide double-wide u64 by radix, storing the quotient in the low u64,
    /// and returning the remainder
    pub(crate) fn rotating_div_u64_radix(hi: u64, lo: &mut u64) -> <Self as RadixType>::Base {
        use num_integer::div_rem;
        type BaseDouble = <RADIX_10p19_u64 as RadixType>::BaseDouble;

        let num = BaseDouble::from(*lo) + (BaseDouble::from(hi) << 64);
        let (q, r) = div_rem(num, Self::RADIX);
        *lo = q.as_();
        r.as_()
    }
}

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

    macro_rules! impl_case {
        (valid $name:ident : $radix:ident ~ $values:expr) => {
            #[test]
            fn $name() {
                assert!($radix::validate_digits($values.iter()));
            }
        };
        (invalid $name:ident : $radix:ident ~ $values:expr) => {
            #[test]
            fn $name() {
                assert!(!$radix::validate_digits($values.iter()));
            }
        };
    }

    impl_case!(valid case_valid: RADIX_10p4_i16 ~ [1, 2, 3, 4, 5, 600]);
    impl_case!(invalid case_invalid_too_big: RADIX_10p4_i16 ~ [10000, 1, 2, 3, 4, 5, 600]);
    impl_case!(invalid case_invalid_negative: RADIX_10p4_i16 ~ [1, 2, -3, 4, 5, 600]);
    impl_case!(invalid case_invalid_leading_zeros: RADIX_10p4_i16 ~ [0, 1, 2, -3, 4, 5, 600]);
    impl_case!(invalid case_p9_toobig: RADIX_10p9_u32 ~ [3330199352]);
}

impl RadixType for RADIX_u32 {
    type Base = u32;
    type BaseDouble = u64;
    type SignedBase = i32;

    const RADIX: Self::BaseDouble = 1u64 << 32;

    // all u32 are valid in this radix
    fn validate_digits<'a, I: IntoIterator<Item = &'a Self::Base>>(_: I) -> bool {
        true
    }

    fn expanding_add(a: u32, b: u32) -> (u32, u32) {
        let (sum, overflow) = a.overflowing_add(b);
        (u32::from(overflow), sum)
    }
}

impl RadixType for RADIX_u64 {
    type Base = u64;
    type BaseDouble = u128;
    type SignedBase = i64;

    const RADIX: Self::BaseDouble = 1u128 << 64;

    // all u64 are valid in this radix
    fn validate_digits<'a, I: IntoIterator<Item = &'a Self::Base>>(_: I) -> bool {
        true
    }

    fn expanding_add(a: u64, b: u64) -> (u64, u64) {
        let (sum, overflow) = a.overflowing_add(b);
        (u64::from(overflow), sum)
    }
}

impl RadixType for RADIX_10p4_i16 {
    type Base = i16;
    type BaseDouble = i32;
    type SignedBase = i64;

    const RADIX: Self::BaseDouble = 10_000;
}

impl RadixType for RADIX_10p9_u32 {
    type Base = u32;
    type BaseDouble = u64;
    type SignedBase = i32;

    const RADIX: Self::BaseDouble = 1_000_000_000;
}

impl RadixType for RADIX_10p19_u64 {
    type Base = u64;
    type BaseDouble = u128;
    type SignedBase = i64;

    const RADIX: Self::BaseDouble = 10_000_000_000_000_000_000;
}

impl RadixType for RADIX_10_u8 {
    type Base = u8;
    type BaseDouble = u8;
    type SignedBase = i8;

    const RADIX: Self::BaseDouble = 10;
}

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

    include!("radix.tests.rs");
}