harper_core/
currency.rs

1use is_macro::Is;
2use serde::{Deserialize, Serialize};
3
4use crate::Number;
5
6/// A national or international currency
7#[derive(Debug, Is, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Hash)]
8pub enum Currency {
9    // $
10    Dollar,
11    // ¢
12    Cent,
13    // €
14    Euro,
15    // ₽
16    Ruble,
17    // ₺
18    Lira,
19    // £
20    Pound,
21    // ¥
22    Yen,
23    // ฿
24    Baht,
25    // ₩
26    Won,
27    // ₭,
28    Kip,
29}
30
31impl Currency {
32    pub fn from_char(c: char) -> Option<Self> {
33        let cur = match c {
34            '$' => Self::Dollar,
35            '¢' => Self::Cent,
36            '€' => Self::Euro,
37            '₽' => Self::Ruble,
38            '₺' => Self::Lira,
39            '£' => Self::Pound,
40            '¥' => Self::Yen,
41            '฿' => Self::Baht,
42            '₩' => Self::Won,
43            '₭' => Self::Kip,
44            _ => return None,
45        };
46
47        Some(cur)
48    }
49
50    pub fn to_char(&self) -> char {
51        match self {
52            Self::Dollar => '$',
53            Self::Cent => '¢',
54            Self::Euro => '€',
55            Self::Ruble => '₽',
56            Self::Lira => '₺',
57            Self::Pound => '£',
58            Self::Yen => '¥',
59            Self::Baht => '฿',
60            Self::Won => '₩',
61            Self::Kip => '₭',
62        }
63    }
64
65    /// Format an amount of the specific currency.
66    pub fn format_amount(&self, amount: &Number) -> String {
67        let c = self.to_char();
68
69        let amount = amount.to_string();
70
71        match self {
72            Currency::Dollar => format!("{c}{amount}"),
73            Currency::Cent => format!("{amount}{c}"),
74            Currency::Euro => format!("{c}{amount}"),
75            Currency::Ruble => format!("{amount} {c}"),
76            Currency::Lira => format!("{amount} {c}"),
77            Currency::Pound => format!("{c}{amount}"),
78            Currency::Yen => format!("{c} {amount}"),
79            Currency::Baht => format!("{amount} {c}"),
80            Currency::Won => format!("{c} {amount}"),
81            Currency::Kip => format!("{c}{amount}"),
82        }
83    }
84}