uuid.rs 870 Bytes
use std::{fmt::Display, convert::TryFrom};

use crate::error::Error;

#[derive(Clone,Copy,Debug)]
pub struct Uuid(pub uuid::Uuid);

impl Display for Uuid {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

macro_rules! ns {
    ($n:expr) => {
        uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_DNS, $n.as_bytes())
    }
}

impl Uuid {
    pub fn get(ns: &str, buf: &mut [u8]) -> Self {
        Self(uuid::Uuid::new_v5(&ns!(ns), buf))
    }
}

impl TryFrom<&[u8]> for Uuid {
    type Error = Error;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        Ok(Self(uuid::Uuid::from_slice(value)?))
    }
}

impl TryFrom<Vec<u8>> for Uuid {
    type Error = Error;

    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        Ok(Self(uuid::Uuid::from_slice(value.as_slice())?))
    }
}