Skip to main content

ocpi_tariffs/
country.rs

1//! An `ISO 3166-1` country code.
2//!
3//! Use `CodeSet` to parse a `Code` from JSON.
4
5#[cfg(test)]
6pub(crate) mod test;
7
8#[cfg(test)]
9mod test_from_schema;
10
11mod data;
12
13use std::fmt;
14
15#[doc(inline)]
16pub use data::Code;
17
18use crate::{
19    LowerSchema, json,
20    schema::{self, HasElement as _},
21    warning,
22};
23
24const RESERVED_PREFIX: u8 = b'x';
25const ALPHA_2_LEN: usize = 2;
26const ALPHA_3_LEN: usize = 3;
27
28/// The warnings that happen when reading a country code.
29#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
30pub enum Warning {
31    /// Neither the timezone or country field require char escape codes.
32    ContainsEscapeCodes,
33
34    /// The field at the path could not be decoded.
35    Decode(json::decode::Warning),
36
37    /// The `country` is not written in upper case, which `ISO 3166-1` calls for.
38    IncorrectCase,
39
40    /// The `country` is not a valid `ISO 3166-1` country code.
41    InvalidCode,
42
43    /// The `country` is not a valid `ISO 3166-1` country code because it's not 2 or 3 chars in length.
44    InvalidLength,
45
46    /// The `country` begins with `X`, which `ISO 3166-1` reserves.
47    ///
48    /// Reported rather than refused, because whether the code is assigned is
49    /// `InvalidCode`'s to decide. The prefix is tested directly rather than by lookup: a table of
50    /// assigned codes shows that an `X` code is unassigned, not that the standard reserves it.
51    InvalidReserved,
52}
53
54impl fmt::Display for Warning {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match self {
57            Self::ContainsEscapeCodes => f.write_str("The value contains escape codes but it does not need them"),
58            Self::Decode(warning) => fmt::Display::fmt(warning, f),
59            Self::IncorrectCase => f.write_str("The country-code follows the ISO 3166-1 standard which states: the chars should be uppercase."),
60            Self::InvalidCode => f.write_str("The country-code is not a valid ISO 3166-1 code."),
61            Self::InvalidLength => f.write_str("The country-code follows the ISO 3166-1 which states that the code should be 2 or 3 chars in length."),
62            Self::InvalidReserved => f.write_str("The country-code follows the ISO 3166-1 standard which states: all codes beginning with 'X' are reserved."),
63        }
64    }
65}
66
67impl crate::Warning for Warning {
68    fn id(&self) -> warning::Id {
69        match self {
70            Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
71            Self::Decode(kind) => kind.id(),
72            Self::IncorrectCase => warning::Id::from_static("incorrect_case"),
73            Self::InvalidCode => warning::Id::from_static("invalid_code"),
74            Self::InvalidLength => warning::Id::from_static("invalid_length"),
75            Self::InvalidReserved => warning::Id::from_static("invalid_reserved"),
76        }
77    }
78}
79
80/// An alpha-2 or alpha-3 `Code`.
81///
82/// The caller can decide if they want to warn or fail if the wrong variant is parsed.
83#[derive(Debug)]
84pub(crate) enum CodeSet {
85    /// An alpha-2 country code was parsed.
86    Alpha2(Code),
87
88    /// An alpha-3 country code was parsed.
89    Alpha3(Code),
90}
91
92impl From<json::decode::Warning> for Warning {
93    fn from(warn_kind: json::decode::Warning) -> Self {
94        Self::Decode(warn_kind)
95    }
96}
97
98impl<'buf> LowerSchema<'buf, schema::Str<'buf>> for CodeSet {
99    type Warning = Warning;
100
101    fn lower_schema(
102        source: &schema::Str<'buf>,
103        warnings: &mut dyn warning::Gather<Warning>,
104    ) -> Result<Self, warning::Error<Warning>> {
105        let elem = source.element();
106
107        // The schema confirmed the value is a string, so there is no kind check; its
108        // content is read directly.
109        let pending_str = source
110            .value()
111            .has_escapes(elem, &mut warning::Converting::new(warnings));
112
113        let s = match pending_str {
114            json::PendingStr::NoEscapes(s) => s,
115            json::PendingStr::HasEscapes => {
116                return Err(warning::Error::new(elem, Warning::ContainsEscapeCodes));
117            }
118        };
119
120        let bytes = s.as_bytes();
121
122        if let [a, b, c] = bytes {
123            let triplet: [u8; ALPHA_3_LEN] = [
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            if a.eq_ignore_ascii_case(&RESERVED_PREFIX) {
134                warnings.insert(elem, Warning::InvalidReserved);
135            }
136
137            let Some(code) = Code::from_alpha_3(triplet) else {
138                return Err(warning::Error::new(elem, Warning::InvalidCode));
139            };
140
141            Ok(CodeSet::Alpha3(code))
142        } else if let [a, b] = bytes {
143            let pair: [u8; ALPHA_2_LEN] = [a.to_ascii_uppercase(), b.to_ascii_uppercase()];
144
145            if pair != bytes {
146                warnings.insert(elem, Warning::IncorrectCase);
147            }
148
149            if a.eq_ignore_ascii_case(&RESERVED_PREFIX) {
150                warnings.insert(elem, Warning::InvalidReserved);
151            }
152
153            let Some(code) = Code::from_alpha_2(pair) else {
154                return Err(warning::Error::new(elem, Warning::InvalidCode));
155            };
156
157            Ok(CodeSet::Alpha2(code))
158        } else {
159            Err(warning::Error::new(elem, Warning::InvalidLength))
160        }
161    }
162}
163
164impl fmt::Display for Code {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.write_str(self.into_alpha_2_str())
167    }
168}
169
170/// Macro to specify a list of valid `ISO 3166-1` `alpha-2` and `alpha-3` country codes strings.
171macro_rules! country_codes {
172    [$(($name:ident, $alpha2:literal, $alpha3:literal)),*] => {
173        /// An `ISO 3166-1` `alpha-2` country code.
174        ///
175        /// The impl is designed to be converted from `json::RawValue`.
176        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash,  PartialOrd, Ord)]
177        #[expect(missing_docs, reason = "Each variant should technically have a comment but each variant is simply the country code.")]
178        pub enum Code {
179            $($name),*
180        }
181
182        impl Code {
183            /// Try creating a `Code` from two upper ASCII bytes.
184            pub(super) const fn from_alpha_2(code: [u8; 2]) -> Option<Self> {
185                match &code {
186                    $($alpha2 => Some(Self::$name),)*
187                    _ => None
188                }
189            }
190
191            /// Try creating a `Code` from three upper ASCII bytes.
192            pub(super) const fn from_alpha_3(code: [u8; 3]) -> Option<Self> {
193                match &code {
194                    $($alpha3 => Some(Self::$name),)*
195                    _ => None
196                }
197            }
198
199            /// Return enum as two byte uppercase `&str`.
200            pub fn into_alpha_2_str(self) -> &'static str {
201                let bytes = match self {
202                    $(Self::$name => $alpha2),*
203                };
204                std::str::from_utf8(bytes).expect("The country code bytes are known to be valid UTF8 as they are embedded into the binary")
205            }
206
207            /// Return enum as three byte uppercase `&str`.
208            pub fn into_alpha_3_str(self) -> &'static str {
209                let bytes = match self {
210                    $(Self::$name => $alpha3),*
211                };
212                std::str::from_utf8(bytes).expect("The country code bytes are known to be valid UTF8 as they are embedded into the binary")
213            }
214        }
215    };
216}
217
218pub(crate) use country_codes;