remora/crates/remora-domain/src/id.rs

73 lines
1.8 KiB
Rust

use std::{fmt, str::FromStr};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct OpaqueId(String);
impl OpaqueId {
pub fn parse(value: impl Into<String>) -> Result<Self, IdError> {
let value = value.into();
let mut chars = value.chars();
let Some(first) = chars.next() else {
return Err(IdError);
};
if !(8..=128).contains(&value.len())
|| !first.is_ascii_alphanumeric()
|| !chars.all(|character| {
character.is_ascii_alphanumeric() || matches!(character, '_' | '-')
})
{
return Err(IdError);
}
Ok(Self(value))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for OpaqueId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}
impl FromStr for OpaqueId {
type Err = IdError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
Self::parse(value)
}
}
impl Serialize for OpaqueId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for OpaqueId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Self::parse(String::deserialize(deserializer)?).map_err(D::Error::custom)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct IdError;
impl fmt::Display for IdError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("invalid opaque identifier")
}
}
impl std::error::Error for IdError {}