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
pub mod calculation;
pub mod constructor;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// A trait for defining currency localization methods.
pub trait CurrencyLocale {
    /// Retrieves the separator used for the currency.
    fn separator(&self) -> char;
    /// Retrieves the thousand separator used for the currency.
    fn thousand_separator(&self) -> char;
    /// Retrieves the currency symbol.
    fn currency_symbol(&self) -> &'static str;
}

/// Represents a currency value with specified localization.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Currency<L: CurrencyLocale + Default> {
    negative: bool,
    full: usize,
    part: u8,
    locale: L,
}

impl<L> std::fmt::Display for Currency<L>
where
    L: CurrencyLocale + Default,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut buffer = self.full.to_string();
        if buffer.len() > 3 {
            let len = buffer.len() - 2;
            for idx in (1..len).rev().step_by(3) {
                buffer.insert(idx, self.locale.thousand_separator());
            }
        }
        if self.negative {
            write!(f, "-")?;
        }
        write!(
            f,
            "{}{}{:02} {}",
            buffer,
            self.locale.separator(),
            self.part,
            self.locale.currency_symbol()
        )
    }
}

impl<L: CurrencyLocale + Default> Currency<L> {
    /// Constructs a new Currency instance.
    ///
    /// # Arguments
    ///
    /// * `negative` - Indicates if the currency value is negative.
    /// * `full` - The whole number part of the currency value.
    /// * `part` - The fractional part of the currency value.
    /// * `locale` - The localization information for the currency.
    ///
    /// # Returns
    ///
    /// A new `Currency` instance.
    #[must_use]
    pub fn new(negative: bool, full: usize, part: u8, locale: L) -> Self {
        Self {
            negative,
            full,
            part,
            locale,
        }
    }

    /// Updates the localization information of the currency.
    ///
    /// # Arguments
    ///
    /// * `locale` - The updated localization information.
    ///
    /// # Returns
    ///
    /// The updated `Currency` instance with the new localization.
    #[must_use]
    pub fn with_locale(mut self, locale: L) -> Self {
        self.locale = locale;
        self
    }
}

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

    #[derive(Clone, Copy, Default, Debug, PartialEq)]
    enum CurrencyL {
        #[default]
        De,
    }

    impl CurrencyLocale for CurrencyL {
        fn separator(&self) -> char {
            ','
        }

        fn thousand_separator(&self) -> char {
            '.'
        }

        fn currency_symbol(&self) -> &'static str {
            "€"
        }
    }

    #[test]
    fn print_currency() {
        let mut curr = Currency::new(false, 2, 22, CurrencyL::De);
        for (full, full_string) in [
            (2, "2"),
            (20, "20"),
            (200, "200"),
            (2_000, "2.000"),
            (20_000, "20.000"),
            (200_000, "200.000"),
            (2_000_000, "2.000.000"),
            (20_000_000, "20.000.000"),
            (200_000_000, "200.000.000"),
        ] {
            curr.full = full;
            assert_eq!(format!("{full_string},22 €"), curr.to_string());
        }

        let curr = Currency::new(false, 2, 2, CurrencyL::De);
        assert_eq!("2,02 €", &curr.to_string());
    }

    #[test]
    fn construct_f32() {
        let first_val = 100.8_f32;
        let second_val = 191.0_f32;

        let expected = Currency::<CurrencyL>::from(first_val + second_val);
        assert_eq!(expected, Currency::new(false, 291, 80, CurrencyL::De));
    }
}