lucre 0.6.0

An ergonomic library for handling money.
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
#![doc = include_str!("../README.md")]

use std::{cmp::Ordering, fmt::Display, num::NonZeroU32};

pub use rust_decimal::Decimal;
use thiserror::Error;
pub use vec1::{Vec1, vec1};

mod format;
mod parse;

pub use format::Format;
pub use parse::{ParseMoneyError, Parser};

/// An amount of a currency.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Money {
    amount: Decimal,
    currency: Currency,
}

impl Money {
    /// Create a Money object with an amount of a currency's major (non-fractional) units.
    pub fn from_major(major: i64, currency: &Currency) -> Self {
        let amount = Decimal::new(major, 0);
        Self {
            currency: *currency,
            amount,
        }
    }

    /// Create a Money object with an amount of a currency's minor (fractional) units.
    pub fn from_minor(minor: i64, currency: &Currency) -> Self {
        let amount = Decimal::new(minor, currency.minor_digits);
        Self {
            currency: *currency,
            amount,
        }
    }

    /// Create a Money object directly from a decimal amount.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Money};
    ///
    /// // The amount is used verbatim — nothing is rounded or scaled to the
    /// // currency's minor digits.
    /// let money = Money::from_decimal("1.005".parse().unwrap(), &Currency::USD);
    ///
    /// assert_eq!(money.amount().to_string(), "1.005");
    /// ```
    pub fn from_decimal(amount: Decimal, currency: &Currency) -> Self {
        Self {
            currency: *currency,
            amount,
        }
    }

    /// The monetary value, in major units.
    pub fn amount(&self) -> Decimal {
        self.amount
    }

    /// The ISO currency this value is denominated in.
    pub fn currency(&self) -> Currency {
        self.currency
    }

    /// Whether the amount is exactly zero.
    pub fn is_amount_zero(&self) -> bool {
        self.amount.is_zero()
    }

    /// Whether the amount is strictly greater than zero.
    pub fn is_amount_positive(&self) -> bool {
        self.amount > Decimal::ZERO
    }

    /// Whether the amount is strictly less than zero.
    pub fn is_amount_negative(&self) -> bool {
        self.amount < Decimal::ZERO
    }

    /// The sum of two amounts denominated in the same currency — the fallible
    /// counterpart of `+`.
    ///
    /// ## Errors
    ///
    /// Returns `MoneyError::CurrencyMismatch` if the Money values have different currencies.
    /// Returns `MoneyError::Overflow` if the result falls outside the range a `Decimal` can hold.
    pub fn checked_add(&self, other: &Money) -> Result<Self, MoneyError> {
        Self::check_currency_match(self, other)?;

        Ok(Self {
            amount: self
                .amount
                .checked_add(other.amount)
                .ok_or(MoneyError::Overflow)?,
            currency: self.currency,
        })
    }

    /// The difference between two amounts denominated in the same currency —
    /// the fallible counterpart of `-`.
    ///
    /// ## Errors
    ///
    /// Returns `MoneyError::CurrencyMismatch` if the Money values have different currencies.
    /// Returns `MoneyError::Overflow` if the result falls outside the range a `Decimal` can hold.
    pub fn checked_sub(&self, other: &Money) -> Result<Self, MoneyError> {
        Self::check_currency_match(self, other)?;

        Ok(Self {
            amount: self
                .amount
                .checked_sub(other.amount)
                .ok_or(MoneyError::Overflow)?,
            currency: self.currency,
        })
    }

    /// The amount scaled by an arbitrary factor — the fallible counterpart
    /// of `*`.
    ///
    /// ## Errors
    ///
    /// Returns `MoneyError::Overflow` if the result falls outside the range a `Decimal` can hold.
    pub fn checked_mul<N: Into<Decimal>>(&self, other: N) -> Result<Self, MoneyError> {
        Ok(Self {
            amount: self
                .amount
                .checked_mul(other.into())
                .ok_or(MoneyError::Overflow)?,
            currency: self.currency,
        })
    }

    /// The amount split evenly across a divisor — the fallible counterpart
    /// of `/`.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::{Currency, Money, RoundingMode};
    ///
    /// let bill = Money::from_major(10, &Currency::USD);
    ///
    /// // The quotient keeps `Decimal`'s full precision, so it may carry
    /// // more fractional digits than the currency has; apply `Money::round`
    /// // when a spendable amount is needed.
    /// let third = bill.checked_div(3).unwrap();
    ///
    /// assert_eq!(third.round(2, RoundingMode::HalfUp).to_string(), "3.33 USD");
    /// ```
    ///
    /// ## Errors
    ///
    /// Returns `MoneyError::DivisionByZero` if the `other` is zero.
    /// Returns `MoneyError::Overflow` if the result falls outside the range a `Decimal` can hold.
    pub fn checked_div<N: Into<Decimal>>(&self, other: N) -> Result<Self, MoneyError> {
        let other_dec: Decimal = other.into();

        if other_dec.is_zero() {
            return Err(MoneyError::DivisionByZero);
        }

        Ok(Self {
            amount: self
                .amount
                .checked_div(other_dec)
                .ok_or(MoneyError::Overflow)?,
            currency: self.currency,
        })
    }

    /// Returns a new `Money` rounded to the specified number of digits in the fractional portion,
    /// using the given strategy.
    pub fn round(&self, digits: u32, strategy: RoundingMode) -> Self {
        let dec_strategy = match strategy {
            RoundingMode::HalfUp => rust_decimal::RoundingStrategy::MidpointAwayFromZero,
            RoundingMode::HalfDown => rust_decimal::RoundingStrategy::MidpointTowardZero,
            RoundingMode::HalfEven => rust_decimal::RoundingStrategy::MidpointNearestEven,
        };

        let amount = self.amount.round_dp_with_strategy(digits, dec_strategy);

        Self {
            amount,
            currency: self.currency,
        }
    }

    /// Divide the amount into `n` parts that sum back to exactly `self`.
    ///
    /// Parts differ by at most one smallest unit — the finer of the amount's
    /// scale and the currency's minor digits. Negative amounts divide
    /// symmetrically.
    ///
    /// ## Example
    ///
    /// ```
    /// use std::num::NonZeroU32;
    /// use lucre::{Currency, Money};
    ///
    /// let three = NonZeroU32::new(3).unwrap();
    /// let parts = Money::from_major(10, &Currency::USD).split(three);
    ///
    /// // Earlier parts take the extra units.
    /// assert_eq!(
    ///     *parts,
    ///     [
    ///         Money::from_minor(334, &Currency::USD),
    ///         Money::from_minor(333, &Currency::USD),
    ///         Money::from_minor(333, &Currency::USD),
    ///     ]
    /// );
    /// ```
    pub fn split(&self, n: NonZeroU32) -> Vec1<Money> {
        let count = n.get() as usize;
        self.distribute(u128::from(n.get()), std::iter::repeat_n(1, count))
    }

    /// Divide the amount proportionally to `weights`, producing parts that
    /// sum back to exactly `self`, one per weight.
    ///
    /// Whatever cannot be divided proportionally at the smallest unit — the
    /// finer of the amount's scale and the currency's minor digits — goes one
    /// unit apiece to the earliest parts. Negative amounts divide
    /// symmetrically.
    ///
    /// ## Example
    ///
    /// ```
    /// use std::num::NonZeroU32;
    /// use lucre::{Currency, Money, vec1};
    ///
    /// let three = NonZeroU32::new(3).unwrap();
    /// let seven = NonZeroU32::new(7).unwrap();
    ///
    /// let parts = Money::from_minor(5, &Currency::USD).allocate(&vec1![three, seven]);
    ///
    /// assert_eq!(
    ///     *parts,
    ///     [
    ///         Money::from_minor(2, &Currency::USD),
    ///         Money::from_minor(3, &Currency::USD),
    ///     ]
    /// );
    /// ```
    pub fn allocate(&self, weights: &Vec1<NonZeroU32>) -> Vec1<Money> {
        let sum = weights.iter().map(|w| u128::from(w.get())).sum();
        self.distribute(sum, weights.iter().map(|w| u128::from(w.get())))
    }

    /// Apportion the amount's smallest units across `weights`, giving each
    /// part its proportional floor and handing the leftover units one apiece
    /// to the earliest parts.
    ///
    /// Computing each floor as `whole * w + partial * w / weight_sum` (rather
    /// than `magnitude * w / weight_sum`) keeps every intermediate value no
    /// larger than the original mantissa, so no input can overflow.
    fn distribute(&self, weight_sum: u128, weights: impl Iterator<Item = u128>) -> Vec1<Money> {
        let mut scale = self.amount.scale();
        let mut magnitude = self.amount.mantissa().unsigned_abs();
        let sign = if self.amount.mantissa() < 0 {
            -1i128
        } else {
            1
        };

        // Refine coarse amounts to minor units, stopping short if the
        // mantissa would overflow (only possible within 10^4 of Decimal::MAX).
        let max_magnitude = Decimal::MAX.mantissa().unsigned_abs();
        while scale < self.currency.minor_digits && magnitude <= max_magnitude / 10 {
            magnitude *= 10;
            scale += 1;
        }

        let whole = magnitude / weight_sum;
        let partial = magnitude % weight_sum;

        let mut units: Vec<u128> = weights
            .map(|weight| whole * weight + partial * weight / weight_sum)
            .collect();

        let mut leftover = magnitude - units.iter().sum::<u128>();
        for unit in units.iter_mut() {
            if leftover == 0 {
                break;
            }
            *unit += 1;
            leftover -= 1;
        }

        let parts = units
            .into_iter()
            .map(|unit| Self {
                amount: Decimal::from_i128_with_scale(sign * unit as i128, scale),
                currency: self.currency,
            })
            .collect();

        Vec1::try_from_vec(parts).expect("one part per weight, and weights cannot be empty")
    }

    fn check_currency_match(a: &Money, b: &Money) -> Result<(), MoneyError> {
        if a.currency == b.currency {
            Ok(())
        } else {
            Err(MoneyError::CurrencyMismatch)
        }
    }
}

impl std::ops::Add for Money {
    type Output = Money;

    /// # Panics
    ///
    /// Panics on mismatched currencies or on overflow. Use
    /// [`Money::checked_add`] to handle both conditions as errors.
    fn add(self, rhs: Self) -> Self::Output {
        self.checked_add(&rhs)
            .unwrap_or_else(|e| panic!("addition error: {e}"))
    }
}

impl std::ops::Sub for Money {
    type Output = Money;

    /// # Panics
    ///
    /// Panics on mismatched currencies or on overflow. Use
    /// [`Money::checked_sub`] to handle both conditions as errors.
    fn sub(self, rhs: Self) -> Self::Output {
        self.checked_sub(&rhs)
            .unwrap_or_else(|e| panic!("subtraction error: {e}"))
    }
}

impl<N> std::ops::Mul<N> for Money
where
    N: Into<Decimal>,
{
    type Output = Money;

    /// # Panics
    ///
    /// Panics on overflow. Use [`Money::checked_mul`] to handle it as an
    /// error.
    fn mul(self, rhs: N) -> Self::Output {
        self.checked_mul(rhs)
            .unwrap_or_else(|e| panic!("multiplication error: {e}"))
    }
}

impl<N> std::ops::Div<N> for Money
where
    N: Into<Decimal>,
{
    type Output = Money;

    /// # Panics
    ///
    /// Panics on a zero divisor or on overflow. Use [`Money::checked_div`] to
    /// handle both conditions as errors.
    fn div(self, rhs: N) -> Self::Output {
        self.checked_div(rhs)
            .unwrap_or_else(|e| panic!("division error: {e}"))
    }
}

impl std::cmp::PartialOrd for Money {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        if self.currency != other.currency {
            return None;
        }

        Some(self.amount.cmp(&other.amount))
    }
}

/// The ISO 4217 numeric code for a currency.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct IsoNumericCode(u32);

impl IsoNumericCode {
    /// The code as its underlying integer.
    pub fn value(&self) -> u32 {
        self.0
    }
}

/// The ISO 4217 alphabetic code for a currency.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct IsoAlphabeticCode([u8; 3]);

impl IsoAlphabeticCode {
    /// The code as a string slice.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Currency;
    ///
    /// assert_eq!(Currency::USD.alphabetic_code().as_str(), "USD");
    /// ```
    pub fn as_str(&self) -> &str {
        std::str::from_utf8(&self.0).expect("alphabetic codes are ASCII")
    }
}

impl Display for IsoAlphabeticCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// An ISO 4217 currency.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct Currency {
    alphabetic_code: IsoAlphabeticCode,
    numeric_code: IsoNumericCode,
    minor_digits: u32,
    symbol: &'static str,
}

impl Currency {
    /// The three-letter code identifying this currency.
    pub fn alphabetic_code(&self) -> IsoAlphabeticCode {
        self.alphabetic_code
    }

    /// The numeric code identifying this currency.
    pub fn numeric_code(&self) -> IsoNumericCode {
        self.numeric_code
    }

    /// How many fractional digits one whole unit divides into.
    pub fn minor_digits(&self) -> u32 {
        self.minor_digits
    }

    /// The customary sign written next to amounts.
    ///
    /// ## Example
    ///
    /// ```
    /// use lucre::Currency;
    ///
    /// assert_eq!(Currency::USD.symbol(), "$");
    /// assert_eq!(Currency::GBP.symbol(), "£");
    /// ```
    pub fn symbol(&self) -> &'static str {
        self.symbol
    }
}

// The ISO 4217 catalog, generated by build.rs from isodata.tsv.
include!(concat!(env!("OUT_DIR"), "/iso_currencies.rs"));

impl Display for Currency {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.alphabetic_code)
    }
}

/// Strategy for resolving a midpoint value when reducing precision.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RoundingMode {
    HalfUp,
    HalfDown,
    HalfEven,
}

/// An error that can occur while working with `Money`.
#[derive(Error, Debug)]
pub enum MoneyError {
    #[error("mismatched currencies")]
    CurrencyMismatch,

    #[error("overflow")]
    Overflow,

    #[error("division by zero")]
    DivisionByZero,
}

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

    #[test]
    fn from_major_minor_decimal_are_equal_test() {
        let from_minor = Money::from_minor(100, &Currency::USD);
        let from_major = Money::from_major(1, &Currency::USD);
        let from_decimal = Money::from_decimal(dec!(1.00), &Currency::USD);

        assert_eq!(from_minor, from_major);
        assert_eq!(from_major, from_decimal);
        assert_eq!(from_minor, from_decimal);
    }

    #[test]
    fn eq_with_different_currencies_are_not_equal() {
        let a = Money::from_major(100, &Currency::USD);
        let b = Money::from_major(100, &Currency::EUR);

        assert_ne!(a, b);
    }

    #[test]
    fn not_equal_with_different_amounts_test() {
        let a = Money::from_major(100, &Currency::USD);
        let b = Money::from_major(200, &Currency::USD);

        assert_ne!(a, b);
    }

    #[test]
    fn add_test() {
        let a = Money::from_minor(100, &Currency::USD);
        let b = Money::from_minor(200, &Currency::USD);

        let expected = Money::from_minor(300, &Currency::USD);

        assert_eq!(a + b, expected);
    }

    #[test]
    fn add_overflow_test() {
        let a = Money::from_decimal(Decimal::MAX, &Currency::USD);
        let b = Money::from_major(1, &Currency::USD);

        assert!(a.checked_add(&b).is_err());
    }

    #[test]
    #[should_panic]
    fn add_operator_overflow_panics_test() {
        let a = Money::from_decimal(Decimal::MAX, &Currency::USD);
        let b = Money::from_major(1, &Currency::USD);

        let _ = a + b;
    }

    #[test]
    fn add_mismatched_currencies_test() {
        let a = Money::from_minor(100, &Currency::USD);
        let b = Money::from_minor(100, &Currency::EUR);

        assert!(a.checked_add(&b).is_err());
    }

    #[test]
    #[should_panic]
    fn add_operator_mismatched_currencies_panics_test() {
        let _ = Money::from_minor(100, &Currency::USD) + Money::from_minor(100, &Currency::EUR);
    }

    #[test]
    fn sub_test() {
        let a = Money::from_minor(200, &Currency::USD);
        let b = Money::from_minor(100, &Currency::USD);

        assert_eq!(a - b, Money::from_minor(100, &Currency::USD));
    }

    #[test]
    fn sub_overflow_test() {
        let a = Money::from_decimal(Decimal::MIN, &Currency::USD);
        let b = Money::from_major(1, &Currency::USD);

        assert!(a.checked_sub(&b).is_err());
    }

    #[test]
    fn sub_mismatched_currencies_test() {
        let a = Money::from_minor(100, &Currency::USD);
        let b = Money::from_minor(100, &Currency::EUR);

        assert!(a.checked_sub(&b).is_err());
    }

    #[test]
    #[should_panic]
    fn sub_operator_mismatched_currencies_panics_test() {
        let _ = Money::from_minor(100, &Currency::USD) - Money::from_minor(100, &Currency::EUR);
    }

    #[test]
    fn mul_test() {
        let a = Money::from_major(100, &Currency::USD);

        assert_eq!(a * 5, Money::from_major(500, &Currency::USD));
    }

    #[test]
    fn mul_overflow_test() {
        let a = Money::from_decimal(Decimal::MAX, &Currency::USD);

        assert!(a.checked_mul(2).is_err());
    }

    #[test]
    fn div_test() {
        let a = Money::from_major(100, &Currency::USD);

        assert_eq!(a / 5, Money::from_major(20, &Currency::USD));
    }

    #[test]
    fn div_overflow_test() {
        let a = Money::from_decimal(Decimal::MAX, &Currency::USD);

        assert!(a.checked_div(dec!(0.5)).is_err());
    }

    #[test]
    fn div_by_zero_test() {
        let a = Money::from_major(100, &Currency::USD);

        assert!(a.checked_div(0).is_err());
    }

    #[test]
    #[should_panic]
    fn div_operator_by_zero_panics_test() {
        let _ = Money::from_major(100, &Currency::USD) / 0;
    }

    #[test]
    fn partial_cmp_test() {
        let one = Money::from_major(1, &Currency::USD);
        let two = Money::from_major(2, &Currency::USD);

        assert_eq!(one.partial_cmp(&two), Some(Ordering::Less));
        assert_eq!(one.partial_cmp(&one), Some(Ordering::Equal));
        assert_eq!(two.partial_cmp(&one), Some(Ordering::Greater));
    }

    #[test]
    fn partial_cmp_mismatched_currencies_test() {
        let a = Money::from_major(1, &Currency::USD);
        let b = Money::from_major(1, &Currency::EUR);

        assert_eq!(a.partial_cmp(&b), None);
    }

    #[test]
    #[allow(clippy::neg_cmp_op_on_partial_ord)]
    fn ordering_operators_test() {
        let one = Money::from_major(1, &Currency::USD);
        let two = Money::from_major(2, &Currency::USD);

        assert!(one < two);
        assert!(one <= two);
        assert!(one <= one);
        assert!(two > one);
        assert!(two >= one);
        assert!(two >= two);
        assert!(!(two < one));
        assert!(!(one > two));
    }

    #[test]
    #[allow(clippy::neg_cmp_op_on_partial_ord)]
    fn ordering_operators_mismatched_currencies_test() {
        let a = Money::from_major(1, &Currency::USD);
        let b = Money::from_major(2, &Currency::EUR);

        assert!(!(a < b));
        assert!(!(a > b));
        assert!(!(a <= b));
        assert!(!(a >= b));
    }

    #[test]
    fn round_half_up_test() {
        let a = Money::from_decimal(dec!(0.125), &Currency::USD);

        assert_eq!(
            a.round(2, RoundingMode::HalfUp),
            Money::from_decimal(dec!(0.13), &Currency::USD)
        );
    }

    #[test]
    fn round_half_down_test() {
        let a = Money::from_decimal(dec!(0.125), &Currency::USD);

        assert_eq!(
            a.round(2, RoundingMode::HalfDown),
            Money::from_decimal(dec!(0.12), &Currency::USD)
        );
    }

    #[test]
    fn round_half_even_test() {
        assert_eq!(
            Money::from_decimal(dec!(0.125), &Currency::USD).round(2, RoundingMode::HalfEven),
            Money::from_decimal(dec!(0.12), &Currency::USD)
        );
        assert_eq!(
            Money::from_decimal(dec!(0.135), &Currency::USD).round(2, RoundingMode::HalfEven),
            Money::from_decimal(dec!(0.14), &Currency::USD)
        );
    }

    #[test]
    #[should_panic]
    fn sub_operator_overflow_panics_test() {
        let a = Money::from_decimal(Decimal::MIN, &Currency::USD);
        let b = Money::from_major(1, &Currency::USD);

        let _ = a - b;
    }

    #[test]
    #[should_panic]
    fn mul_operator_overflow_panics_test() {
        let _ = Money::from_decimal(Decimal::MAX, &Currency::USD) * 2;
    }

    #[test]
    #[should_panic]
    fn div_operator_overflow_panics_test() {
        let _ = Money::from_decimal(Decimal::MAX, &Currency::USD) / dec!(0.5);
    }

    #[test]
    fn arithmetic_with_negative_amounts_test() {
        let credit = Money::from_major(5, &Currency::USD);
        let debit = Money::from_major(-2, &Currency::USD);

        assert_eq!(credit + debit, Money::from_major(3, &Currency::USD));
        assert_eq!(debit - credit, Money::from_major(-7, &Currency::USD));
        assert!(debit < credit);
    }

    #[test]
    fn mul_by_decimal_scalar_test() {
        let a = Money::from_major(5, &Currency::USD);

        assert_eq!(
            a * dec!(0.5),
            Money::from_decimal(dec!(2.5), &Currency::USD)
        );
    }

    #[test]
    fn div_keeps_fractional_result_test() {
        let a = Money::from_major(10, &Currency::USD);

        assert_eq!(a / 4, Money::from_decimal(dec!(2.5), &Currency::USD));
    }

    #[test]
    fn round_negative_midpoint_goes_away_from_zero_test() {
        let a = Money::from_decimal(dec!(-0.125), &Currency::USD);

        assert_eq!(
            a.round(2, RoundingMode::HalfUp),
            Money::from_decimal(dec!(-0.13), &Currency::USD)
        );
    }

    #[test]
    fn round_beyond_scale_is_identity_test() {
        let a = Money::from_decimal(dec!(1.5), &Currency::USD);

        assert_eq!(a.round(2, RoundingMode::HalfUp), a);
    }

    #[test]
    fn money_accessors_test() {
        let a = Money::from_minor(150, &Currency::USD);

        assert_eq!(a.amount(), dec!(1.50));
        assert_eq!(a.currency(), Currency::USD);
    }

    #[test]
    fn currency_accessors_test() {
        let currency = Currency::USD;

        assert_eq!(currency.alphabetic_code().as_str(), "USD");
        assert_eq!(currency.numeric_code().value(), 840);
        assert_eq!(currency.minor_digits(), 2);
        assert_eq!(currency.symbol(), "$");
    }

    #[test]
    fn display_test() {
        assert_eq!(
            Money::from_minor(150, &Currency::USD).to_string(),
            "1.50 USD"
        );
        assert_eq!(
            Money::from_major(-3, &Currency::USD).to_string(),
            "-3.00 USD"
        );
    }

    #[test]
    fn currency_lookup_test() {
        assert_eq!(Currency::from_alphabetic_code("USD"), Some(Currency::USD));
        assert_eq!(Currency::from_alphabetic_code("ZZZ"), None);
        assert_eq!(Currency::from_numeric_code(978), Some(Currency::EUR));
        assert_eq!(Currency::from_numeric_code(1), None);
    }

    #[test]
    fn currency_catalog_test() {
        assert!(Currency::all().contains(&Currency::USD));
        assert!(Currency::all().contains(&Currency::XAU));
        assert_eq!(Currency::BHD.minor_digits(), 3);
        assert_eq!(Currency::XAU.minor_digits(), 0);
    }

    #[test]
    fn is_amount_zero_test() {
        assert!(Money::from_major(0, &Currency::USD).is_amount_zero());
        assert!(!Money::from_major(1, &Currency::USD).is_amount_zero());
        assert!(!Money::from_major(-1, &Currency::USD).is_amount_zero());
    }

    #[test]
    fn is_amount_positive_test() {
        assert!(Money::from_major(1, &Currency::USD).is_amount_positive());
        assert!(!Money::from_major(-1, &Currency::USD).is_amount_positive());
        assert!(!Money::from_major(0, &Currency::USD).is_amount_positive());
    }

    #[test]
    fn is_amount_negative_test() {
        assert!(Money::from_major(-1, &Currency::USD).is_amount_negative());
        assert!(!Money::from_major(1, &Currency::USD).is_amount_negative());
        assert!(!Money::from_major(0, &Currency::USD).is_amount_negative());
    }

    #[test]
    fn negative_zero_is_zero_not_negative_test() {
        let a = Money::from_decimal(dec!(-0.00), &Currency::USD);

        assert!(a.is_amount_zero());
        assert!(!a.is_amount_negative());
        assert!(!a.is_amount_positive());
    }

    #[test]
    fn from_minor_with_three_minor_digits_test() {
        let a = Money::from_minor(1500, &Currency::BHD);

        assert_eq!(a.amount(), dec!(1.500));
    }

    fn n(value: u32) -> NonZeroU32 {
        NonZeroU32::new(value).unwrap()
    }

    fn usd(amount: Decimal) -> Money {
        Money::from_decimal(amount, &Currency::USD)
    }

    #[test]
    fn split_evenly_test() {
        let parts = usd(dec!(9.00)).split(n(3));

        assert_eq!(*parts, vec![usd(dec!(3.00)); 3]);
    }

    #[test]
    fn split_gives_extra_units_to_earlier_parts_test() {
        let parts = usd(dec!(10.00)).split(n(3));

        assert_eq!(
            *parts,
            vec![usd(dec!(3.34)), usd(dec!(3.33)), usd(dec!(3.33))]
        );
    }

    #[test]
    fn split_into_one_part_is_identity_test() {
        let a = usd(dec!(10.01));

        assert_eq!(*a.split(n(1)), vec![a]);
    }

    #[test]
    fn split_negative_is_symmetric_test() {
        let parts = usd(dec!(-10.01)).split(n(2));

        assert_eq!(*parts, vec![usd(dec!(-5.01)), usd(dec!(-5.00))]);
    }

    #[test]
    fn split_zero_amount_test() {
        let parts = usd(dec!(0.00)).split(n(3));

        assert_eq!(*parts, vec![usd(dec!(0.00)); 3]);
    }

    #[test]
    fn split_keeps_sub_minor_precision_test() {
        let parts = usd(dec!(10.005)).split(n(2));

        assert_eq!(*parts, vec![usd(dec!(5.003)), usd(dec!(5.002))]);
    }

    #[test]
    fn split_refines_coarse_amounts_to_minor_units_test() {
        let parts = Money::from_major(10, &Currency::USD).split(n(3));

        assert_eq!(
            *parts,
            vec![usd(dec!(3.34)), usd(dec!(3.33)), usd(dec!(3.33))]
        );
    }

    #[test]
    fn split_zero_minor_digit_currency_stays_whole_test() {
        let parts = Money::from_major(10, &Currency::XAU).split(n(3));

        assert_eq!(
            *parts,
            vec![
                Money::from_major(4, &Currency::XAU),
                Money::from_major(3, &Currency::XAU),
                Money::from_major(3, &Currency::XAU),
            ]
        );
    }

    #[test]
    fn split_near_decimal_max_conserves_the_total_test() {
        let a = Money::from_decimal(Decimal::MAX, &Currency::USD);

        let total = a
            .split(n(3))
            .into_iter()
            .reduce(|sum, part| sum + part)
            .unwrap();

        assert_eq!(total, a);
    }

    #[test]
    fn split_conserves_the_total_test() {
        let a = usd(dec!(100.03));

        let total = a
            .split(n(7))
            .into_iter()
            .reduce(|sum, part| sum + part)
            .unwrap();

        assert_eq!(total, a);
    }

    #[test]
    fn allocate_proportionally_test() {
        let parts = usd(dec!(10.00)).allocate(&vec1![n(7), n(3)]);

        assert_eq!(*parts, vec![usd(dec!(7.00)), usd(dec!(3.00))]);
    }

    #[test]
    fn allocate_gives_remainder_units_to_earlier_parts_test() {
        let parts = usd(dec!(0.05)).allocate(&vec1![n(3), n(7)]);

        assert_eq!(*parts, vec![usd(dec!(0.02)), usd(dec!(0.03))]);
    }

    #[test]
    fn allocate_single_weight_is_identity_test() {
        let a = usd(dec!(10.01));

        assert_eq!(*a.allocate(&vec1![n(42)]), vec![a]);
    }

    #[test]
    fn allocate_negative_is_symmetric_test() {
        let parts = usd(dec!(-0.05)).allocate(&vec1![n(3), n(7)]);

        assert_eq!(*parts, vec![usd(dec!(-0.02)), usd(dec!(-0.03))]);
    }

    #[test]
    fn allocate_conserves_the_total_test() {
        let a = usd(dec!(97.31));

        let total = a
            .allocate(&vec1![n(1), n(999), n(37), n(2)])
            .into_iter()
            .reduce(|sum, part| sum + part)
            .unwrap();

        assert_eq!(total, a);
    }

    #[test]
    fn allocate_with_equal_weights_matches_split_test() {
        let a = usd(dec!(10.00));

        assert_eq!(a.allocate(&vec1![n(5), n(5), n(5)]), a.split(n(3)));
    }
}