use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct DepartmentId(String);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DepartmentIdError {
Empty,
TooLong {
length: usize,
},
}
impl std::fmt::Display for DepartmentIdError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
DepartmentIdError::Empty => write!(f, "department identifier must be non-empty"),
DepartmentIdError::TooLong { length } => {
write!(f, "department identifier length {length} exceeds maximum 128 characters")
}
}
}
}
impl std::error::Error for DepartmentIdError {}
impl DepartmentId {
pub const MAX_LEN: usize = 128;
pub fn new(value: impl Into<String>) -> Result<Self, DepartmentIdError> {
let value = value.into();
if value.is_empty() {
return Err(DepartmentIdError::Empty);
}
if value.len() > Self::MAX_LEN {
return Err(DepartmentIdError::TooLong { length: value.len() });
}
Ok(DepartmentId(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl Display for DepartmentId {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for DepartmentId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
DepartmentId::new(s).map_err(serde::de::Error::custom)
}
}