Skip to main content

ftracker_identifiers/country/
error.rs

1use core::fmt;
2
3/// The set of reasons a country code string can fail validation.
4///
5/// Every fallible constructor of [`CountryCode`](super::CountryCode) returns this type. A country
6/// code carries no checksum. Its validity is defined by membership in the officially assigned ISO
7/// 3166-1 alpha-2 set, so beyond the structural checks there is one assignment failure mode
8/// ([`CountryCodeError::Unassigned`]). Each variant maps to a single, specific failure, so callers
9/// can react programmatically rather than parsing a message.
10#[non_exhaustive]
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum CountryCodeError {
13    /// The input was an empty string.
14    Empty,
15
16    /// After trimming surrounding whitespace, the input did not contain exactly two characters.
17    InvalidLength {
18        /// The number of characters found after trimming.
19        found: usize,
20    },
21
22    /// A character outside `A` to `Z` was found at a given position. Every position of a country
23    /// code is an uppercase ASCII letter.
24    InvalidCharacter {
25        /// The offending character, as originally provided (before case folding).
26        character: char,
27        /// The 1 indexed position within the two characters.
28        position: u8,
29    },
30
31    /// The two letters are well formed but are not a code that ISO 3166-1 officially assigns.
32    Unassigned {
33        /// The offending code, as two uppercase letters.
34        code: [char; 2],
35    },
36}
37
38impl fmt::Display for CountryCodeError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            CountryCodeError::Empty => f.write_str("country code input is empty"),
42            CountryCodeError::InvalidLength { found } => {
43                write!(
44                    f,
45                    "country code must contain exactly 2 characters, found {found}"
46                )
47            }
48            CountryCodeError::InvalidCharacter {
49                character,
50                position,
51            } => write!(
52                f,
53                "invalid character '{character}' at position {position} of 2: expected an uppercase letter (A to Z)"
54            ),
55            CountryCodeError::Unassigned { code } => write!(
56                f,
57                "'{}{}' is not an officially assigned ISO 3166-1 alpha-2 code",
58                code[0], code[1]
59            ),
60        }
61    }
62}
63
64impl core::error::Error for CountryCodeError {}