Skip to main content

ocpi_tariffs/
currency.rs

1//! An ISO 4217 currency code.
2
3#[cfg(test)]
4pub(crate) mod test;
5
6#[cfg(test)]
7mod test_from_schema;
8
9mod data;
10
11use std::fmt;
12
13#[doc(inline)]
14pub use data::Code;
15
16use crate::{
17    LowerSchema, from_warning_all, json,
18    schema::{self, HasElement as _},
19    warning,
20};
21
22/// The warnings that can happen when parsing or linting a currency code.
23#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
24pub enum Warning {
25    /// The currency field does not require char escape codes.
26    ContainsEscapeCodes,
27
28    /// The field at the path could not be decoded.
29    Decode(json::decode::Warning),
30
31    /// The `currency` is not written in upper case, which `ISO 4217` calls for.
32    IncorrectCase,
33
34    /// The `currency` is not a valid `ISO 4217` currency code.
35    InvalidCode,
36
37    /// The `currency` is not a valid `ISO 4217` currency code: it should be 3 chars.
38    InvalidLength,
39
40    /// The `currency` is not a valid `ISO 4217` currency code because it's a test code.
41    InvalidCodeXTS,
42
43    /// The `currency` is not a valid `ISO 4217` currency code because it's a code for `no-currency`.
44    InvalidCodeXXX,
45}
46
47impl fmt::Display for Warning {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::ContainsEscapeCodes => write!(
51                f,
52                "The currency-code contains escape-codes but it does not need them.",
53            ),
54            Self::Decode(warning) => fmt::Display::fmt(warning, f),
55            Self::IncorrectCase => write!(
56                f,
57                "The currency-code follows the ISO 4217 standard which states: the chars should be uppercase.",
58            ),
59            Self::InvalidCode => {
60                write!(f, "The currency-code is not a valid ISO 4217 code.")
61            }
62            Self::InvalidLength => write!(
63                f,
64                "The currency-code follows the ISO 4217 standard which states: the code should be three chars."
65            ),
66            Self::InvalidCodeXTS => write!(
67                f,
68                "The currency-code is `XTS`. This is a code for testing only",
69            ),
70            Self::InvalidCodeXXX => write!(
71                f,
72                "The currency-code is `XXX`. This means there is no currency",
73            ),
74        }
75    }
76}
77
78impl crate::Warning for Warning {
79    fn id(&self) -> warning::Id {
80        match self {
81            Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
82            Self::Decode(kind) => kind.id(),
83            Self::IncorrectCase => warning::Id::from_static("incorrect_case"),
84            Self::InvalidCode => warning::Id::from_static("invalid_code"),
85            Self::InvalidLength => warning::Id::from_static("invalid_length"),
86            Self::InvalidCodeXTS => warning::Id::from_static("invalid_code_xts"),
87            Self::InvalidCodeXXX => warning::Id::from_static("invalid_code_xxx"),
88        }
89    }
90}
91
92from_warning_all!(json::decode::Warning => Warning::Decode);
93
94impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for Code {
95    type Warning = Warning;
96
97    fn lower_schema(
98        source: &schema::Str<'buf>,
99        warnings: &mut dyn warning::Gather<Warning>,
100    ) -> Result<Self, warning::Error<Warning>> {
101        let elem = source.element();
102
103        // The schema confirmed the value is a string, so there is no kind check; its
104        // content is read directly.
105        let pending_str = source
106            .value()
107            .has_escapes(elem, &mut warning::Converting::new(warnings));
108
109        let s = match pending_str {
110            json::PendingStr::NoEscapes(s) => s,
111            json::PendingStr::HasEscapes => {
112                return Err(warning::Error::new(elem, Warning::ContainsEscapeCodes));
113            }
114        };
115
116        let bytes = s.as_bytes();
117
118        // ISO 4217 is expected to be 3 chars enclosed in quotes.
119        let [a, b, c] = bytes else {
120            return Err(warning::Error::new(elem, Warning::InvalidLength));
121        };
122
123        let triplet: [u8; 3] = [
124            a.to_ascii_uppercase(),
125            b.to_ascii_uppercase(),
126            c.to_ascii_uppercase(),
127        ];
128
129        if triplet != bytes {
130            warnings.insert(elem, Warning::IncorrectCase);
131        }
132
133        let Some(code) = Code::from_alpha_3(triplet) else {
134            return Err(warning::Error::new(elem, Warning::InvalidCode));
135        };
136
137        if matches!(code, Code::Xts) {
138            warnings.insert(elem, Warning::InvalidCodeXTS);
139        } else if matches!(code, Code::Xxx) {
140            warnings.insert(elem, Warning::InvalidCodeXXX);
141        }
142
143        Ok(code)
144    }
145}
146
147impl fmt::Display for Code {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        f.write_str(self.into_str())
150    }
151}
152
153/// Macro to specify a list of valid ISO 4217 alpha-3 currency codes.
154macro_rules! currency_codes {
155    [$(($name:ident, $alpha3:literal, $symbol:literal)),*] => {
156        /// An ISO 4217 currency code.
157        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash,  PartialOrd, Ord)]
158        #[expect(missing_docs, reason = "Each variant should technically have a comment but each variant is simply the currency code.")]
159        pub enum Code {
160            $($name),*
161        }
162
163        impl Code {
164            /// Try creating a `Code` from three upper ASCII bytes.
165            pub(super) const fn from_alpha_3(code: [u8; 3]) -> Option<Self> {
166                match &code {
167                    $($alpha3 => Some(Self::$name),)*
168                    _ => None
169                }
170            }
171
172            /// Return enum as three byte uppercase &str.
173            pub fn into_str(self) -> &'static str {
174                let bytes = match self {
175                    $(Self::$name => $alpha3),*
176                };
177                std::str::from_utf8(bytes).expect("The currency code bytes are known to be valid UTF8 as they are embedded into the binary")
178            }
179
180            /// Return a str symbol of the [Code].
181            pub fn into_symbol(self) -> &'static str {
182                match self {
183                    $(Self::$name => $symbol),*
184                }
185            }
186        }
187    };
188}
189
190pub(crate) use currency_codes;