1#[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#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
30pub enum Warning {
31 ContainsEscapeCodes,
33
34 Decode(json::decode::Warning),
36
37 IncorrectCase,
39
40 InvalidCode,
42
43 InvalidLength,
45
46 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#[derive(Debug)]
84pub(crate) enum CodeSet {
85 Alpha2(Code),
87
88 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 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
170macro_rules! country_codes {
172 [$(($name:ident, $alpha2:literal, $alpha3:literal)),*] => {
173 #[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 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 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 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 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;