-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathlib.rs
2959 lines (2596 loc) · 88 KB
/
lib.rs
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 Adam Sunderland
// 2016-2017 Andrew Kubera
// 2017 Ruben De Smet
// See the COPYRIGHT file at the top-level directory of this
// distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A Big Decimal
//!
//! `BigDecimal` allows storing any real number to arbitrary precision; which
//! avoids common floating point errors (such as 0.1 + 0.2 ≠ 0.3) at the
//! cost of complexity.
//!
//! Internally, `BigDecimal` uses a `BigInt` object, paired with a 64-bit
//! integer which determines the position of the decimal point. Therefore,
//! the precision *is not* actually arbitrary, but limited to 2<sup>63</sup>
//! decimal places.
//!
//! Common numerical operations are overloaded, so we can treat them
//! the same way we treat other numbers.
//!
//! It is not recommended to convert a floating point number to a decimal
//! directly, as the floating point representation may be unexpected.
//!
//! # Example
//!
//! ```
//! use bigdecimal::BigDecimal;
//! use std::str::FromStr;
//!
//! let input = "0.8";
//! let dec = BigDecimal::from_str(&input).unwrap();
//! let float = f32::from_str(&input).unwrap();
//!
//! println!("Input ({}) with 10 decimals: {} vs {})", input, dec, float);
//! ```
extern crate num_bigint;
extern crate num_integer;
extern crate num_traits as traits;
#[cfg(feature = "serde")]
extern crate serde;
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::default::Default;
use std::error::Error;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::num::{ParseFloatError, ParseIntError};
use std::ops::{Add, AddAssign, Div, Mul, MulAssign, Neg, Rem, Sub, SubAssign};
use std::iter::Sum;
use std::str::{self, FromStr};
use num_bigint::{BigInt, ParseBigIntError, Sign, ToBigInt};
use num_integer::Integer;
pub use traits::{FromPrimitive, Num, One, Signed, ToPrimitive, Zero};
#[macro_use]
mod macros;
#[inline(always)]
fn ten_to_the(pow: u64) -> BigInt {
if pow < 20 {
BigInt::from(10u64.pow(pow as u32))
} else {
let (half, rem) = pow.div_rem(&16);
let mut x = ten_to_the(half);
for _ in 0..4 {
x = &x * &x;
}
if rem == 0 {
x
} else {
x * ten_to_the(rem)
}
}
}
#[inline(always)]
fn count_decimal_digits(int: &BigInt) -> u64 {
if int.is_zero() {
return 1;
}
// guess number of digits based on number of bits in UInt
let mut digits = (int.bits() as f64 / 3.3219280949) as u64;
let mut num = ten_to_the(digits);
while int >= &num {
num *= 10u8;
digits += 1;
}
digits
}
/// Internal function used for rounding
///
/// returns 1 if most significant digit is >= 5, otherwise 0
///
/// This is used after dividing a number by a power of ten and
/// rounding the last digit.
///
#[inline(always)]
fn get_rounding_term(num: &BigInt) -> u8 {
if num.is_zero() {
return 0;
}
let digits = (num.bits() as f64 / 3.3219280949) as u64;
let mut n = ten_to_the(digits);
// loop-method
loop {
if num < &n {
return 1;
}
n *= 5;
if num < &n {
return 0;
}
n *= 2;
}
// string-method
// let s = format!("{}", num);
// let high_digit = u8::from_str(&s[0..1]).unwrap();
// if high_digit < 5 { 0 } else { 1 }
}
/// A big decimal type.
///
#[derive(Clone, Eq)]
pub struct BigDecimal {
int_val: BigInt,
// A positive scale means a negative power of 10
scale: i64,
}
impl BigDecimal {
/// Creates and initializes a `BigDecimal`.
///
#[inline]
pub fn new(digits: BigInt, scale: i64) -> BigDecimal {
BigDecimal {
int_val: digits,
scale: scale,
}
}
/// Creates and initializes a `BigDecimal`.
///
/// Decodes using `str::from_utf8` and forwards to `BigDecimal::from_str_radix`.
/// Only base-10 is supported.
///
/// # Examples
///
/// ```
/// use bigdecimal::{BigDecimal, Zero};
///
/// assert_eq!(BigDecimal::parse_bytes(b"0", 10).unwrap(), BigDecimal::zero());
/// assert_eq!(BigDecimal::parse_bytes(b"13", 10).unwrap(), BigDecimal::from(13));
/// ```
#[inline]
pub fn parse_bytes(buf: &[u8], radix: u32) -> Option<BigDecimal> {
str::from_utf8(buf)
.ok()
.and_then(|s| BigDecimal::from_str_radix(s, radix).ok())
}
/// Return a new BigDecimal object equivalent to self, with internal
/// scaling set to the number specified.
/// If the new_scale is lower than the current value (indicating a larger
/// power of 10), digits will be dropped (as precision is lower)
///
#[inline]
pub fn with_scale(&self, new_scale: i64) -> BigDecimal {
if self.int_val.is_zero() {
return BigDecimal::new(BigInt::zero(), new_scale);
}
if new_scale > self.scale {
let scale_diff = new_scale - self.scale;
let int_val = &self.int_val * ten_to_the(scale_diff as u64);
BigDecimal::new(int_val, new_scale)
} else if new_scale < self.scale {
let scale_diff = self.scale - new_scale;
let int_val = &self.int_val / ten_to_the(scale_diff as u64);
BigDecimal::new(int_val, new_scale)
} else {
self.clone()
}
}
#[inline(always)]
fn take_and_scale(mut self, new_scale: i64) -> BigDecimal {
// let foo = bar.moved_and_scaled_to()
if self.int_val.is_zero() {
return BigDecimal::new(BigInt::zero(), new_scale);
}
if new_scale > self.scale {
self.int_val *= ten_to_the((new_scale - self.scale) as u64);
BigDecimal::new(self.int_val, new_scale)
} else if new_scale < self.scale {
self.int_val /= ten_to_the((self.scale - new_scale) as u64);
BigDecimal::new(self.int_val, new_scale)
} else {
self
}
}
/// Return a new BigDecimal object with precision set to new value
///
#[inline]
pub fn with_prec(&self, prec: u64) -> BigDecimal {
let digits = self.digits();
if digits > prec {
let diff = digits - prec;
let p = ten_to_the(diff);
let (mut q, r) = self.int_val.div_rem(&p);
// check for "leading zero" in remainder term; otherwise round
if p < 10 * &r {
q += get_rounding_term(&r);
}
BigDecimal {
int_val: q,
scale: self.scale - diff as i64,
}
} else if digits < prec {
let diff = prec - digits;
BigDecimal {
int_val: &self.int_val * ten_to_the(diff),
scale: self.scale + diff as i64,
}
} else {
self.clone()
}
}
/// Return the sign of the `BigDecimal` as `num::bigint::Sign`.
///
/// # Examples
///
/// ```
/// extern crate num_bigint;
/// extern crate bigdecimal;
/// use std::str::FromStr;
///
/// assert_eq!(bigdecimal::BigDecimal::from_str("-1").unwrap().sign(), num_bigint::Sign::Minus);
/// assert_eq!(bigdecimal::BigDecimal::from_str("0").unwrap().sign(), num_bigint::Sign::NoSign);
/// assert_eq!(bigdecimal::BigDecimal::from_str("1").unwrap().sign(), num_bigint::Sign::Plus);
/// ```
#[inline]
pub fn sign(&self) -> num_bigint::Sign {
self.int_val.sign()
}
/// Return the internal big integer value and an exponent. Note that a positive
/// exponent indicates a negative power of 10.
///
/// # Examples
///
/// ```
/// extern crate num_bigint;
/// extern crate bigdecimal;
/// use std::str::FromStr;
///
/// assert_eq!(bigdecimal::BigDecimal::from_str("1.1").unwrap().as_bigint_and_exponent(),
/// (num_bigint::BigInt::from_str("11").unwrap(), 1));
#[inline]
pub fn as_bigint_and_exponent(&self) -> (BigInt, i64) {
(self.int_val.clone(), self.scale)
}
/// Convert into the internal big integer value and an exponent. Note that a positive
/// exponent indicates a negative power of 10.
///
/// # Examples
///
/// ```
/// extern crate num_bigint;
/// extern crate bigdecimal;
/// use std::str::FromStr;
///
/// assert_eq!(bigdecimal::BigDecimal::from_str("1.1").unwrap().into_bigint_and_exponent(),
/// (num_bigint::BigInt::from_str("11").unwrap(), 1));
#[inline]
pub fn into_bigint_and_exponent(self) -> (BigInt, i64) {
(self.int_val, self.scale)
}
/// Number of digits in the non-scaled integer representation
///
#[inline]
pub fn digits(&self) -> u64 {
count_decimal_digits(&self.int_val)
}
/// Compute the absolute value of number
#[inline]
pub fn abs(&self) -> BigDecimal {
BigDecimal {
int_val: self.int_val.abs(),
scale: self.scale,
}
}
#[inline]
pub fn double(&self) -> BigDecimal {
if self.is_zero() {
self.clone()
} else {
BigDecimal {
int_val: self.int_val.clone() * 2,
scale: self.scale,
}
}
}
/// Divide this efficiently by 2
///
/// Note, if this is odd, the precision will increase by 1, regardless
/// of the context's limit.
///
#[inline]
pub fn half(&self) -> BigDecimal {
if self.is_zero() {
self.clone()
} else if self.int_val.is_even() {
BigDecimal {
int_val: self.int_val.clone().div(2u8),
scale: self.scale,
}
} else {
BigDecimal {
int_val: self.int_val.clone().mul(5u8),
scale: self.scale + 1,
}
}
}
///
#[inline]
pub fn square(&self) -> BigDecimal {
if self.is_zero() || self.is_one() {
self.clone()
} else {
BigDecimal {
int_val: self.int_val.clone() * &self.int_val,
scale: self.scale * 2,
}
}
}
#[inline]
pub fn cube(&self) -> BigDecimal {
if self.is_zero() || self.is_one() {
self.clone()
} else {
BigDecimal {
int_val: self.int_val.clone() * &self.int_val * &self.int_val,
scale: self.scale * 3,
}
}
}
/// Take the square root of the number
///
/// If the value is < 0, None is returned
///
#[inline]
pub fn sqrt(&self) -> Option<BigDecimal> {
if self.is_zero() || self.is_one() {
return Some(self.clone());
}
if self.is_negative() {
return None;
}
// make guess
let guess = {
let log2_10 = 3.32192809488736234787031942948939018_f64;
let magic_guess_scale = 1.1951678538495576_f64;
let initial_guess = (self.int_val.bits() as f64 - self.scale as f64 * log2_10) / 2.0;
let res = magic_guess_scale * initial_guess.exp2();
if res.is_normal() {
BigDecimal::try_from(res).unwrap()
} else {
// can't guess with float - just guess magnitude
let scale =
(self.int_val.bits() as f64 / -log2_10 + self.scale as f64).round() as i64;
BigDecimal::new(BigInt::from(1), scale / 2)
}
};
// // wikipedia example - use for testing the algorithm
// if self == &BigDecimal::from_str("125348").unwrap() {
// running_result = BigDecimal::from(600)
// }
// TODO: Use context variable to set precision
let max_precision = 100;
let next_iteration = move |r: BigDecimal| {
// division needs to be precise to (at least) one extra digit
let tmp = impl_division(
self.int_val.clone(),
&r.int_val,
self.scale - r.scale,
max_precision + 1,
);
// half will increase precision on each iteration
(tmp + r).half()
};
// calculate first iteration
let mut running_result = next_iteration(guess);
let mut prev_result = BigDecimal::one();
let mut result = BigDecimal::zero();
// TODO: Prove that we don't need to arbitrarily limit iterations
// and that convergence can be calculated
while prev_result != result {
// store current result to test for convergence
prev_result = result;
// calculate next iteration
running_result = next_iteration(running_result);
// 'result' has clipped precision, 'running_result' has full precision
result = if running_result.digits() > max_precision {
running_result.with_prec(max_precision)
} else {
running_result.clone()
};
}
return Some(result);
}
/// Take the cube root of the number
///
#[inline]
pub fn cbrt(&self) -> BigDecimal {
if self.is_zero() || self.is_one() {
return self.clone();
}
if self.is_negative() {
return -self.abs().cbrt();
}
// make guess
let guess = {
let log2_10 = 3.32192809488736234787031942948939018_f64;
let magic_guess_scale = 1.124960491619939_f64;
let initial_guess = (self.int_val.bits() as f64 - self.scale as f64 * log2_10) / 3.0;
let res = magic_guess_scale * initial_guess.exp2();
if res.is_normal() {
BigDecimal::try_from(res).unwrap()
} else {
// can't guess with float - just guess magnitude
let scale =
(self.int_val.bits() as f64 / log2_10 - self.scale as f64).round() as i64;
BigDecimal::new(BigInt::from(1), -scale / 3)
}
};
// TODO: Use context variable to set precision
let max_precision = 100;
let three = BigDecimal::from(3);
let next_iteration = move |r: BigDecimal| {
let sqrd = r.square();
let tmp = impl_division(
self.int_val.clone(),
&sqrd.int_val,
self.scale - sqrd.scale,
max_precision + 1,
);
let tmp = tmp + r.double();
impl_division(
tmp.int_val,
&three.int_val,
tmp.scale - three.scale,
max_precision + 1,
)
};
// result initial
let mut running_result = next_iteration(guess);
let mut prev_result = BigDecimal::one();
let mut result = BigDecimal::zero();
// TODO: Prove that we don't need to arbitrarily limit iterations
// and that convergence can be calculated
while prev_result != result {
// store current result to test for convergence
prev_result = result;
running_result = next_iteration(running_result);
// result has clipped precision, running_result has full precision
result = if running_result.digits() > max_precision {
running_result.with_prec(max_precision)
} else {
running_result.clone()
};
}
return result;
}
/// Compute the reciprical of the number: x<sup>-1</sup>
#[inline]
pub fn inverse(&self) -> BigDecimal {
if self.is_zero() || self.is_one() {
return self.clone();
}
if self.is_negative() {
return self.abs().inverse().neg();
}
let guess = {
let bits = self.int_val.bits() as f64;
let scale = self.scale as f64;
let log2_10 = 3.32192809488736234787031942948939018_f64;
let magic_factor = 0.721507597259061_f64;
let initial_guess = scale * log2_10 - bits;
let res = magic_factor * initial_guess.exp2();
if res.is_normal() {
BigDecimal::try_from(res).unwrap()
} else {
// can't guess with float - just guess magnitude
let scale = (bits / log2_10 + scale).round() as i64;
BigDecimal::new(BigInt::from(1), -scale)
}
};
let max_precision = 100;
let next_iteration = move |r: BigDecimal| {
let two = BigDecimal::from(2);
let tmp = two - self * &r;
r * tmp
};
// calculate first iteration
let mut running_result = next_iteration(guess);
let mut prev_result = BigDecimal::one();
let mut result = BigDecimal::zero();
// TODO: Prove that we don't need to arbitrarily limit iterations
// and that convergence can be calculated
while prev_result != result {
// store current result to test for convergence
prev_result = result;
// calculate next iteration
running_result = next_iteration(running_result).with_prec(max_precision);
// 'result' has clipped precision, 'running_result' has full precision
result = if running_result.digits() > max_precision {
running_result.with_prec(max_precision)
} else {
running_result.clone()
};
}
return result;
}
/// Return number rounded to round_digits precision after the decimal point
pub fn round(&self, round_digits: i64) -> BigDecimal {
let (bigint, decimal_part_digits) = self.as_bigint_and_exponent();
let need_to_round_digits = decimal_part_digits - round_digits;
if round_digits >= 0 && need_to_round_digits <= 0 {
return self.clone();
}
let mut number = bigint.to_i128().unwrap();
if number < 0 {
number = -number;
}
for _ in 0..(need_to_round_digits - 1) {
number /= 10;
}
let digit = number % 10;
if digit <= 4 {
self.with_scale(round_digits)
} else if bigint.is_negative() {
self.with_scale(round_digits) - BigDecimal::new(BigInt::from(1), round_digits)
} else {
self.with_scale(round_digits) + BigDecimal::new(BigInt::from(1), round_digits)
}
}
/// Return true if this number has zero fractional part (is equal
/// to an integer)
///
#[inline]
pub fn is_integer(&self) -> bool {
if self.scale <= 0 {
true
} else {
(self.int_val.clone() % ten_to_the(self.scale as u64)).is_zero()
}
}
/// Evaluate the natural-exponential function e<sup>x</sup>
///
#[inline]
pub fn exp(&self) -> BigDecimal {
if self.is_zero() {
return BigDecimal::one();
}
let precision = self.digits();
let mut term = self.clone();
let mut result = self.clone() + BigDecimal::one();
let mut prev_result = result.clone();
let mut factorial = BigInt::one();
for n in 2.. {
term *= self;
factorial *= n;
// ∑ term=x^n/n!
result += impl_division(
term.int_val.clone(),
&factorial,
term.scale,
117 + precision,
);
let trimmed_result = result.with_prec(105);
if prev_result == trimmed_result {
return trimmed_result.with_prec(100);
}
prev_result = trimmed_result;
}
return result.with_prec(100);
}
#[must_use]
pub fn normalized(&self) -> BigDecimal {
if self == &BigDecimal::zero() {
return BigDecimal::zero()
}
let (sign, mut digits) = self.int_val.to_radix_be(10);
let trailing_count = digits.iter().rev().take_while(|i| **i == 0).count();
let trunc_to = digits.len() - trailing_count as usize;
digits.truncate(trunc_to);
let int_val = BigInt::from_radix_be(sign, &digits, 10).unwrap();
let scale = self.scale - trailing_count as i64;
BigDecimal::new(int_val, scale)
}
}
#[derive(Debug, PartialEq)]
pub enum ParseBigDecimalError {
ParseDecimal(ParseFloatError),
ParseInt(ParseIntError),
ParseBigInt(ParseBigIntError),
Empty,
Other(String),
}
impl fmt::Display for ParseBigDecimalError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use ParseBigDecimalError::*;
match *self {
ParseDecimal(ref e) => e.fmt(f),
ParseInt(ref e) => e.fmt(f),
ParseBigInt(ref e) => e.fmt(f),
Empty => "Failed to parse empty string".fmt(f),
Other(ref reason) => reason[..].fmt(f),
}
}
}
impl Error for ParseBigDecimalError {
fn description(&self) -> &str {
"failed to parse bigint/biguint"
}
}
impl From<ParseFloatError> for ParseBigDecimalError {
fn from(err: ParseFloatError) -> ParseBigDecimalError {
ParseBigDecimalError::ParseDecimal(err)
}
}
impl From<ParseIntError> for ParseBigDecimalError {
fn from(err: ParseIntError) -> ParseBigDecimalError {
ParseBigDecimalError::ParseInt(err)
}
}
impl From<ParseBigIntError> for ParseBigDecimalError {
fn from(err: ParseBigIntError) -> ParseBigDecimalError {
ParseBigDecimalError::ParseBigInt(err)
}
}
impl FromStr for BigDecimal {
type Err = ParseBigDecimalError;
#[inline]
fn from_str(s: &str) -> Result<BigDecimal, ParseBigDecimalError> {
BigDecimal::from_str_radix(s, 10)
}
}
#[allow(deprecated)] // trim_right_match -> trim_end_match
impl Hash for BigDecimal {
fn hash<H: Hasher>(&self, state: &mut H) {
let mut dec_str = self.int_val.to_str_radix(10).to_string();
let scale = self.scale;
let zero = self.int_val.is_zero();
if scale > 0 && !zero {
let mut cnt = 0;
dec_str = dec_str
.trim_right_matches(|x| {
cnt += 1;
x == '0' && cnt <= scale
})
.to_string();
} else if scale < 0 && !zero {
dec_str.push_str(&"0".repeat(self.scale.abs() as usize));
}
dec_str.hash(state);
}
}
impl PartialOrd for BigDecimal {
#[inline]
fn partial_cmp(&self, other: &BigDecimal) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for BigDecimal {
/// Complete ordering implementation for BigDecimal
///
/// # Example
///
/// ```
/// use std::str::FromStr;
///
/// let a = bigdecimal::BigDecimal::from_str("-1").unwrap();
/// let b = bigdecimal::BigDecimal::from_str("1").unwrap();
/// assert!(a < b);
/// assert!(b > a);
/// let c = bigdecimal::BigDecimal::from_str("1").unwrap();
/// assert!(b >= c);
/// assert!(c >= b);
/// let d = bigdecimal::BigDecimal::from_str("10.0").unwrap();
/// assert!(d > c);
/// let e = bigdecimal::BigDecimal::from_str(".5").unwrap();
/// assert!(e < c);
/// ```
#[inline]
fn cmp(&self, other: &BigDecimal) -> Ordering {
let scmp = self.sign().cmp(&other.sign());
if scmp != Ordering::Equal {
return scmp;
}
match self.sign() {
Sign::NoSign => Ordering::Equal,
_ => {
let tmp = self - other;
match tmp.sign() {
Sign::Plus => Ordering::Greater,
Sign::Minus => Ordering::Less,
Sign::NoSign => Ordering::Equal,
}
}
}
}
}
impl PartialEq for BigDecimal {
#[inline]
fn eq(&self, rhs: &BigDecimal) -> bool {
// fix scale and test equality
if self.scale > rhs.scale {
let scaled_int_val = &rhs.int_val * ten_to_the((self.scale - rhs.scale) as u64);
self.int_val == scaled_int_val
} else if self.scale < rhs.scale {
let scaled_int_val = &self.int_val * ten_to_the((rhs.scale - self.scale) as u64);
scaled_int_val == rhs.int_val
} else {
self.int_val == rhs.int_val
}
}
}
impl Default for BigDecimal {
#[inline]
fn default() -> BigDecimal {
Zero::zero()
}
}
impl Zero for BigDecimal {
#[inline]
fn zero() -> BigDecimal {
BigDecimal::new(BigInt::zero(), 0)
}
#[inline]
fn is_zero(&self) -> bool {
self.int_val.is_zero()
}
}
impl One for BigDecimal {
#[inline]
fn one() -> BigDecimal {
BigDecimal::new(BigInt::one(), 0)
}
}
impl Add<BigDecimal> for BigDecimal {
type Output = BigDecimal;
#[inline]
fn add(self, rhs: BigDecimal) -> BigDecimal {
let mut lhs = self;
match lhs.scale.cmp(&rhs.scale) {
Ordering::Equal => {
lhs.int_val += rhs.int_val;
lhs
}
Ordering::Less => lhs.take_and_scale(rhs.scale) + rhs,
Ordering::Greater => rhs.take_and_scale(lhs.scale) + lhs,
}
}
}
impl<'a> Add<&'a BigDecimal> for BigDecimal {
type Output = BigDecimal;
#[inline]
fn add(self, rhs: &'a BigDecimal) -> BigDecimal {
let mut lhs = self;
match lhs.scale.cmp(&rhs.scale) {
Ordering::Equal => {
lhs.int_val += &rhs.int_val;
lhs
}
Ordering::Less => lhs.take_and_scale(rhs.scale) + rhs,
Ordering::Greater => rhs.with_scale(lhs.scale) + lhs,
}
}
}
impl<'a> Add<BigDecimal> for &'a BigDecimal {
type Output = BigDecimal;
#[inline]
fn add(self, rhs: BigDecimal) -> BigDecimal {
rhs + self
}
}
impl<'a, 'b> Add<&'b BigDecimal> for &'a BigDecimal {
type Output = BigDecimal;
#[inline]
fn add(self, rhs: &BigDecimal) -> BigDecimal {
let lhs = self;
if self.scale < rhs.scale {
lhs.with_scale(rhs.scale) + rhs
} else if self.scale > rhs.scale {
rhs.with_scale(lhs.scale) + lhs
} else {
BigDecimal::new(lhs.int_val.clone() + &rhs.int_val, lhs.scale)
}
}
}
impl Add<BigInt> for BigDecimal {
type Output = BigDecimal;
#[inline]
fn add(self, rhs: BigInt) -> BigDecimal {
let mut lhs = self;
match lhs.scale.cmp(&0) {
Ordering::Equal => {
lhs.int_val += rhs;
lhs
}
Ordering::Greater => {
lhs.int_val += rhs * ten_to_the(lhs.scale as u64);
lhs
}
Ordering::Less => lhs.take_and_scale(0) + rhs,
}
}
}
impl<'a> Add<&'a BigInt> for BigDecimal {
type Output = BigDecimal;
#[inline]
fn add(self, rhs: &BigInt) -> BigDecimal {
let mut lhs = self;
match lhs.scale.cmp(&0) {
Ordering::Equal => {
lhs.int_val += rhs;
lhs
}
Ordering::Greater => {
lhs.int_val += rhs * ten_to_the(lhs.scale as u64);
lhs
}
Ordering::Less => lhs.take_and_scale(0) + rhs,
}
}
}
impl<'a> Add<BigInt> for &'a BigDecimal {
type Output = BigDecimal;
#[inline]
fn add(self, rhs: BigInt) -> BigDecimal {
BigDecimal::new(rhs, 0) + self
}
}
impl<'a, 'b> Add<&'a BigInt> for &'b BigDecimal {
type Output = BigDecimal;
#[inline]
fn add(self, rhs: &BigInt) -> BigDecimal {
self.with_scale(0) + rhs
}
}
forward_val_assignop!(impl AddAssign for BigDecimal, add_assign);
impl<'a> AddAssign<&'a BigDecimal> for BigDecimal {
#[inline]
fn add_assign(&mut self, rhs: &BigDecimal) {
if self.scale < rhs.scale {
let scaled = self.with_scale(rhs.scale);
self.int_val = scaled.int_val + &rhs.int_val;
self.scale = rhs.scale;
} else if self.scale > rhs.scale {
let scaled = rhs.with_scale(self.scale);
self.int_val += scaled.int_val;
} else {
self.int_val += &rhs.int_val;
}
}
}
impl<'a> AddAssign<BigInt> for BigDecimal {
#[inline]
fn add_assign(&mut self, rhs: BigInt) {
*self += BigDecimal::new(rhs, 0)
}
}
impl<'a> AddAssign<&'a BigInt> for BigDecimal {
#[inline]
fn add_assign(&mut self, rhs: &BigInt) {
/* // which one looks best?
if self.scale == 0 {
self.int_val += rhs;
} else if self.scale > 0 {
self.int_val += rhs * ten_to_the(self.scale as u64);
} else {
self.int_val *= ten_to_the((-self.scale) as u64);
self.int_val += rhs;
self.scale = 0;