rust_decimal 0.2.0

A Decimal Implementation written in pure Rust suitable for financial calculations.
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
extern crate num;
extern crate serde;
extern crate serde_json;
#[macro_use] extern crate lazy_static;

#[macro_use]
#[cfg(feature = "postgres")]
extern crate postgres as pg_crate;
#[cfg(feature = "postgres")]
mod postgres;
mod serde_types;

use std::ops::{Add, Div, Mul, Rem, Sub};
use std::str::FromStr;
use std::iter::repeat;
use std::cmp::*;
use std::cmp::Ordering::Equal;

use num::{BigInt, BigUint, FromPrimitive, Integer, One, ToPrimitive, Zero};
use num::bigint::Sign::{Minus, Plus};

// 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.
#[allow(overflowing_literals)]
const SIGN_MASK: i32 = 0x80000000;

// 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: i32 = 0x00FF0000;
const U8_MASK: i32 = 0x000000FF;
const I32_MASK: i64 = 0xFFFFFFFF;

// Number of bits scale is shifted by.
const SCALE_SHIFT: i32 = 16;

// The maximum supported precision
const MAX_PRECISION: u32 = 28;
const MAX_BYTES: usize = 12;
const MAX_BITS: usize = 96;

lazy_static! {
    static ref MIN: Decimal = Decimal { flags: -2147483648, lo: -1, mid: -1, hi: -1 };
    static ref MAX: Decimal = Decimal { flags: 0, lo: -1, mid: -1, hi: -1 };
}

// Fast access for 10^n where n is 0-9
static POWERS_10: &'static [u32; 10] = &[1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000];
// Fast access for 10^n where n is 10-19
static BIG_POWERS_10: &'static [u64; 10] = &[10000000000,
                                             100000000000,
                                             1000000000000,
                                             10000000000000,
                                             100000000000000,
                                             1000000000000000,
                                             10000000000000000,
                                             100000000000000000,
                                             1000000000000000000,
                                             10000000000000000000];

/// 128 bit representation of a decimal
/// The finite set of values of type Decimal are of the form m / 10^e,
/// where m is an integer such that -2^96 <; m <; 2^96, and e is an integer
/// between 0 and 28 inclusive.
#[derive(Clone, Debug, Copy)]
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: i32,
    // The lo, mid, hi, and flags fields contain the representation of the
    // Decimal value as a 96-bit integer.
    hi: i32,
    lo: i32,
    mid: i32
}

#[allow(dead_code)]
impl Decimal {

    pub fn new(num: i64, scale: u32) -> Decimal {
        if scale > MAX_PRECISION {
            panic!("Scale exceeds the maximum precision allowed");
        }
        let flags: i32 = (scale as i32) << SCALE_SHIFT;
        if num < 0 {
            return Decimal {
                flags: flags & SIGN_MASK,
                hi: 0,
                lo: (num & I32_MASK) as i32,
                mid: ((num.abs() >> 32) & I32_MASK) as i32
            };
        }
        Decimal {
            flags: flags,
            hi: 0,
            lo: (num & I32_MASK) as i32,
            mid: ((num >> 32) & I32_MASK) as i32
        }
    }

    pub fn scale(&self) -> u32 {
        ((self.flags & SCALE_MASK) >> SCALE_SHIFT) as u32
    }

    pub fn set_sign(&mut self, positive: bool) {
        if positive {
            if self.is_negative() {
                self.flags ^= SIGN_MASK;
            }
        } else {
            self.flags |= SIGN_MASK;
        }
    }

    pub fn unsigned_bytes_le(&self) -> Vec<u8> {
        return vec![(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];
    }

    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]
    }

    pub fn deserialize(bytes: [u8; 16]) -> Decimal {
        Decimal {
            flags: (bytes[0] as i32) | (bytes[1] as i32) << 8 | (bytes[2] as i32) << 16 | (bytes[3] as i32) << 24,
            lo: (bytes[4] as i32) | (bytes[5] as i32) << 8 | (bytes[6] as i32) << 16 | (bytes[7] as i32) << 24,
            mid: (bytes[8] as i32) | (bytes[9] as i32) << 8 | (bytes[10] as i32) << 16 | (bytes[11] as i32) << 24,
            hi: (bytes[12] as i32) | (bytes[13] as i32) << 8 | (bytes[14] as i32) << 16 | (bytes[15] as i32) << 24
        }
    }

    pub fn is_negative(&self) -> bool {
        self.flags < 0
    }

    pub fn is_positive(&self) -> bool {
        self.flags >= 0
    }

    pub fn min_value() -> Decimal {
        *MIN
    }

    pub fn max_value() -> Decimal {
        *MAX
    }

    pub fn round(&self) -> Decimal {
        self.round_dp(0)
    }

    // We use bankers rounding! i.e. 6.5 -> 6, 7.5 -> 8
    pub fn round_dp(&self, dp: u32) -> Decimal {

        let old_scale = self.scale();

        if dp < old_scale && dp < 20 { // Technically, it's 28...
            // Short circuit for zero
            if self.is_zero() {
                return self.rescale(dp);
            }

            // Check to see if we need to add or subtract one.
            // Some expected results assuming dp = 2 and old_scale = 3:
            //   1.235  = 1.24
            //   1.2361 = 1.24
            //   1.2250 = 1.22
            //   1.2251 = 1.23
            // If we consider this example, we have the following number in `low`:
            //   1235 (scale 3)
            //   12361
            //   12250
            //   12251
            let index = dp as usize;
            let power10 = if dp < 10 {
                Decimal::from_u32(POWERS_10[index]).unwrap()
            } else {
                Decimal::from_u64(BIG_POWERS_10[index - 10]).unwrap()
            };
            //println!("{} * {}", self.to_string(), power10.to_string());
            let mut value = self.mul(power10);

            // 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
            // We only need to search back a certain number. e.g. 2.500, round(2) search 1.
            let raw = self.to_biguint();

            // Get the decimal portion
            //  e.g. 2.5001, round(2) decimal portion = 01
            let offset = self.rescale(dp).rescale(old_scale).to_biguint();
            //println!("Raw: {}, Offset: {}", raw.to_string(), offset.to_string());
            let decimal_portion = raw - offset;

            // Rescale to zero so it's easier to work with
            value = value.rescale(0u32);

            // If the decimal_portion is zero then we round based on the other data
            let mut cap = BigUint::from_u32(5u32).unwrap();
            for _ in 0..(old_scale - dp - 1) {
                cap = cap.mul(BigUint::from_u32(10u32).unwrap());
            }
            //println!("Cap {} Decimal Portion {}", cap, decimal_portion);
            if decimal_portion == cap {
                let even_or_odd = value.rem(Decimal::from_u32(2u32).unwrap());
                if !even_or_odd.is_zero() {
                    value = value.add(Decimal::one());
                }
            } else if decimal_portion > cap {
                // Doesn't matter about the decimal portion
                if self.is_negative() {
                    value = value.sub(Decimal::one());
                } else {
                    //println!("Decimal is greater than cap {} > {}", decimal_portion, cap);
                    value = value.add(Decimal::one());
                }
            }

            // Divide by the power to get back
            value.div(power10)
        } else {
            *self
        }
    }

    fn rescale(&self, exp: u32) -> Decimal {
        if exp > MAX_PRECISION {
            panic!("Cannot have an exponent greater than {}", MAX_PRECISION);
        }
        let diff = exp as i32 - self.scale() as i32;
        if diff == 0 {
            // Since it's a copy type we can just return the self
            return *self;
        }

        // 1.23 is scale 2. If we're making it 1.2300 scale 4
        // Raw bit manipulation is hard (going up is easy, going down is hard)
        // Let's just use BigUint to help out
        let unsigned = self.to_biguint();
        let result: BigUint;

        // Figure out whether to multiply or divide
        let index = diff.abs() as usize;
        if diff > 0 {
            if index < 10 {
                result = unsigned * BigUint::from_u32(POWERS_10[index]).unwrap();
            } else if index < 20 {
                result = unsigned * BigUint::from_u64(BIG_POWERS_10[index - 10]).unwrap();
            } else {
                let u32_index = index - 19; // -20 + 1 for getting the right u32 index
                let exponent = BigUint::from_u64(BIG_POWERS_10[9]).unwrap() *
                               BigUint::from_u32(POWERS_10[u32_index]).unwrap();
                result = unsigned * exponent;
            }
        } else {
            if index < 10 {
                result = unsigned / BigUint::from_u32(POWERS_10[index]).unwrap();
            } else if index < 20 {
                result = unsigned / BigUint::from_u64(BIG_POWERS_10[index - 10]).unwrap();
            } else {
                let u32_index = index - 19; // -20 + 1 for getting the right u32 index
                let exponent = BigUint::from_u64(BIG_POWERS_10[9]).unwrap() *
                               BigUint::from_u32(POWERS_10[u32_index]).unwrap();
                result = unsigned / exponent;
            }
        }

        // Convert it back
        let bytes = result.to_bytes_le();
        Decimal::from_bytes_le(bytes, exp, self.is_negative())
    }

    //
    // These do not address scale. If you want that, rescale to 0 first.
    //
    fn to_biguint(&self) -> BigUint {
        let bytes = self.unsigned_bytes_le();
        BigUint::from_bytes_le(&bytes[..])
    }

    fn to_bigint(&self) -> BigInt {
        let bytes = self.unsigned_bytes_le();
        let sign = if self.is_negative() {
                       Minus
                   } else {
                       Plus
                   };
        BigInt::from_bytes_le(sign, &bytes[..])
    }

    fn from_biguint(res: BigUint, scale: u32, negative: bool) -> Result<Decimal, &'static str> {
        let bytes = res.to_bytes_le();
        if bytes.len() > MAX_BYTES {
            return Err("Decimal Overflow");
        }
        if scale > MAX_PRECISION {
            return Err("Scale exceeds maximum precision");
        }

        Ok(Decimal::from_bytes_le(bytes, scale, negative))
    }

    fn from_bytes_le(bytes: Vec<u8>, scale: u32, negative: bool) -> Decimal {
        // Finally build the flags
        let mut flags = 0i32;
        let mut lo = 0i32;
        let mut mid = 0i32;
        let mut hi = 0i32;

        if scale > 0 {
            flags = (scale as i32) << SCALE_SHIFT;
        }
        if negative {
            flags |= SIGN_MASK;
        }
        if bytes.len() > MAX_BYTES {
            panic!("Decimal Overflow");
        }

        let mut pos = 0;
        for b in bytes {
            if pos < 4 {
                lo |= (b as i32) << (pos * 8);
            } else if pos < 8 {
                mid |= (b as i32) << ((pos - 4) * 8);
            } else {
                hi |= (b as i32) << ((pos - 8) * 8);
            }
            // Move position
            pos += 1;
        }

        // Build up each hi/lo
        Decimal {
            flags: flags,
            hi: hi,
            lo: lo,
            mid: mid
        }
    }
}

pub trait ToDecimal {
    /// Converts the value of `self` to a `Decimal`.
    fn to_decimal(&self) -> Option<Decimal>;
}

macro_rules! impl_to_decimal {
    ($T:ty, $from_ty:path) => {
        impl ToDecimal for $T {
            #[inline]
            fn to_decimal(&self) -> Option<Decimal> {
                $from_ty(*self)
            }
        }
    }
}

impl_to_decimal!(isize, FromPrimitive::from_isize);
impl_to_decimal!(i8,    FromPrimitive::from_i8);
impl_to_decimal!(i16,   FromPrimitive::from_i16);
impl_to_decimal!(i32,   FromPrimitive::from_i32);
impl_to_decimal!(i64,   FromPrimitive::from_i64);
impl_to_decimal!(usize, FromPrimitive::from_usize);
impl_to_decimal!(u8,    FromPrimitive::from_u8);
impl_to_decimal!(u16,   FromPrimitive::from_u16);
impl_to_decimal!(u32,   FromPrimitive::from_u32);
impl_to_decimal!(u64,   FromPrimitive::from_u64);

macro_rules! forward_val_val_binop {
    (impl $imp:ident for $res:ty, $method:ident) => {
        impl $imp<$res> for $res {
            type Output = $res;

            #[inline]
            fn $method(self, other: $res) -> $res {
                (&self).$method(&other)
            }
        }
    }
}

macro_rules! forward_ref_val_binop {
    (impl $imp:ident for $res:ty, $method:ident) => {
        impl<'a> $imp<$res> for &'a $res {
            type Output = $res;

            #[inline]
            fn $method(self, other: $res) -> $res {
                self.$method(&other)
            }
        }
    }
}

macro_rules! forward_val_ref_binop {
    (impl $imp:ident for $res:ty, $method:ident) => {
        impl<'a> $imp<&'a $res> for $res {
            type Output = $res;

            #[inline]
            fn $method(self, other: &$res) -> $res {
                (&self).$method(other)
            }
        }
    }
}

macro_rules! forward_all_binop {
    (impl $imp:ident for $res:ty, $method:ident) => {
        forward_val_val_binop!(impl $imp for $res, $method);
        forward_ref_val_binop!(impl $imp for $res, $method);
        forward_val_ref_binop!(impl $imp for $res, $method);
    };
}

impl Zero for Decimal {

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

    fn zero() -> Decimal {
        Decimal {
            flags: 0,
            hi: 0,
            lo: 0,
            mid: 0
        }
    }

}

impl One for Decimal {
    fn one() -> Decimal {
        Decimal {
            flags: 0,
            hi: 0,
            lo: 1,
            mid: 0
        }
    }
}

impl FromStr for Decimal {

    type Err = &'static str;

    fn from_str(value: &str) -> Result<Decimal, &'static str> {

        let mut offset = 0;
        let mut len = value.len();
        let chars: Vec<char> = value.chars().collect();
        let mut negative = false; // assume positive

        // handle the sign
        if chars[offset] == '-' {
            negative = true; // leading minus means negative
            offset += 1;
            len -= 1;
        } else if chars[offset] == '+' {
            // leading + allowed
            offset += 1;
            len -= 1;
        }

        // should now be at numeric part of the significand
        let mut dot_offset: i32 = -1;  // '.' offset, -1 if none
        let cfirst = offset;  // record start of integer
        let mut coeff = String::new(); // integer significand array

        while len > 0 {
            let c = chars[offset];
            if c.is_digit(10) {
                coeff.push(c);
                offset += 1;
                len -= 1;
                continue;
            }
            if c == '.' {
                if dot_offset >= 0 {
                    return Err("Invalid decimal: two decimal points");
                }
                dot_offset = offset as i32;
                offset += 1;
                len -= 1;
                continue;
            }

            return Err("Invalid decimal: unknown character");
        }

        // here when no characters left
        if coeff.is_empty() {
            return Err("Invalid decimal: no digits found");
        }

        // println!("coeff.len() {}, dot_offset {} cfirst {} negative {}", coeff.len(), dot_offset, cfirst, negative);
        let mut scale = 0u32;
        if dot_offset >= 0 {
            // we had a decimal place so set the scale
            scale = (coeff.len() as u32) - (dot_offset as u32 - cfirst as u32);
        }

        // Parse this into a big uint
        let res = BigUint::from_str(&coeff[..]);
        if res.is_err() {
            return Err("Failed to parse string");
        }

        Decimal::from_biguint(res.unwrap(), scale, negative)
    }
}

impl ToString for Decimal {
    fn to_string(&self) -> String {

        // Get the scale - where we need to put the decimal point
        let scale = self.scale();

        // Get the whole number without decimal points (or signs)
        let uint = self.to_biguint();

        // Convert to a string and manipulate that (neg at front, inject decimal)
        let mut rep = uint.to_string();
        let len = rep.len();

        // Inject the decimal point
        if scale > 0 {

            // Must be a low fractional
            if scale > len as u32 {
                let mut new_rep = String::new();
                let zeros = repeat("0").take(scale as usize - len).collect::<String>();
                new_rep.push_str("0.");
                new_rep.push_str(&zeros[..]);
                new_rep.push_str(&rep[..]);
                rep = new_rep;
            } else if scale == len as u32 {
                rep.insert(0, '.');
                rep.insert(0, '0');
            } else {
                rep.insert(len - scale as usize, '.');
            }
        }

        // Last set the negation
        if self.is_negative() {
            rep.insert(0, '-');
        }

        rep
    }
}

impl FromPrimitive for Decimal {
    fn from_i32(n: i32) -> Option<Decimal> {
        let flags: i32;
        let value_copy: i32;
        if n >= 0 {
            flags = 0;
            value_copy = n;
        } else {
            flags = SIGN_MASK;
            value_copy = -n;
        }
        Some(Decimal {
            flags: flags,
            lo: value_copy,
            mid: 0,
            hi: 0
        })
    }

    fn from_i64(n: i64) -> Option<Decimal> {
        let flags: i32;
        let value_copy: i64;
        if n >= 0 {
            flags = 0;
            value_copy = n;
        } else {
            flags = SIGN_MASK;
            value_copy = -n;
        }
        Some(Decimal {
            flags: flags,
            lo: value_copy as i32,
            mid: (value_copy >> 32) as i32,
            hi: 0
        })
    }

    fn from_u32(n: u32) -> Option<Decimal> {
        Some(Decimal {
            flags: 0,
            lo: n as i32,
            mid: 0,
            hi: 0
        })
    }

    fn from_u64(n: u64) -> Option<Decimal> {
        Some(Decimal {
            flags: 0,
            lo: n as i32,
            mid: (n >> 32) as i32,
            hi: 0
        })
    }

}

impl ToPrimitive for Decimal {

    fn to_i64(&self) -> Option<i64> {
        let d = self.rescale(0);
        // Convert to biguint and use that
        let bytes = d.unsigned_bytes_le();
        let sign;
        if self.is_negative() {
            sign = Minus;
        } else {
            sign = Plus;
        }
        BigInt::from_bytes_le(sign, &bytes[..]).to_i64()
    }

    fn to_u64(&self) -> Option<u64> {
        if self.is_negative() {
            return None;
        }

        // Rescale to 0 (truncate)
        let d = self.rescale(0);
        if d.hi != 0 {
            // Overflow
            return None;
        }

        // Convert to biguint and use that
        let bytes = d.unsigned_bytes_le();
        BigUint::from_bytes_le(&bytes[..]).to_u64()
    }
}

fn scaled_biguints(me: &Decimal, other: &Decimal) -> (BigUint, BigUint, u32) {
    // Scale to the max
    let s_scale = me.scale();
    let o_scale = other.scale();

    if s_scale > o_scale {
        (me.to_biguint(),
         other.rescale(s_scale).to_biguint(),
         s_scale)
    } else if o_scale > s_scale {
        (me.rescale(o_scale).to_biguint(),
         other.to_biguint(),
         o_scale)
    } else {
        (me.to_biguint(), other.to_biguint(), s_scale)
    }
}

fn scaled_bigints(me: &Decimal, other: &Decimal) -> (BigInt, BigInt, u32) {
    // Scale to the max
    let s_scale = me.scale();
    let o_scale = other.scale();

    if s_scale > o_scale {
        (me.to_bigint(), other.rescale(s_scale).to_bigint(), s_scale)
    } else if o_scale > s_scale {
        (me.rescale(o_scale).to_bigint(), other.to_bigint(), o_scale)
    } else {
        (me.to_bigint(), other.to_bigint(), s_scale)
    }
}

forward_all_binop!(impl Add for Decimal, add);

impl<'a, 'b> Add<&'b Decimal> for &'a Decimal {
    type Output = Decimal;

    #[inline]
    fn add(self, other: &Decimal) -> Decimal {

        // Get big uints to work with
        let (left, right, scale) = scaled_biguints(self, other);

        // Now we have the big boys - do a quick add
        // println!("Left {} Right {}", left, right);
        let l_negative = self.is_negative();
        let r_negative = other.is_negative();
        let result;
        let is_negative;
        if l_negative && r_negative {
            result = left + right;
            is_negative = true;
        } else if !l_negative && !r_negative {
            result = left + right;
            is_negative = false;
        } else {
            //  1 + -2 (l < r, -r => r - l, -)
            //  2 + -1 (l > r, -r => l - r, +)
            // -1 +  2 (l < r, -l => r - l, +)
            // -2 +  1 (l > r, -l => l - r, -)
            if r_negative {
                if left < right {
                    result = right - left;
                    is_negative = true;
                } else if left > right {
                    result = left - right;
                    is_negative = false;
                } else {
                    result = BigUint::zero();
                    is_negative = false;
                }
            } else {
                // l_negative
                if left < right {
                    result = right - left;
                    is_negative = false;
                } else if left > right {
                    result = left - right;
                    is_negative = true;
                } else {
                    result = BigUint::zero();
                    is_negative = false;
                }
            }
        }

        // Convert it back
        let bytes = result.to_bytes_le();
        Decimal::from_bytes_le(bytes, scale, is_negative)
    }
}

forward_all_binop!(impl Sub for Decimal, sub);

impl<'a, 'b> Sub<&'b Decimal> for &'a Decimal {
    type Output = Decimal;

    #[inline]
    fn sub(self, other: &Decimal) -> Decimal {
        // Get big uints to work with
        let (left, right, scale) = scaled_biguints(self, other);

        // Now we have the big boys - do a quick subtraction
        // Both Positive:
        // 1 - 2 = -1
        // 2 - 1 = 1
        // Both negative:
        // -1 - -2 = 1
        // -2 - -1 = -1
        // Mismatch
        // -1 - 2 = -3
        // -2 - 1 = -3
        // 1 - -2 = 3
        // 2 - -1 = 3
        let l_negative = self.is_negative();
        let r_negative = other.is_negative();
        let result: BigUint;
        let is_negative: bool;
        if l_negative ^ r_negative {
            result = left + right;
            is_negative = l_negative;
        } else {
            if left > right {
                result = left - right;
                is_negative = l_negative && r_negative;
            } else {
                result = right - left;
                is_negative = !l_negative && !r_negative;
            }
        }

        // Convert it back
        let bytes = result.to_bytes_le();
        Decimal::from_bytes_le(bytes, scale, is_negative && !result.is_zero())
    }
}

forward_all_binop!(impl Mul for Decimal, mul);

impl<'a, 'b> Mul<&'b Decimal> for &'a Decimal {
    type Output = Decimal;

    #[inline]
    fn mul(self, other: &Decimal) -> Decimal {
        // Get big uints to work with
        let left = self.to_biguint();
        let right = other.to_biguint();

        // Easy!
        let mut result = left * right; // Has the potential to overflow below if > 2^96
        let mut scale = self.scale() + other.scale();
        //println!("Result: {}, Scale: {}", result, scale);
        //println!("Self Scale: {}, Other Scale: {}", self.scale(), other.scale());

        // The result may be an overflow of what we can comfortably represent in 96 bits
        // We can only do this if we have a scale to work with
        if result.bits() > MAX_BITS {
            // Try to truncate until we're ok
            let ten = BigUint::from_i32(10).unwrap();
            while scale > 0 && result.bits() > 96 {
                result = result / &ten;
                scale -= 1;
                //println!("result: {} new scale: {}", result, scale);
            }
        }

        // Last check for overflow
        if result.bits() > MAX_BITS {
            panic!("Decimal overflow from multiplication");
        }

        if scale > MAX_PRECISION {
            // Then what? Truncate?
            panic!("Scale overflow; cannot represent exp {}", scale);
        }
        // Negativity is based on xor. e.g.
        // 1 * 2 = 2
        // -1 * 2 = -2
        // 1 * -2 = -2
        // -1 * -2 = 2
        let bytes = result.to_bytes_le();
        Decimal::from_bytes_le(bytes, scale, self.is_negative() ^ other.is_negative())
    }
}

forward_all_binop!(impl Div for Decimal, div);

impl<'a, 'b> Div<&'b Decimal> for &'a Decimal {
    type Output = Decimal;

    #[inline]
    fn div(self, other: &Decimal) -> Decimal {
        if other.is_zero() {
            panic!("Division by zero");
        }
        // Shortcircuit the basic cases
        if self.is_zero() {
            return Decimal::zero();
        }

        let mut rem: BigUint;
        let ten = BigUint::from_i32(10).unwrap();
        let mut fractional: Vec<u8> = Vec::new();

        // Get the values
        let (left, right, _) = scaled_biguints(self, other);

        // The algorithm for this is:
        //  (integral, rem) = div_rem(x, y)
        //  while rem > 0 {
        //      (part, rem) = div_rem(rem * 10, y)
        //      fractional_part.push(part)
        //  }
        // This could be a really big number.
        //  Consider 9,999,999,999,999/10,000,000,000,000
        //  This would be (0, 9,999,999,999,999)
        let (i, r) = left.div_rem(&right);
        let mut integral = i;
        let length = if integral.is_zero() { 0usize } else { integral.to_string().len() };
        rem = r;

        // This is slightly too agressive. But it is just being safe. We need to check against Decimal::MAX
        while !rem.is_zero() && fractional.len() + length < MAX_PRECISION as usize {
            let rem_carried = &ten * rem;
            let (frac, r) = rem_carried.div_rem(&right);
            fractional.push(frac.to_u8().unwrap());
            rem = r;
        }

        // Add on the fractional part
        let scale = fractional.len();
        for f in fractional {
            integral = integral * &ten + BigUint::from_u8(f).unwrap();
        }

        let bytes = integral.to_bytes_le();
        // Negative only if one or the other is negative
        Decimal::from_bytes_le(bytes,
                               scale as u32,
                               self.is_negative() ^ other.is_negative())
    }
}

forward_all_binop!(impl Rem for Decimal, rem);

impl<'a, 'b> Rem<&'b Decimal> for &'a Decimal {
    type Output = Decimal;

    #[inline]
    fn rem(self, other: &Decimal) -> Decimal {
        if other.is_zero() {
            panic!("Division by zero");
        }

        // Shortcircuit the basic case
        if self.is_zero() {
            return Decimal::zero();
        }

        // Make sure they're scaled
        let (left, right, scale) = scaled_bigints(self, other);
        //println!("{}, {}", left, right);

        // Since we're just getting the remainder, we simply need to do a standard mod
        let (_, remainder) = left.div_rem(&right);

        // Remainder is always positive?
        let (sign, bytes) = remainder.to_bytes_le();
        Decimal::from_bytes_le(bytes, scale, sign == Minus)
    }
}

impl PartialEq for Decimal {
    #[inline]
    fn eq(&self, other: &Decimal) -> bool {
        self.cmp(other) == Equal
    }
}

impl Eq for Decimal {}

impl PartialOrd for Decimal {
    #[inline]
    fn partial_cmp(&self, other: &Decimal) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Decimal {

    fn cmp(&self, other: &Decimal) -> Ordering {
        // If we have 1.23 and 1.2345 then we have
        //  123 scale 2 and 12345 scale 4
        //  We need to convert the first to
        //  12300 scale 4 so we can compare equally
        let s = self.scale() as u32;
        let o = other.scale() as u32;
        if s > o {
            let d = other.rescale(s);
            return self.cmp(&d);
        } else if s < o {
            let d = self.rescale(o);
            return (&d).cmp(other);
        }

        // Convert to big int
        let si = self.to_biguint();
        let oi = other.to_biguint();
        si.cmp(&oi)
    }
}

// PRIVATE TESTS

// Rescale
//  nb: these choose different constants (u32, u64, calculated)

#[test]
fn it_rescales_integer_up_1() {
    let a = Decimal::from_str("1").unwrap().rescale(8);
    assert_eq!("1.00000000", a.to_string());
}

#[test]
fn it_rescales_integer_up_2() {
    let a = Decimal::from_str("1").unwrap().rescale(16);
    assert_eq!("1.0000000000000000", a.to_string());
}

#[test]
fn it_rescales_integer_up_3() {
    let a = Decimal::from_str("1").unwrap().rescale(24);
    assert_eq!("1.000000000000000000000000", a.to_string());
}

#[test]
fn it_rescales_integer_down_1() {
    let a = Decimal::from_str("1.00000000").unwrap().rescale(2);
    assert_eq!("1.00", a.to_string());
}

#[test]
fn it_rescales_integer_down_2() {
    let a = Decimal::from_str("1.0000000000000000").unwrap().rescale(2);
    assert_eq!("1.00", a.to_string());
}

#[test]
fn it_rescales_integer_down_3() {
    let a = Decimal::from_str("1.000000000000000000000000").unwrap().rescale(2);
    assert_eq!("1.00", a.to_string());
}

#[test]
fn it_rescales_float_up_1() {
    let a = Decimal::from_str("0.1").unwrap().rescale(8);
    assert_eq!("0.10000000", a.to_string());
}

#[test]
fn it_rescales_float_up_2() {
    let a = Decimal::from_str("0.1").unwrap().rescale(16);
    assert_eq!("0.1000000000000000", a.to_string());
}

#[test]
fn it_rescales_float_up_3() {
    let a = Decimal::from_str("0.1").unwrap().rescale(24);
    assert_eq!("0.100000000000000000000000", a.to_string());
}

#[test]
fn it_rescales_float_down_1() {
    let a = Decimal::from_str("1.00000001").unwrap().rescale(2);
    assert_eq!("1.00", a.to_string());
}

#[test]
fn it_rescales_float_down_2() {
    let a = Decimal::from_str("1.0000000000000001").unwrap().rescale(2);
    assert_eq!("1.00", a.to_string());
}

#[test]
fn it_rescales_float_down_3() {
    let a = Decimal::from_str("1.000000000000000000000001").unwrap().rescale(2);
    assert_eq!("1.00", a.to_string());
}

#[test]
fn it_can_round_complex_numbers() {
    // This is 1982.2708333333333
    let a = Decimal { flags: 1572864, hi: 107459117, lo: -2075830955, mid: 849254895 };
    let b = a.round_dp(2u32);
    assert_eq!("1982.27", b.to_string());
}