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)]
14pub struct Cents(pub u32);
15
16impl Cents {
17 pub const ZERO: Self = Self(0);
18
19 pub const fn new(cents: u32) -> Self {
20 Self(cents)
21 }
22
23 pub const fn from_dollars(dollars: u32) -> Self {
24 Self(dollars * 100)
25 }
26
27 pub fn saturating_sub(self, other: Cents) -> Self {
28 Self(self.0.saturating_sub(other.0))
29 }
30}
31
32#[cfg(test)]
33mod tests {
34 use pretty_assertions::assert_eq;
35
36 use super::*;
37
38 #[test]
39 fn test_cents_new() {
40 assert_eq!(Cents::new(50), Cents(50));
41 }
42
43 #[test]
44 fn test_cents_from_dollars() {
45 assert_eq!(Cents::from_dollars(1), Cents(100));
46 assert_eq!(Cents::from_dollars(5), Cents(500));
47 }
48
49 #[test]
50 fn test_cents_zero() {
51 assert_eq!(Cents::ZERO, Cents(0));
52 }
53
54 #[test]
55 fn test_cents_add() {
56 assert_eq!(Cents(50) + Cents(30), Cents(80));
57 }
58
59 #[test]
60 fn test_cents_add_assign() {
61 let mut cents = Cents(50);
62 cents += Cents(30);
63 assert_eq!(cents, Cents(80));
64 }
65
66 #[test]
67 fn test_cents_saturating_sub() {
68 assert_eq!(Cents(50).saturating_sub(Cents(30)), Cents(20));
69 assert_eq!(Cents(30).saturating_sub(Cents(50)), Cents(0));
70 }
71
72 #[test]
73 fn test_cents_ordering() {
74 assert!(Cents(50) > Cents(30));
75 assert!(Cents(30) < Cents(50));
76 assert_eq!(Cents(50), Cents(50));
77 }
78}