reckoner 0.3.0

A high level arbitrary precision arithmetic library supporting integer and rational 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
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
use crate::{error::Error, integer::Integer};
use core::{
    convert::TryInto,
    iter::{Product, Sum},
    ptr,
};
use std::os::raw::c_long;

mod addition;
mod addition_assign;
mod division;
mod division_assign;
mod multiplication;
mod multiplication_assign;
mod negation;
mod remainder;
mod remainder_assign;
mod subtraction;
mod subtraction_assign;

impl Integer {
    /// Add two integers and return the result
    pub fn add(&self, other: &Self) -> Self {
        let self_raw = self.as_raw();
        let other_raw = other.as_raw();

        let result_int = Integer::new();
        let result_raw = result_int.as_raw();

        // This operation is safe bc `self`, `other`, and `result` have all been
        // initialized. `result` does not necessarily need to be initialized.
        let op_res = unsafe { creachadair_imath_sys::mp_int_add(self_raw, other_raw, result_raw) };

        imath_check_panic!(op_res, "Operation failed!");

        result_int
    }

    /// Add two integers and assign the result to self
    pub fn add_assign(&mut self, other: &Self) {
        let self_raw = self.as_raw();
        let other_raw = other.as_raw();

        // This operation is safe because `self` and `other` have been initialized and
        // the result pointer is allowed to alias with either of the arguments.
        let op_res = unsafe { creachadair_imath_sys::mp_int_add(self_raw, other_raw, self_raw) };

        imath_check_panic!(op_res, "Operation failed!");
    }

    pub(crate) fn add_c_long(&self, value: impl Into<c_long>) -> Self {
        let self_raw = self.as_raw();
        let result_int = Integer::new();
        let result_raw = result_int.as_raw();

        // This operation is safe because `self` and `result` have been initialized.
        let op_res =
            unsafe { creachadair_imath_sys::mp_int_add_value(self_raw, value.into(), result_raw) };

        imath_check_panic!(op_res, "Operation failed!");

        result_int
    }

    pub(crate) fn add_c_long_assign(&mut self, other: impl Into<c_long>) {
        let self_raw = self.as_raw();

        // This operation is safe because `self` has been initialized and the result
        // pointer is allowed to alias with the integer argument.
        let op_res =
            unsafe { creachadair_imath_sys::mp_int_add_value(self_raw, other.into(), self_raw) };

        imath_check_panic!(op_res, "Operation failed!");
    }

    /// Subtract two integers and return the result
    pub fn subtract(&self, other: &Self) -> Self {
        let self_raw = self.as_raw();
        let other_raw = other.as_raw();

        let result_int = Integer::new();
        let result_raw = result_int.as_raw();

        // This operation is safe bc `self`, `other`, and `result` have all been
        // initialized. `result` does not necessarily need to be initialized.
        let op_res = unsafe { creachadair_imath_sys::mp_int_sub(self_raw, other_raw, result_raw) };

        imath_check_panic!(op_res, "Operation failed!");

        result_int
    }

    /// Subtract two integers and assign the result to self
    pub fn subtract_assign(&mut self, other: &Self) {
        let self_raw = self.as_raw();
        let other_raw = other.as_raw();

        let op_res = unsafe { creachadair_imath_sys::mp_int_sub(self_raw, other_raw, self_raw) };

        imath_check_panic!(op_res, "Operation failed!");
    }

    pub(crate) fn subtract_c_long(&self, value: impl Into<c_long>) -> Self {
        let self_raw = self.as_raw();
        let result_int = Integer::new();
        let result_raw = result_int.as_raw();

        let op_res =
            unsafe { creachadair_imath_sys::mp_int_sub_value(self_raw, value.into(), result_raw) };

        imath_check_panic!(op_res, "Operation failed!");

        result_int
    }

    pub(crate) fn subtract_c_long_assign(&mut self, other: impl Into<c_long>) {
        let self_raw = self.as_raw();

        let op_res =
            unsafe { creachadair_imath_sys::mp_int_sub_value(self_raw, other.into(), self_raw) };

        imath_check_panic!(op_res, "Operation failed!");
    }

    /// Multiply two integers and return the result
    pub fn multiply(&self, other: &Self) -> Self {
        let self_raw = self.as_raw();
        let other_raw = other.as_raw();

        let result_int = Integer::new();
        let result_raw = result_int.as_raw();

        // This operation is safe bc `self`, `other`, and `result` have all been
        // initialized. `result` does not necessarily need to be initialized.
        let op_res = unsafe { creachadair_imath_sys::mp_int_mul(self_raw, other_raw, result_raw) };

        imath_check_panic!(op_res, "Operation failed!");

        result_int
    }

    /// Multiply two integers and assign the result to self
    pub fn multiply_assign(&mut self, other: &Self) {
        let self_raw = self.as_raw();
        let other_raw = other.as_raw();

        let op_res = unsafe { creachadair_imath_sys::mp_int_mul(self_raw, other_raw, self_raw) };

        imath_check_panic!(op_res, "Operation failed!");
    }

    pub(crate) fn multiply_c_long(&self, value: impl Into<c_long>) -> Self {
        let self_raw = self.as_raw();
        let result_int = Integer::new();
        let result_raw = result_int.as_raw();

        let op_res =
            unsafe { creachadair_imath_sys::mp_int_mul_value(self_raw, value.into(), result_raw) };

        imath_check_panic!(op_res, "Operation failed!");

        result_int
    }

    pub(crate) fn multiply_c_long_assign(&mut self, other: impl Into<c_long>) {
        let self_raw = self.as_raw();

        let op_res =
            unsafe { creachadair_imath_sys::mp_int_mul_value(self_raw, other.into(), self_raw) };

        imath_check_panic!(op_res, "Operation failed!");
    }

    /// Return the additive inverse
    pub fn negate(&self) -> Self {
        let self_raw = self.as_raw();
        let result_int = Integer::new();
        let result_raw = result_int.as_raw();

        // This operation is safe bc `self`and `result` have all been initialized.
        // `result` does not necessarily need to be initialized.
        let op_res = unsafe { creachadair_imath_sys::mp_int_neg(self_raw, result_raw) };

        imath_check_panic!(op_res, "Operation failed!");

        result_int
    }

    /// Assign the additive inverse to self
    pub fn negate_assign(&mut self) {
        let self_raw = self.as_raw();

        let op_res = unsafe { creachadair_imath_sys::mp_int_neg(self_raw, self_raw) };

        imath_check_panic!(op_res, "Operation failed!");
    }

    /// Return the absolute value
    pub fn absolute_value(&self) -> Self {
        let self_raw = self.as_raw();
        let result_int = Integer::new();
        let result_raw = result_int.as_raw();

        // This operation is safe bc `self`and `result` have all been initialized.
        // `result` does not necessarily need to be initialized.
        let op_res = unsafe { creachadair_imath_sys::mp_int_abs(self_raw, result_raw) };

        imath_check_panic!(op_res, "Operation failed!");

        result_int
    }

    /// Assign the absolute value to self
    pub fn absolute_value_assign(&mut self) {
        let self_raw = self.as_raw();

        let op_res = unsafe { creachadair_imath_sys::mp_int_abs(self_raw, self_raw) };

        imath_check_panic!(op_res, "Operation failed!");
    }

    /// Perform integer division operation.
    ///
    /// # Safety
    ///
    /// `dividend` and `divisor` are allowed to alias for this operation, so
    /// they may point to the same `Integer`. Either `out_quotient` or
    /// `out_remainder` may be `null`, but not both. These also may alias with
    /// either of the input arguments, `dividend` or `divisor`.
    fn mp_int_div(
        dividend: &Integer,
        divisor: &Integer,
        out_quotient: creachadair_imath_sys::mp_int,
        out_remainder: creachadair_imath_sys::mp_int,
    ) {
        assert!(!(out_quotient.is_null() && out_remainder.is_null()));

        let dividend_raw = dividend.as_raw();
        let divisor_raw = divisor.as_raw();

        // This operation is safe bc `dividend`, `divisor` have all been initialized.
        // Also, runtime checks of `out_quotient` and `out_remainder` ensure that a
        // result can be written somewhere.
        let op_res = unsafe {
            creachadair_imath_sys::mp_int_div(
                dividend_raw,
                divisor_raw,
                out_quotient,
                out_remainder,
            )
        };

        imath_check_panic!(op_res, "Operation failed!");
    }

    /// Divide two integers and return quotient and remainder
    pub fn divide_full(&self, rhs: &Self) -> (Self, Self) {
        let quotient = Integer::new();
        let quotient_raw = quotient.as_raw();
        let remainder = Integer::new();
        let remainder_raw = remainder.as_raw();

        Integer::mp_int_div(self, rhs, quotient_raw, remainder_raw);

        (quotient, remainder)
    }

    /// Divide two integers and return only quotient
    pub fn divide(&self, rhs: &Self) -> Self {
        let quotient = Integer::new();
        let quotient_raw = quotient.as_raw();

        Integer::mp_int_div(self, rhs, quotient_raw, ptr::null_mut());

        quotient
    }

    /// Divide two integers and assign the result to self
    pub fn divide_assign(&mut self, rhs: &Self) {
        let quotient_raw = self.as_raw();

        Integer::mp_int_div(self, rhs, quotient_raw, ptr::null_mut());
    }

    /// Divide two integers and return only remainder
    pub fn remainder(&self, rhs: &Self) -> Self {
        let remainder = Integer::new();
        let remainder_raw = remainder.as_raw();

        Integer::mp_int_div(self, rhs, ptr::null_mut(), remainder_raw);

        remainder
    }

    /// Divide two integers and assign the remainder to self
    pub fn remainder_assign(&mut self, rhs: &Self) {
        let remainder_raw = self.as_raw();

        Integer::mp_int_div(self, rhs, ptr::null_mut(), remainder_raw);
    }

    /// Perform the integer division with primitive value operation.
    ///
    /// # Safety
    ///
    /// Either `out_quotient` or `out_remainder` may be `null`, but not both.
    /// These also may alias with the `Integer` input argument, `dividend`.
    fn mp_int_div_value(
        dividend: &Integer,
        divisor: impl Into<c_long>,
        out_quotient: creachadair_imath_sys::mp_int,
        out_remainder: *mut c_long,
    ) {
        let divident_raw = dividend.as_raw();

        // This operation is safe bc `dividend` has been initialized. Also, runtime
        // checks of `out_quotient` and `out_remainder` ensure that a result can
        // be written somewhere.
        let op_res = unsafe {
            creachadair_imath_sys::mp_int_div_value(
                divident_raw,
                divisor.into(),
                out_quotient,
                out_remainder,
            )
        };

        imath_check_panic!(op_res, "Operation failed!");
    }

    #[allow(dead_code)]
    pub(crate) fn divide_full_c_long<V>(&self, value: V) -> (Integer, V)
    where
        V: Into<c_long>,
        c_long: TryInto<V>,
    {
        let mut remainder: c_long = 0;
        let quotient = Integer::new();
        let quotient_raw = quotient.as_raw();

        Integer::mp_int_div_value(self, value.into(), quotient_raw, &mut remainder);

        // This should not panic bc the modulo operation will always return within the
        // range [0, value].
        (
            quotient,
            remainder
                .try_into()
                .map_err(|_| Error::RemainderOutsideBounds)
                .unwrap(),
        )
    }

    pub(crate) fn divide_c_long(&self, value: impl Into<c_long>) -> Self {
        let quotient = Integer::new();
        let quotient_raw = quotient.as_raw();

        Integer::mp_int_div_value(self, value, quotient_raw, ptr::null_mut());

        quotient
    }

    pub(crate) fn divide_c_long_assign(&mut self, value: impl Into<c_long>) {
        let quotient_raw = self.as_raw();

        Integer::mp_int_div_value(self, value, quotient_raw, ptr::null_mut());
    }

    pub(crate) fn remainder_c_long<V>(&self, value: V) -> V
    where
        V: Into<c_long>,
        c_long: TryInto<V>,
    {
        let mut result: c_long = 0;
        let result_raw = (&mut result) as *mut _;

        Integer::mp_int_div_value(self, value, ptr::null_mut(), result_raw);

        // This will not panic bc the modulo operation will always return within the
        // range [0, value).
        result
            .try_into()
            .map_err(|_| Error::RemainderOutsideBounds)
            .unwrap()
    }

    pub(crate) fn remainder_c_long_assign(&mut self, value: impl Into<c_long>) {
        let remainder_raw = self.as_raw();

        Integer::mp_int_div(
            self,
            &Integer::from(value.into()),
            ptr::null_mut(),
            remainder_raw,
        );
    }
}

impl Sum for Integer {
    fn sum<I: Iterator<Item = Integer>>(iter: I) -> Self {
        let mut s = Integer::from(0);

        for v in iter {
            s += v;
        }

        s
    }
}

impl Product for Integer {
    fn product<I: Iterator<Item = Integer>>(iter: I) -> Self {
        let mut s = Integer::from(1);

        for v in iter {
            s *= v;
        }

        s
    }
}

pub(crate) mod helpers {
    use crate::{error::Error, integer::Integer};
    use core::convert::TryInto;
    use std::os::raw::c_long;

    #[inline]
    pub fn reverse_add_c_long(other: impl Into<c_long>, integer: &Integer) -> Integer {
        Integer::add_c_long(integer, other)
    }

    #[inline]
    pub fn reverse_add_assign(integer: &Integer, other: &mut Integer) {
        Integer::add_assign(other, integer);
    }

    #[inline]
    pub fn reverse_add_c_long_assign(other: impl Into<c_long>, integer: &mut Integer) {
        Integer::add_c_long_assign(integer, other);
    }

    #[inline]
    pub fn reverse_multiply_c_long(other: impl Into<c_long>, integer: &Integer) -> Integer {
        Integer::multiply_c_long(integer, other)
    }

    #[inline]
    pub fn reverse_multiply_assign(integer: &Integer, other: &mut Integer) {
        Integer::multiply_assign(other, integer);
    }

    #[inline]
    pub fn reverse_multiply_c_long_assign(other: impl Into<c_long>, integer: &mut Integer) {
        Integer::multiply_c_long_assign(integer, other);
    }

    #[inline]
    pub fn reverse_remainder<V>(value: V, integer: &Integer) -> V
    where
        Integer: TryInto<V> + From<V>,
    {
        let mut lhs = Integer::from(value);

        Integer::remainder_assign(&mut lhs, integer);

        lhs.try_into()
            .map_err(|_| Error::RemainderOutsideBounds)
            .unwrap()
    }

    #[inline]
    pub fn remainder_reuse<V>(mut integer: Integer, rhs: V) -> V
    where
        Integer: TryInto<V> + From<V>,
    {
        Integer::remainder_assign(&mut integer, &Integer::from(rhs));

        integer
            .try_into()
            .map_err(|_| Error::RemainderOutsideBounds)
            .unwrap()
    }

    #[inline]
    pub fn remainder_ref<V>(integer: &Integer, rhs: V) -> V
    where
        Integer: TryInto<V> + From<V>,
    {
        Integer::remainder(integer, &Integer::from(rhs))
            .try_into()
            .map_err(|_| Error::RemainderOutsideBounds)
            .unwrap()
    }

    #[inline]
    pub fn c_long_remainder_assign<V>(value: &mut V, integer: &Integer)
    where
        Integer: TryInto<V> + From<V>,
        V: Copy,
    {
        let mut lhs = Integer::from(*value);

        Integer::remainder_assign(&mut lhs, integer);

        *value = lhs
            .try_into()
            .map_err(|_| Error::RemainderOutsideBounds)
            .unwrap();
    }
}

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

    fn fibonacci(mut n: usize) -> Integer {
        let mut f0 = Integer::new();
        let mut f1 = Integer::from(1);

        if n == 0 {
            f0
        } else if n == 1 {
            f1
        } else {
            n -= 1;

            while n > 0 {
                let temp = f1;
                f1 = &temp + f0;
                f0 = temp;

                n -= 1;
            }

            f1
        }
    }

    #[test]
    fn fibonacci_values() {
        assert_eq!(fibonacci(1).to_string(), "1");
        assert_eq!(fibonacci(10).to_string(), "55");
        assert_eq!(fibonacci(50).to_string(), "12586269025");
        assert_eq!(fibonacci(100).to_string(), "354224848179261915075");
    }

    #[test]
    fn add_integers() {
        let a = Integer::from_c_long(11111);
        let b = Integer::from_c_long(33333);
        let c = a + b;

        assert_eq!(c, 44_444);
    }

    #[test]
    fn add_assign_integers() {
        let mut a = Integer::from_c_long(11111);
        let b = Integer::from_c_long(33333);
        a += b;

        assert_eq!(a, 44_444);
    }

    #[test]
    fn subtract_integers() {
        let a = Integer::from_c_long(12345);
        let b = Integer::from_c_long(1234);
        let c = a - b;

        assert_eq!(c, 11_111);
    }

    #[test]
    fn subtract_assign_integers() {
        let mut a = Integer::from_c_long(12345);
        let b = Integer::from_c_long(1234);
        a -= b;

        assert_eq!(a, 11_111);
    }

    #[test]
    fn multiply_integers() {
        let a = Integer::from_c_long(50505);
        let b = Integer::from_c_long(5050);
        let c = a * b;

        assert_eq!(c, 255_050_250);
    }

    #[test]
    fn multiply_assign_integers() {
        let mut a = Integer::from_c_long(50505);
        let b = Integer::from_c_long(5050);

        a *= b;
        assert_eq!(a, 255_050_250);
    }

    #[test]
    fn divide_integers() {
        let a: Integer = "52384129912341238437480192384".parse().unwrap();

        #[allow(clippy::eq_op)]
        let one = &a / &a;
        assert_eq!(one, 1);
        assert_eq!(&a / 10_000_000_000_000_000_000_000u128, 5_238_412);

        let b: Integer = 1_234_567.into();
        assert_eq!(&b / 123_456, 10);
        assert_eq!(&b / 3, 411_522);
        assert_eq!(&b / -3, -411_522);
        assert_eq!(&b / -230, -5_367)
    }

    #[test]
    fn divide_assign_integers() {
        let mut a: Integer = "52384129912341238437480192384".parse().unwrap();

        a /= a.clone();
        assert_eq!(a, 1);
    }

    #[test]
    fn remainder_integers() {
        let a: Integer = "52384129912341238437480192384".parse().unwrap();

        let res_u8: u8 = &a % 122u8;
        assert_eq!(res_u8, 62);

        let res_u16: u16 = &a % 60_000u16;
        assert_eq!(res_u16, 12384);

        let res_u32: i32 = &a % 127_384i32;
        assert_eq!(res_u32, 85248);
    }

    #[test]
    fn remainder_assign_integers() {
        let mut a: Integer = "52384129912341238437480192384".parse().unwrap();

        a %= 60_000u16;
        assert_eq!(a, 12384);
    }

    #[test]
    fn negate_integers() {
        let a: Integer = "52384129912341238437480192384".parse().unwrap();
        let b = -a;

        let string_repr = b.to_string();
        assert_eq!(&string_repr, "-52384129912341238437480192384");
    }

    #[test]
    fn absolute_value_integer() {
        let neg_int: Integer = "-37129740".parse().unwrap();
        let pos_int: Integer = "37129740".parse().unwrap();

        assert_eq!(neg_int.absolute_value(), pos_int);
        assert_eq!(pos_int.absolute_value(), 37_129_740);
    }
}