use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::error::Error;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Uuid(uuid::Uuid);
impl Uuid {
pub const fn new() -> Self {
Self(uuid::Uuid::nil())
}
pub const fn from_inner(uuid: uuid::Uuid) -> Self {
Self(uuid)
}
pub const fn into_inner(self) -> uuid::Uuid {
self.0
}
}
impl Default for Uuid {
fn default() -> Self {
Self::new()
}
}
impl TryFrom<&str> for Uuid {
type Error = Error;
fn try_from(val: &str) -> Result<Self, Self::Error> {
uuid::Uuid::parse_str(val).map(Self).map_err(Error::from)
}
}
impl TryFrom<String> for Uuid {
type Error = Error;
fn try_from(val: String) -> Result<Self, Self::Error> {
Self::try_from(val.as_str())
}
}
impl From<Uuid> for String {
fn from(val: Uuid) -> Self {
Self::from(&val)
}
}
impl From<&Uuid> for String {
fn from(val: &Uuid) -> Self {
val.0
.hyphenated()
.encode_lower(&mut uuid::Uuid::encode_buffer())
.to_string()
}
}
impl Serialize for Uuid {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
uuid::fmt::Hyphenated::from_uuid(self.0).serialize(s)
}
}
impl<'de> Deserialize<'de> for Uuid {
fn deserialize<D>(d: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error as _;
String::deserialize(d)
.as_deref()
.map_err(|err| D::Error::custom(format!("missing UUID string: {err}")))
.and_then(|u| {
uuid::Uuid::parse_str(u)
.map(Self)
.map_err(|err| D::Error::custom(format!("error parsing UUID: {err}")))
})
}
}
impl std::fmt::Display for Uuid {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", String::from(self))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_uuid() {
let uuid_str = "936da01f-9abd-4d9d-80c7-02af85c822a8";
let uuid_json = serde_json::to_string(&uuid_str).unwrap();
let inner_uuid = uuid::Uuid::parse_str(uuid_str).unwrap();
let uuid = Uuid::from_inner(inner_uuid);
assert_eq!(Uuid::try_from(uuid_str), Ok(uuid));
assert_eq!(Uuid::try_from(uuid_str.to_string()), Ok(uuid));
assert_eq!(uuid.into_inner(), inner_uuid);
assert_eq!(format!("{uuid}").as_str(), uuid_str);
assert_eq!(serde_json::to_string(&uuid).unwrap(), uuid_json);
assert_eq!(serde_json::from_str::<Uuid>(&uuid_json).unwrap(), uuid);
}
}