use serde::{Deserialize, Serialize};
use crate::error::{MyIdError, MyIdResult};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct Pinfl(String);
impl Pinfl {
pub const LEN: usize = 14;
pub fn parse(value: impl AsRef<str>) -> MyIdResult<Self> {
let pinfl = value.as_ref().trim();
if pinfl.len() != Self::LEN {
return Err(MyIdError::validation(format!(
"pinfl must be exactly {} digits, got {} chars: {pinfl}",
Self::LEN,
pinfl.len(),
)));
}
if !pinfl.bytes().all(|b| b.is_ascii_digit()) {
return Err(MyIdError::validation(format!(
"pinfl must contain only digits, got: {pinfl}"
)));
}
Ok(Self(pinfl.to_owned()))
}
#[inline]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl AsRef<str> for Pinfl {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for Pinfl {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl TryFrom<String> for Pinfl {
type Error = MyIdError;
fn try_from(value: String) -> MyIdResult<Self> {
Self::parse(value)
}
}
impl From<Pinfl> for String {
fn from(value: Pinfl) -> Self {
value.0
}
}