use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{kind} id {value:?} must match [a-z0-9-]{{1,64}}")]
pub struct IdError {
kind: &'static str,
value: String,
}
fn is_slug(value: &str) -> bool {
(1..=64).contains(&value.len())
&& value
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}
macro_rules! id {
($(#[$meta:meta])* $name:ident, $kind:literal) => {
$(#[$meta])*
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct $name(String);
impl $name {
pub fn parse(value: impl Into<String>) -> Result<Self, IdError> {
let value = value.into();
if is_slug(&value) {
Ok(Self(value))
} else {
Err(IdError { kind: $kind, value })
}
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for $name {
type Error = IdError;
fn try_from(value: String) -> Result<Self, IdError> {
Self::parse(value)
}
}
impl From<$name> for String {
fn from(id: $name) -> String {
id.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
};
}
id!(
AssetId,
"asset"
);
id!(
SliceId,
"slice"
);
id!(
TechnicalUnitId,
"technical unit"
);
id!(
ReserveGroupId,
"reserve group"
);
id!(
PoolId,
"pool"
);
id!(
OwnerId,
"owner"
);
id!(
ProductId,
"product"
);