cents.rs

 1/// A number of cents.
 2#[derive(
 3    Debug,
 4    PartialEq,
 5    Eq,
 6    PartialOrd,
 7    Ord,
 8    Hash,
 9    Clone,
10    Copy,
11    derive_more::Add,
12    derive_more::AddAssign,
13    derive_more::Sub,
14    derive_more::SubAssign,
15)]
16pub struct Cents(pub u32);
17
18impl Cents {
19    pub const ZERO: Self = Self(0);
20
21    pub const fn new(cents: u32) -> Self {
22        Self(cents)
23    }
24
25    pub const fn from_dollars(dollars: u32) -> Self {
26        Self(dollars * 100)
27    }
28
29    pub fn saturating_sub(self, other: Cents) -> Self {
30        Self(self.0.saturating_sub(other.0))
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use pretty_assertions::assert_eq;
37
38    use super::*;
39
40    #[test]
41    fn test_cents_new() {
42        assert_eq!(Cents::new(50), Cents(50));
43    }
44
45    #[test]
46    fn test_cents_from_dollars() {
47        assert_eq!(Cents::from_dollars(1), Cents(100));
48        assert_eq!(Cents::from_dollars(5), Cents(500));
49    }
50
51    #[test]
52    fn test_cents_zero() {
53        assert_eq!(Cents::ZERO, Cents(0));
54    }
55
56    #[test]
57    fn test_cents_add() {
58        assert_eq!(Cents(50) + Cents(30), Cents(80));
59    }
60
61    #[test]
62    fn test_cents_add_assign() {
63        let mut cents = Cents(50);
64        cents += Cents(30);
65        assert_eq!(cents, Cents(80));
66    }
67
68    #[test]
69    fn test_cents_saturating_sub() {
70        assert_eq!(Cents(50).saturating_sub(Cents(30)), Cents(20));
71        assert_eq!(Cents(30).saturating_sub(Cents(50)), Cents(0));
72    }
73
74    #[test]
75    fn test_cents_ordering() {
76        assert!(Cents(50) > Cents(30));
77        assert!(Cents(30) < Cents(50));
78        assert_eq!(Cents(50), Cents(50));
79    }
80}