-
Notifications
You must be signed in to change notification settings - Fork 173
/
decimal.rs
2469 lines (2228 loc) · 78.3 KB
/
decimal.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
use Error;
use num::{FromPrimitive, One, ToPrimitive, Zero};
use std::cmp::*;
use std::cmp::Ordering::Equal;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter::repeat;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign};
use std::str::FromStr;
// Sign mask for the flags field. A value of zero in this bit indicates a
// positive Decimal value, and a value of one in this bit indicates a
// negative Decimal value.
const SIGN_MASK: u32 = 0x8000_0000;
// Scale mask for the flags field. This byte in the flags field contains
// the power of 10 to divide the Decimal value by. The scale byte must
// contain a value between 0 and 28 inclusive.
const SCALE_MASK: u32 = 0x00FF_0000;
const U8_MASK: u32 = 0x0000_00FF;
const U32_MASK: u64 = 0xFFFF_FFFF;
// Number of bits scale is shifted by.
const SCALE_SHIFT: u32 = 16;
// The maximum supported precision
const MAX_PRECISION: u32 = 28;
static ONE_INTERNAL_REPR: [u32; 3] = [1, 0, 0];
lazy_static! {
static ref MIN: Decimal = Decimal {
flags: 2_147_483_648,
lo: 4_294_967_295,
mid: 4_294_967_295,
hi: 4_294_967_295
};
static ref MAX: Decimal = Decimal {
flags: 0,
lo: 4_294_967_295,
mid: 4_294_967_295,
hi: 4_294_967_295
};
}
// Fast access for 10^n where n is 0-9
static POWERS_10: [u32; 10] = [
1,
10,
100,
1_000,
10_000,
100_000,
1_000_000,
10_000_000,
100_000_000,
1_000_000_000,
];
// Fast access for 10^n where n is 10-19
#[allow(dead_code)]
static BIG_POWERS_10: [u64; 10] = [
10_000_000_000,
100_000_000_000,
1_000_000_000_000,
10_000_000_000_000,
100_000_000_000_000,
1_000_000_000_000_000,
10_000_000_000_000_000,
100_000_000_000_000_000,
1_000_000_000_000_000_000,
10_000_000_000_000_000_000,
];
/// `Decimal` represents a 128 bit representation of a fixed-precision decimal number.
/// The finite set of values of type `Decimal` are of the form m / 10<sup>e</sup>,
/// where m is an integer such that -2<sup>96</sup> <= m <= 2<sup>96</sup>, and e is an integer
/// between 0 and 28 inclusive.
#[derive(Clone, Copy, Debug)]
pub struct Decimal {
// Bits 0-15: unused
// Bits 16-23: Contains "e", a value between 0-28 that indicates the scale
// Bits 24-30: unused
// Bit 31: the sign of the Decimal value, 0 meaning positive and 1 meaning negative.
flags: u32,
// The lo, mid, hi, and flags fields contain the representation of the
// Decimal value as a 96-bit integer.
hi: u32,
lo: u32,
mid: u32,
}
#[allow(dead_code)]
impl Decimal {
/// Returns a `Decimal` with a 64 bit `m` representation and corresponding `e` scale.
///
/// # Arguments
///
/// * `num` - An i64 that represents the `m` portion of the decimal number
/// * `scale` - A u32 representing the `e` portion of the decimal number.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let pi = Decimal::new(3141, 3);
/// assert_eq!(pi.to_string(), "3.141");
/// ```
pub fn new(num: i64, scale: u32) -> Decimal {
if scale > MAX_PRECISION {
panic!(
"Scale exceeds the maximum precision allowed: {} > {}",
scale,
MAX_PRECISION
);
}
let flags: u32 = scale << SCALE_SHIFT;
if num < 0 {
return Decimal {
flags: flags | SIGN_MASK,
hi: 0,
lo: (num.abs() as u64 & U32_MASK) as u32,
mid: ((num.abs() as u64 >> 32) & U32_MASK) as u32,
};
}
Decimal {
flags: flags,
hi: 0,
lo: (num as u64 & U32_MASK) as u32,
mid: ((num as u64 >> 32) & U32_MASK) as u32,
}
}
/// Returns a `Decimal` using the instances constituent parts.
///
/// # Arguments
///
/// * `lo` - The low 32 bits of a 96-bit integer.
/// * `mid` - The middle 32 bits of a 96-bit integer.
/// * `hi` - The high 32 bits of a 96-bit integer.
/// * `negative` - `true` to indicate a negative number.
/// * `scale` - A power of 10 ranging from 0 to 28.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let pi = Decimal::from_parts(1102470952, 185874565, 1703060790, false, 28);
/// assert_eq!(pi.to_string(), "3.1415926535897932384626433832");
/// ```
pub fn from_parts(lo: u32, mid: u32, hi: u32, negative: bool, scale: u32) -> Decimal {
Decimal {
lo: lo,
mid: mid,
hi: hi,
flags: flags(negative, scale),
}
}
/// Returns a `Result` which if successful contains the `Decimal` constitution of
/// the scientific notation provided by `value`.
///
/// # Arguments
///
/// * `value` - The scientific notation of the `Decimal`.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let value = Decimal::from_scientific("9.7e-7").unwrap();
/// assert_eq!(value.to_string(), "0.00000097");
/// ```
pub fn from_scientific(value: &str) -> Result<Decimal, Error> {
let err = Error::new("Failed to parse");
let mut split = value.splitn(2, 'e');
let base = split.next().ok_or(err.clone())?;
let mut scale = split.next().ok_or(err.clone())?.to_string();
let mut ret = Decimal::from_str(base)?;
if scale.contains('-') {
scale.remove(0);
let scale: u32 = scale.as_str().parse().map_err(move |_| err.clone())?;
let current_scale = ret.scale();
ret.set_scale(current_scale+ scale)?;
} else {
if scale.contains('+') {
scale.remove(0);
}
let pow: u32 = scale.as_str().parse().map_err(move |_| err.clone())?;
ret *= Decimal::from_i64(10_i64.pow(pow)).unwrap();
ret = ret.normalize();
}
Ok(ret)
}
/// Returns the scale of the decimal number, otherwise known as `e`.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let num = Decimal::new(1234, 3);
/// assert_eq!(num.scale(), 3u32);
/// ```
#[inline]
pub fn scale(&self) -> u32 {
((self.flags & SCALE_MASK) >> SCALE_SHIFT) as u32
}
/// An optimized method for changing the sign of a decimal number.
///
/// # Arguments
///
/// * `positive`: true if the resulting decimal should be positive.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let mut one = Decimal::new(1, 0);
/// one.set_sign(false);
/// assert_eq!(one.to_string(), "-1");
/// ```
pub fn set_sign(&mut self, positive: bool) {
if positive {
if self.is_sign_negative() {
self.flags ^= SIGN_MASK;
}
} else {
self.flags |= SIGN_MASK;
}
}
/// An optimized method for changing the scale of a decimal number.
///
/// # Arguments
///
/// * `scale`: the new scale of the number
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let mut one = Decimal::new(1, 0);
/// one.set_scale(5);
/// assert_eq!(one.to_string(), "0.00001");
/// ```
pub fn set_scale(&mut self, scale: u32) -> Result<(), Error> {
if scale > MAX_PRECISION {
return Err(Error::new("Scale exceeds maximum precision"));
}
self.flags = (scale << SCALE_SHIFT) | (self.flags & SIGN_MASK);
Ok(())
}
/// Returns a serialized version of the decimal number.
/// The resulting byte array will have the following representation:
///
/// * Bytes 1-4: flags
/// * Bytes 5-8: lo portion of `m`
/// * Bytes 9-12: mid portion of `m`
/// * Bytes 13-16: high portion of `m`
pub fn serialize(&self) -> [u8; 16] {
[
(self.flags & U8_MASK) as u8,
((self.flags >> 8) & U8_MASK) as u8,
((self.flags >> 16) & U8_MASK) as u8,
((self.flags >> 24) & U8_MASK) as u8,
(self.lo & U8_MASK) as u8,
((self.lo >> 8) & U8_MASK) as u8,
((self.lo >> 16) & U8_MASK) as u8,
((self.lo >> 24) & U8_MASK) as u8,
(self.mid & U8_MASK) as u8,
((self.mid >> 8) & U8_MASK) as u8,
((self.mid >> 16) & U8_MASK) as u8,
((self.mid >> 24) & U8_MASK) as u8,
(self.hi & U8_MASK) as u8,
((self.hi >> 8) & U8_MASK) as u8,
((self.hi >> 16) & U8_MASK) as u8,
((self.hi >> 24) & U8_MASK) as u8,
]
}
/// Deserializes the given bytes into a decimal number.
/// The deserialized byte representation must be 16 bytes and adhere to the followign convention:
///
/// * Bytes 1-4: flags
/// * Bytes 5-8: lo portion of `m`
/// * Bytes 9-12: mid portion of `m`
/// * Bytes 13-16: high portion of `m`
pub fn deserialize(bytes: [u8; 16]) -> Decimal {
Decimal {
flags: u32::from(bytes[0]) | u32::from(bytes[1]) << 8 | u32::from(bytes[2]) << 16 |
u32::from(bytes[3]) << 24,
lo: u32::from(bytes[4]) | u32::from(bytes[5]) << 8 | u32::from(bytes[6]) << 16 | u32::from(bytes[7]) << 24,
mid: u32::from(bytes[8]) | u32::from(bytes[9]) << 8 | u32::from(bytes[10]) << 16 |
u32::from(bytes[11]) << 24,
hi: u32::from(bytes[12]) | u32::from(bytes[13]) << 8 | u32::from(bytes[14]) << 16 |
u32::from(bytes[15]) << 24,
}
}
/// Returns `true` if the decimal is negative.
#[deprecated(since = "0.6.3", note = "please use `is_sign_negative` instead")]
pub fn is_negative(&self) -> bool {
self.is_sign_negative()
}
/// Returns `true` if the decimal is positive.
#[deprecated(since = "0.6.3", note = "please use `is_sign_positive` instead")]
pub fn is_positive(&self) -> bool {
self.is_sign_positive()
}
/// Returns `true` if the decimal is negative.
pub fn is_sign_negative(&self) -> bool {
self.flags & SIGN_MASK > 0
}
/// Returns `true` if the decimal is positive.
pub fn is_sign_positive(&self) -> bool {
self.flags & SIGN_MASK == 0
}
/// Returns the minimum possible number that `Decimal` can represent.
pub fn min_value() -> Decimal {
*MIN
}
/// Returns the maximum possible number that `Decimal` can represent.
pub fn max_value() -> Decimal {
*MAX
}
/// Returns a new `Decimal` integral with no fractional portion.
/// This is a true truncation whereby no rounding is performed.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let pi = Decimal::new(3141, 3);
/// let trunc = Decimal::new(3, 0);
/// // note that it returns a decimal
/// assert_eq!(pi.trunc(), trunc);
/// ```
pub fn trunc(&self) -> Decimal {
let mut scale = self.scale();
if scale == 0 {
// Nothing to do
return *self;
}
let mut working = [self.lo, self.mid, self.hi];
while scale > 0 {
// We're removing precision, so we don't care about overflow
if scale < 10 {
div_by_u32(&mut working, POWERS_10[scale as usize]);
break;
} else {
div_by_u32(&mut working, POWERS_10[9]);
// Only 9 as this array starts with 1
scale -= 9;
}
}
Decimal {
lo: working[0],
mid: working[1],
hi: working[2],
flags: flags(self.is_sign_negative(), 0),
}
}
/// Returns a new `Decimal` representing the fractional portion of the number.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let pi = Decimal::new(3141, 3);
/// let fract = Decimal::new(141, 3);
/// // note that it returns a decimal
/// assert_eq!(pi.fract(), fract);
/// ```
pub fn fract(&self) -> Decimal {
// This is essentially the original number minus the integral.
// Could possibly be optimized in the future
*self - self.trunc()
}
/// Computes the absolute value of `self`.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let num = Decimal::new(-3141, 3);
/// assert_eq!(num.abs().to_string(), "3.141");
/// ```
pub fn abs(&self) -> Decimal {
let mut me = *self;
me.set_sign(true);
me
}
/// Returns the largest integer less than or equal to a number.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let num = Decimal::new(3641, 3);
/// assert_eq!(num.floor().to_string(), "3");
/// ```
pub fn floor(&self) -> Decimal {
// Opportunity for optimization here
self.trunc()
}
/// Returns the smallest integer greater than or equal to a number.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let num = Decimal::new(3141, 3);
/// assert_eq!(num.ceil().to_string(), "4");
/// let num = Decimal::new(3, 0);
/// assert_eq!(num.ceil().to_string(), "3");
/// ```
pub fn ceil(&self) -> Decimal {
// Opportunity for optimization here
if self.fract().is_zero() {
*self
} else {
self.trunc() + Decimal::one()
}
}
/// Strips any trailing zero's from a `Decimal`.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// let number = Decimal::new(3100, 3);
/// // note that it returns a decimal, without the extra scale
/// assert_eq!(number.normalize().to_string(), "3.1");
/// ```
pub fn normalize(&self) -> Decimal {
let mut scale = self.scale();
if scale == 0 {
// Nothing to do
return *self;
}
let mut result = [self.lo, self.mid, self.hi];
let mut working = [self.lo, self.mid, self.hi];
while scale > 0 {
if div_by_u32(&mut working, 10) > 0 {
break;
}
scale -= 1;
result.copy_from_slice(&working);
}
Decimal {
lo: result[0],
mid: result[1],
hi: result[2],
flags: flags(self.is_sign_negative(), scale),
}
}
/// Returns a new `Decimal` number with no fractional portion (i.e. an integer).
/// Rounding currently follows "Bankers Rounding" rules. e.g. 6.5 -> 6, 7.5 -> 8
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
///
/// // Demonstrating bankers rounding...
/// let number_down = Decimal::new(65, 1);
/// let number_up = Decimal::new(75, 1);
/// assert_eq!(number_down.round().to_string(), "6");
/// assert_eq!(number_up.round().to_string(), "8");
/// ```
pub fn round(&self) -> Decimal {
self.round_dp(0)
}
/// Returns a new `Decimal` number with the specified number of decimal points for fractional portion.
/// Rounding currently follows "Bankers Rounding" rules. e.g. 6.5 -> 6, 7.5 -> 8
///
/// # Arguments
/// * `dp`: the number of decimal points to round to.
///
/// # Example
///
/// ```
/// use rust_decimal::Decimal;
/// use std::str::FromStr;
///
/// let pi = Decimal::from_str("3.1415926535897932384626433832").unwrap();
/// assert_eq!(pi.round_dp(2).to_string(), "3.14");
/// ```
pub fn round_dp(&self, dp: u32) -> Decimal {
let old_scale = self.scale();
if dp < old_scale {
// Short circuit for zero
if self.is_zero() {
return Decimal {
lo: 0,
mid: 0,
hi: 0,
flags: flags(self.is_sign_negative(), dp),
};
}
let mut value = [self.lo, self.mid, self.hi];
let mut value_scale = self.scale();
let negative = self.is_sign_negative();
value_scale -= dp;
// Rescale to zero so it's easier to work with
while value_scale > 0 {
if value_scale < 10 {
div_by_u32(&mut value, POWERS_10[value_scale as usize]);
value_scale = 0;
} else {
div_by_u32(&mut value, POWERS_10[9]);
value_scale -= 9;
}
}
// Do some midpoint rounding checks
// We're actually doing two things here.
// 1. Figuring out midpoint rounding when we're right on the boundary. e.g. 2.50000
// 2. Figuring out whether to add one or not e.g. 2.51
// For this, we need to figure out the fractional portion that is additional to
// the rounded number. e.g. for 0.12345 rounding to 2dp we'd want 345.
// We're doing the equivalent of losing precision (e.g. to get 0.12)
// then increasing the precision back up to 0.12000
let mut offset = [self.lo, self.mid, self.hi];
let mut diff = old_scale - dp;
while diff > 0 {
if diff < 10 {
div_by_u32(&mut offset, POWERS_10[diff as usize]);
break;
} else {
div_by_u32(&mut offset, POWERS_10[9]);
// Only 9 as this array starts with 1
diff -= 9;
}
}
let mut diff = old_scale - dp;
while diff > 0 {
if diff < 10 {
mul_by_u32(&mut offset, POWERS_10[diff as usize]);
break;
} else {
mul_by_u32(&mut offset, POWERS_10[9]);
// Only 9 as this array starts with 1
diff -= 9;
}
}
let mut decimal_portion = [self.lo, self.mid, self.hi];
sub_internal(&mut decimal_portion, &offset);
// If the decimal_portion is zero then we round based on the other data
let mut cap = [5, 0, 0];
for _ in 0..(old_scale - dp - 1) {
mul_by_u32(&mut cap, 10);
}
let order = cmp_internal(&decimal_portion, &cap);
match order {
Ordering::Equal => {
if (value[0] & 1) == 1 {
add_internal(&mut value, &ONE_INTERNAL_REPR);
}
}
Ordering::Greater => {
// Doesn't matter about the decimal portion
add_internal(&mut value, &ONE_INTERNAL_REPR);
}
_ => {}
}
Decimal {
lo: value[0],
mid: value[1],
hi: value[2],
flags: flags(negative, dp),
}
} else {
*self
}
}
fn base2_to_decimal(bits: &mut [u32; 3], exponent2: i32, positive: bool, is64: bool) -> Option<Self> {
// 2^exponent2 = (10^exponent2)/(5^exponent2)
// = (5^-exponent2)*(10^exponent2)
let mut exponent5 = -exponent2;
let mut exponent10 = exponent2; // Ultimately, we want this for the scale
while exponent5 > 0 {
// Check to see if the mantissa is divisible by 2
if bits[0] & 0x1 == 0 {
exponent10 += 1;
exponent5 -= 1;
// We can divide by 2 without losing precision
let hi_carry = bits[2] & 0x1 == 1;
bits[2] >>= 1;
let mid_carry = bits[1] & 0x1 == 1;
bits[1] = (bits[1] >> 1) | if hi_carry { SIGN_MASK } else { 0 };
bits[0] = (bits[0] >> 1) | if mid_carry { SIGN_MASK } else { 0 };
} else {
// The mantissa is NOT divisible by 2. Therefore the mantissa should
// be multiplied by 5, unless the multiplication overflows.
exponent5 -= 1;
let mut temp = [bits[0], bits[1], bits[2]];
if mul_by_u32(&mut temp, 5) == 0 {
// Multiplication succeeded without overflow, so copy result back
bits[0] = temp[0];
bits[1] = temp[1];
bits[2] = temp[2];
} else {
// Multiplication by 5 overflows. The mantissa should be divided
// by 2, and therefore will lose significant digits.
exponent10 += 1;
// Shift right
let hi_carry = bits[2] & 0x1 == 1;
bits[2] >>= 1;
let mid_carry = bits[1] & 0x1 == 1;
bits[1] = (bits[1] >> 1) | if hi_carry { SIGN_MASK } else { 0 };
bits[0] = (bits[0] >> 1) | if mid_carry { SIGN_MASK } else { 0 };
}
}
}
// In order to divide the value by 5, it is best to multiply by 2/10.
// Therefore, exponent10 is decremented, and the mantissa should be multiplied by 2
while exponent5 < 0 {
if bits[2] & SIGN_MASK == 0 {
// No far left bit, the mantissa can withstand a shift-left without overflowing
exponent10 -= 1;
exponent5 += 1;
shl_internal(bits, 1, 0);
} else {
// The mantissa would overflow if shifted. Therefore it should be
// directly divided by 5. This will lose significant digits, unless
// by chance the mantissa happens to be divisible by 5.
exponent5 += 1;
div_by_u32(bits, 5);
}
}
// At this point, the mantissa has assimilated the exponent5, but
// exponent10 might not be suitable for assignment. exponent10 must be
// in the range [-MAX_PRECISION..0], so the mantissa must be scaled up or
// down appropriately.
while exponent10 > 0 {
// In order to bring exponent10 down to 0, the mantissa should be
// multiplied by 10 to compensate. If the exponent10 is too big, this
// will cause the mantissa to overflow.
if mul_by_u32(bits, 10) == 0 {
exponent10 -= 1;
} else {
// Overflowed - return?
return None;
}
}
// In order to bring exponent up to -MAX_PRECISION, the mantissa should
// be divided by 10 to compensate. If the exponent10 is too small, this
// will cause the mantissa to underflow and become 0.
while exponent10 < -(MAX_PRECISION as i32) {
let rem10 = div_by_u32(bits, 10);
exponent10 += 1;
if is_all_zero(bits) {
// Underflow, unable to keep dividing
exponent10 = 0;
} else if rem10 >= 5 {
add_internal(bits, &ONE_INTERNAL_REPR);
}
}
// This step is required in order to remove excess bits of precision from the
// end of the bit representation, down to the precision guaranteed by the
// floating point number
if is64 {
// Guaranteed to about 16 dp
while exponent10 < 0 && (bits[2] != 0 || (bits[1] & 0xFFE0_0000) != 0) {
let rem10 = div_by_u32(bits, 10);
exponent10 += 1;
if rem10 >= 5 {
add_internal(bits, &ONE_INTERNAL_REPR);
}
}
} else {
// Guaranteed to about 7 dp
while exponent10 < 0 &&
(bits[2] != 0 || bits[1] != 0 || (bits[2] == 0 && bits[1] == 0 && (bits[0] & 0xFF00_0000) != 0))
{
let rem10 = div_by_u32(bits, 10);
exponent10 += 1;
if rem10 >= 5 {
add_internal(bits, &ONE_INTERNAL_REPR);
}
}
}
// Remove multiples of 10 from the representation
while exponent10 < 0 {
let mut temp = [bits[0], bits[1], bits[2]];
let remainder = div_by_u32(&mut temp, 10);
if remainder == 0 {
exponent10 += 1;
bits[0] = temp[0];
bits[1] = temp[1];
bits[2] = temp[2];
} else {
break;
}
}
Some(Decimal {
lo: bits[0],
mid: bits[1],
hi: bits[2],
flags: flags(!positive, -exponent10 as u32),
})
}
}
#[inline]
fn flags(neg: bool, scale: u32) -> u32 {
(scale << SCALE_SHIFT) | if neg { SIGN_MASK } else { 0 }
}
/// Rescales the given decimals to equivalent scales.
/// It will firstly try to scale both the left and the right side to
/// the maximum scale of left/right. If it is unable to do that it
/// will try to reduce the accuracy of the other argument.
/// e.g. with 1.23 and 2.345 it'll rescale the first arg to 1.230
fn rescale(left: &mut [u32; 3], left_scale: &mut u32, right: &mut [u32; 3], right_scale: &mut u32) {
if left_scale == right_scale {
// Nothing to do
return;
}
enum Target {
Left,
Right,
}
let target; // The target which we're aiming for
let mut diff;
let my;
let other;
if left_scale > right_scale {
diff = *left_scale - *right_scale;
my = right;
other = left;
target = Target::Left;
} else {
diff = *right_scale - *left_scale;
my = left;
other = right;
target = Target::Right;
};
let mut working = [my[0], my[1], my[2]];
while diff > 0 && mul_by_10(&mut working) == 0 {
my.copy_from_slice(&working);
diff -= 1;
}
if diff == 0 {
// We're done - same scale
match target {
Target::Left => *right_scale = *left_scale,
Target::Right => *left_scale = *right_scale,
}
return;
}
// Scaling further isn't possible since we got an overflow
// In this case we need to reduce the accuracy of the "side to keep"
// First, set the scales
match target {
Target::Left => {
*right_scale = *left_scale;
}
Target::Right => {
*left_scale = *right_scale;
}
}
// Now do the necessary rounding
let mut remainder = 0;
while diff > 0 && !is_all_zero(other) {
diff -= 1;
*left_scale -= 1;
*right_scale -= 1;
// Any remainder is discarded if diff > 0 still (i.e. lost precision)
remainder = div_by_u32(other, 10);
}
if remainder >= 5 {
for part in other.iter_mut() {
let digit = u64::from(*part) + 1u64;
remainder = if digit > 0xFFFF_FFFF { 1 } else { 0 };
*part = (digit & 0xFFFF_FFFF) as u32;
if remainder == 0 {
break;
}
}
}
}
// This method should only be used where copy from slice cannot be
#[inline]
fn copy_array_diff_lengths(into: &mut [u32], from: &[u32]) {
for i in 0..into.len() {
if i >= from.len() {
break;
}
into[i] = from[i];
}
}
#[inline]
fn u64_to_array(value: u64) -> [u32;2] {
[
(value & U32_MASK) as u32,
(value >> 32 & U32_MASK) as u32,
]
}
fn add_internal(value: &mut [u32], by: &[u32]) -> u32 {
let mut carry: u64 = 0;
let vl = value.len();
let bl = by.len();
if vl >= bl {
let mut sum: u64;
for i in 0..bl {
sum = u64::from(value[i]) + u64::from(by[i]) + carry;
value[i] = (sum & U32_MASK) as u32;
carry = sum >> 32;
}
if vl > bl && carry > 0 {
for i in value.iter_mut().skip(bl) {
sum = u64::from(*i) + carry;
*i = (sum & U32_MASK) as u32;
carry = sum >> 32;
if carry == 0 {
break;
}
}
}
} else if vl + 1 == bl {
// Overflow, by default, is anything in the high portion of by
let mut sum: u64;
for i in 0..vl {
sum = u64::from(value[i]) + u64::from(by[i]) + carry;
value[i] = (sum & U32_MASK) as u32;
carry = sum >> 32;
}
if by[vl] > 0 {
carry += u64::from(by[vl]);
}
} else {
panic!("Internal error: add using incompatible length arrays. {} <- {}", vl, bl);
}
carry as u32
}
#[inline]
fn add3_internal(value: &mut [u32; 3], by: &[u32; 3]) -> u32 {
let mut carry: u32 = 0;
let bl = by.len();
for i in 0..bl {
let res1 = value[i].overflowing_add(by[i]);
let res2 = res1.0.overflowing_add(carry);
value[i] = res2.0;
carry = (res1.1 | res2.1) as u32;
}
carry
}
fn add_with_scale_internal(
quotient: &mut [u32; 3],
quotient_scale: &mut i32,
working_quotient: &mut [u32; 4],
working_scale: &mut i32,
) -> bool {
// Add quotient and the working (i.e. quotient = quotient + working)
if is_all_zero(quotient) {
// Quotient is zero so we can just copy the working quotient in directly
// First, make sure they are both 96 bit.
while working_quotient[3] != 0 {
div_by_u32(working_quotient, 10);
*working_scale -= 1;
}
copy_array_diff_lengths(quotient, working_quotient);
*quotient_scale = *working_scale;
return false;
}
if is_all_zero(working_quotient) {
return false;
}
// We have ensured that our working is not zero so we should do the addition
// If our two quotients are different then
// try to scale down the one with the bigger scale
let mut temp3 = [0u32, 0u32, 0u32];
let mut temp4 = [0u32, 0u32, 0u32, 0u32];
if *quotient_scale != *working_scale {
// TODO: Remove necessity for temp (without performance impact)
fn div_by_10(target: &mut [u32], temp: &mut [u32], scale: &mut i32, target_scale: i32) {
// Copy to the temp array
temp.copy_from_slice(target);
// divide by 10 until target scale is reached
while *scale > target_scale {
let remainder = div_by_u32(temp, 10);
if remainder == 0 {
*scale -= 1;
target.copy_from_slice(&temp);
} else {
break;
}
}
}
if *quotient_scale < *working_scale {
div_by_10(working_quotient, &mut temp4, working_scale, *quotient_scale);
} else {
div_by_10(quotient, &mut temp3, quotient_scale, *working_scale);
}
}
// If our two quotients are still different then
// try to scale up the smaller scale
if *quotient_scale != *working_scale {
// TODO: Remove necessity for temp (without performance impact)
fn mul_by_10(target: &mut [u32], temp: &mut [u32], scale: &mut i32, target_scale: i32) {
temp.copy_from_slice(target);
let mut overflow = 0;
// Multiply by 10 until target scale reached or overflow
while *scale < target_scale && overflow == 0 {
overflow = mul_by_u32(temp, 10);
if overflow == 0 {
// Still no overflow
*scale += 1;
target.copy_from_slice(&temp);
}
}
}
if *quotient_scale > *working_scale {
mul_by_10(working_quotient, &mut temp4, working_scale, *quotient_scale);
} else {
mul_by_10(quotient, &mut temp3, quotient_scale, *working_scale);
}
}
// If our two quotients are still different then
// try to scale down the one with the bigger scale
// (ultimately losing significant digits)
if *quotient_scale != *working_scale {
// TODO: Remove necessity for temp (without performance impact)
fn div_by_10_lossy(target: &mut [u32], temp: &mut [u32], scale: &mut i32, target_scale: i32) {
temp.copy_from_slice(target);
// divide by 10 until target scale is reached
while *scale > target_scale {