use crate::errors::ValidationError;
use crate::traits::{PrimitiveValue, ValueObject};
pub type CountryCodeInput = String;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct CountryCode(String);
impl ValueObject for CountryCode {
type Input = CountryCodeInput;
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 into_inner(self) -> Self::Input {
self.0
}
}
impl PrimitiveValue for CountryCode {
type Primitive = String;
fn value(&self) -> &String {
&self.0
}
}
impl TryFrom<String> for CountryCode {
type Error = ValidationError;
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::new(s)
}
}
#[cfg(feature = "serde")]
impl From<CountryCode> for String {
fn from(v: CountryCode) -> String {
v.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");
}
#[cfg(feature = "serde")]
#[test]
fn serde_roundtrip() {
let v = CountryCode::try_from("CZ").unwrap();
let json = serde_json::to_string(&v).unwrap();
let back: CountryCode = serde_json::from_str(&json).unwrap();
assert_eq!(v, back);
}
#[cfg(feature = "serde")]
#[test]
fn serde_deserialize_validates() {
let result: Result<CountryCode, _> = serde_json::from_str("\"__invalid__\"");
assert!(result.is_err());
}
}