1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
//! ISO 3166-1 alpha-2 country codes: the two letter codes that identify countries, dependent
//! territories, and special areas of geographical interest.
//!
//! This module provides the validated Rust representation ([`CountryCode`]) together with the
//! parsing, validation, and error types that surround it. It accepts the canonical two letter form
//! (optionally surrounded by whitespace, in any ASCII case), normalizes it, and guarantees that any
//! constructed [`CountryCode`] is a code that ISO 3166-1 officially assigns. There is no partially
//! validated state. If you hold a [`CountryCode`], it is valid.
//!
//! # What this type represents
//!
//! A country code is two uppercase ASCII letters, for example `US`, `BR`, or `GB`. The code
//! identifies a country or territory. This crate stores only the code itself. It does not carry the
//! country name, the alpha-3 code, or the numeric code, and it does not model subdivisions.
//!
//! [`CountryCode`] stores the two characters as normalized uppercase ASCII. It exposes borrowed
//! accessors for the raw bytes ([`CountryCode::as_bytes`]) and for the whole value
//! ([`CountryCode::as_str`]).
//!
//! # Validation rules
//!
//! A country code has no check digit. It is valid exactly when it is one of the codes ISO 3166-1
//! officially assigns. This crate embeds that set as a compile time bitmap. Every fallible
//! constructor runs the same rules, in order, and each maps to one [`CountryCodeError`] variant:
//!
//! 1. Length: after surrounding whitespace is trimmed, the input must contain exactly two
//! characters ([`CountryCodeError::InvalidLength`]). [`CountryCode::parse`] rejects empty input
//! first ([`CountryCodeError::Empty`]).
//! 2. Character class: both positions must be an uppercase ASCII letter
//! ([`CountryCodeError::InvalidCharacter`]).
//! 3. Assignment: the two letters together must be an officially assigned code
//! ([`CountryCodeError::Unassigned`]).
//!
//! Only the assigned codes are recognized. Reserved codes such as `EU` and `UK`, and the user
//! assigned ranges, are not accepted. Codes that were once used and later withdrawn are not
//! accepted either.
//!
//! # Design notes
//!
//! * No invalid state is representable. The only field of [`CountryCode`] is private. Every way to
//! obtain one ([`CountryCode::parse`], [`CountryCode::new`], [`CountryCode::from_bytes`],
//! [`FromStr`], and [`TryFrom<&str>`]) runs full validation. There is no unchecked constructor.
//! * It is zero allocation and `Copy`. [`CountryCode`] is a two byte value that wraps `[u8; 2]`. It
//! works in `no_std` environments. Parsing, validation, and every accessor operate on the stack.
//! The assignment check computes one array index and tests one bit.
//! * Ordering and hashing operate over the raw ASCII bytes. This matches [`str`] ordering on
//! [`CountryCode::as_str`], which is lexicographic and carries no geographic meaning.
//! * It is safe to use as a map or set key. [`CountryCode`] implements [`Eq`] and [`Hash`]
//! consistently with [`PartialEq`], so it works as a `HashMap` or `HashSet` key, and as a
//! `BTreeMap` or `BTreeSet` key, out of the box.
//!
//! # Feature flags
//!
//! The optional integrations are off by default and purely additive. Enabling one never changes the
//! behavior of [`CountryCode::parse`] or the validation rules above:
//!
//! * `serde`: (de)serializes [`CountryCode`] as its two letter string, for example `"US"`.
//! Deserialization re-runs full validation, so an untrusted payload can never produce an invalid
//! [`CountryCode`].
//! * `schemars`: implements `JsonSchema` for [`CountryCode`], describing it as a pattern
//! constrained string (`^[A-Z]{2}$`). The pattern is structural. It cannot express which two
//! letter codes are assigned, so validity is enforced on deserialization. Implies `serde`.
//! * `arbitrary`: implements `Arbitrary` for [`CountryCode`], generating officially assigned codes
//! for fuzz targets.
//! * `proptest`: exposes reusable `proptest` strategies (`ftracker_identifiers::country::proptest`,
//! when this feature is enabled) for generating valid [`CountryCode`] values.
//!
//! # Error handling
//!
//! Every fallible constructor returns [`CountryCodeError`], which is `Clone + PartialEq + Eq` and
//! implements [`core::error::Error`] and [`core::fmt::Display`], so it composes with `?` and with
//! error aggregation crates alike:
//!
//! ```
//! use ftracker_identifiers::{CountryCode, CountryCodeError};
//!
//! match CountryCode::parse("ZZ") {
//! Ok(code) => println!("valid: {code}"),
//! Err(CountryCodeError::Unassigned { code }) => {
//! println!("not assigned: {}{}", code[0], code[1]);
//! }
//! Err(other) => println!("rejected: {other}"),
//! }
//! ```
//!
//! # Examples
//!
//! ```
//! use ftracker_identifiers::CountryCode;
//!
//! let code = CountryCode::parse("us").unwrap(); // lowercase is folded automatically
//! assert_eq!(code.as_str(), "US");
//! assert_eq!(code.as_bytes(), b"US");
//! ```
//!
//! Sorting and deduplicating a batch of codes, for example after importing them from a spreadsheet:
//!
//! ```
//! use ftracker_identifiers::CountryCode;
//!
//! let mut codes: Vec<CountryCode> = ["US", "BR", "US"]
//! .into_iter()
//! .map(|s| CountryCode::parse(s).unwrap())
//! .collect();
//! codes.sort();
//! codes.dedup();
//! assert_eq!(codes.len(), 2);
//! ```
pub use CountryCodeError;
use TryFrom;
use ;
/// A validated ISO 3166-1 alpha-2 country code.
///
/// `CountryCode` is a two byte, `Copy`, allocation free value object. Once constructed, it is
/// guaranteed to be a code that ISO 3166-1 officially assigns. There is no way to get a
/// `CountryCode` that has not passed validation.
///
/// Internally, the code is stored as two raw uppercase ASCII letters (`'A'..='Z'`).
///
/// # Constructing a `CountryCode`
///
/// * [`CountryCode::parse`] and [`CountryCode::new`] accept two character strings, in any ASCII
/// case, trimmed of surrounding whitespace.
/// * [`CountryCode::from_bytes`] accepts exactly two pre normalized uppercase ASCII bytes.
/// * [`FromStr`] and [`TryFrom<&str>`] behave like `parse`, for use in generic code.
///
/// All of them run the same validation and return [`CountryCodeError`] on failure. See the
/// [module level documentation](self) for the validation rules and design rationale.