rusty_money/
locale.rs

1use std::str::FromStr;
2
3/// Enumerates regions which have unique formatting standards for Currencies.  
4///
5/// Each Locale maps 1:1 to a LocalFormat, which contains the characteristics for formatting.
6#[derive(Debug, PartialEq, Eq, Clone, Copy)]
7pub enum Locale {
8    EnUs,
9    EnIn,
10    EnEu,
11    EnBy,
12}
13
14/// Stores currency formatting metadata for a specific region (e.g. EN-US).
15#[derive(Debug, PartialEq, Eq)]
16pub struct LocalFormat {
17    pub name: &'static str,
18    pub digit_separator: char,
19    pub digit_separator_pattern: &'static str,
20    pub exponent_separator: char,
21}
22
23impl LocalFormat {
24    /// Returns a vector indicating where digit separators should be applied on a Money amount.
25    ///
26    /// For example, [3,3,3] indicates that the digit separator should be applied after the 3rd, 6th and 9th digits.  
27    pub fn digit_separator_pattern(&self) -> Vec<usize> {
28        let v: Vec<&str> = self.digit_separator_pattern.split(", ").collect();
29        v.iter().map(|x| usize::from_str(x).unwrap()).collect()
30    }
31
32    /// Returns the associated LocalFormat given a Locale.
33    pub fn from_locale(locale: Locale) -> LocalFormat {
34        use Locale::*;
35
36        match locale {
37            EnUs => LocalFormat {
38                name: "en-us",
39                digit_separator: ',',
40                digit_separator_pattern: "3, 3, 3",
41                exponent_separator: '.',
42            },
43            EnIn => LocalFormat {
44                name: "en-in",
45                digit_separator: ',',
46                digit_separator_pattern: "3, 2, 2",
47                exponent_separator: '.',
48            },
49            EnEu => LocalFormat {
50                name: "en-eu",
51                digit_separator: '.',
52                digit_separator_pattern: "3, 3, 3",
53                exponent_separator: ',',
54            },
55            EnBy => LocalFormat {
56                name: "en-by",
57                digit_separator: ' ',
58                digit_separator_pattern: "3, 3, 3",
59                exponent_separator: ',',
60            },
61        }
62    }
63}