use crate::errors::ValidationError;
use crate::traits::ValueObject;
pub type CountryCodeInput = String;
pub type CountryCodeOutput = String;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct CountryCode(String);
impl ValueObject for CountryCode {
type Input = CountryCodeInput;
type Output = CountryCodeOutput;
type Error = ValidationError;
fn new(value: Self::Input) -> Result<Self, Self::Error> {
let normalised = value.trim().to_uppercase();
let valid = normalised.len() == 2 && normalised.chars().all(|c| c.is_ascii_alphabetic());
if !valid {
return Err(ValidationError::invalid("CountryCode", &normalised));
}
Ok(Self(normalised))
}
fn value(&self) -> &Self::Output {
&self.0
}
fn into_inner(self) -> Self::Input {
self.0
}
}
impl TryFrom<&str> for CountryCode {
type Error = ValidationError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value.to_owned())
}
}
impl std::fmt::Display for CountryCode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalises_to_uppercase() {
let c = CountryCode::new("cz".into()).unwrap();
assert_eq!(c.value(), "CZ");
}
#[test]
fn trims_surrounding_whitespace() {
let c = CountryCode::new(" de ".into()).unwrap();
assert_eq!(c.value(), "DE");
}
#[test]
fn rejects_three_letter_code() {
assert!(CountryCode::new("USA".into()).is_err());
}
#[test]
fn rejects_single_letter() {
assert!(CountryCode::new("C".into()).is_err());
}
#[test]
fn rejects_digit_in_code() {
assert!(CountryCode::new("C1".into()).is_err());
}
#[test]
fn rejects_empty_string() {
assert!(CountryCode::new(String::new()).is_err());
}
#[test]
fn equal_after_normalisation() {
let a = CountryCode::new("cz".into()).unwrap();
let b = CountryCode::new("CZ".into()).unwrap();
assert_eq!(a, b);
}
#[test]
fn try_from_str() {
let c: CountryCode = "DE".try_into().unwrap();
assert_eq!(c.value(), "DE");
}
}