use serde::{Deserialize, Serialize};
use super::super::check_digit::{Gs1KeyCheck, check_gs1_key};
use super::error::GtinError;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Gtin(String);
impl Gtin {
pub fn parse(s: &str) -> Result<Self, GtinError> {
if !matches!(s.len(), 8 | 12 | 13 | 14) || !s.bytes().all(|b| b.is_ascii_digit()) {
return Err(GtinError::InvalidFormat(s.to_owned()));
}
let canonical = format!("{s:0>14}");
match check_gs1_key(&canonical, 14) {
Ok(()) => Ok(Self(canonical)),
Err(Gs1KeyCheck::InvalidFormat) => Err(GtinError::InvalidFormat(s.to_owned())),
Err(Gs1KeyCheck::InvalidCheckDigit { expected, actual }) => {
Err(GtinError::InvalidCheckDigit {
gtin: s.to_owned(),
expected,
actual,
})
}
}
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for Gtin {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl PartialEq<str> for Gtin {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl Serialize for Gtin {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for Gtin {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
Self::parse(&s).map_err(serde::de::Error::custom)
}
}