Skip to main content

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    Rupee,
31}
32
33impl Currency {
34    pub fn from_char(c: char) -> Option<Self> {
35        let cur = match c {
36            '$' => Self::Dollar,
37            '¢' => Self::Cent,
38            '€' => Self::Euro,
39            '₽' => Self::Ruble,
40            '₺' => Self::Lira,
41            '£' => Self::Pound,
42            '¥' => Self::Yen,
43            '฿' => Self::Baht,
44            '₩' => Self::Won,
45            '₭' => Self::Kip,
46            '₹' => Self::Rupee,
47            _ => return None,
48        };
49
50        Some(cur)
51    }
52
53    pub fn to_char(&self) -> char {
54        match self {
55            Self::Dollar => '$',
56            Self::Cent => '¢',
57            Self::Euro => '€',
58            Self::Ruble => '₽',
59            Self::Lira => '₺',
60            Self::Pound => '£',
61            Self::Yen => '¥',
62            Self::Baht => '฿',
63            Self::Won => '₩',
64            Self::Kip => '₭',
65            Self::Rupee => '₹',
66        }
67    }
68
69    /// Format an amount of the specific currency.
70    pub fn format_amount(&self, amount: &Number) -> String {
71        let c = self.to_char();
72
73        let amount = amount.to_string();
74
75        match self {
76            Currency::Dollar => format!("{c}{amount}"),
77            Currency::Cent => format!("{amount}{c}"),
78            Currency::Euro => format!("{c}{amount}"),
79            Currency::Ruble => format!("{amount} {c}"),
80            Currency::Lira => format!("{amount} {c}"),
81            Currency::Pound => format!("{c}{amount}"),
82            Currency::Yen => format!("{c} {amount}"),
83            Currency::Baht => format!("{amount} {c}"),
84            Currency::Won => format!("{c} {amount}"),
85            Currency::Kip => format!("{c}{amount}"),
86            Currency::Rupee => format!("{c}{amount}"),
87        }
88    }
89}