pub type Uuid = [u8; 16];
pub fn try_uuid(bytes: &[u8]) -> Result<Uuid, UuidLengthError> {
bytes.try_into().map_err(|_| UuidLengthError(bytes.len()))
}
#[derive(Debug)]
pub struct UuidLengthError(pub usize);
impl std::fmt::Display for UuidLengthError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "expected 16-byte UUID, got {} bytes", self.0)
}
}
impl std::error::Error for UuidLengthError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn try_uuid_accepts_exactly_16_bytes() {
assert_eq!(try_uuid(&[7u8; 16]).unwrap(), [7u8; 16]);
assert_eq!(try_uuid(&[0u8; 15]).unwrap_err().0, 15);
assert_eq!(try_uuid(&[0u8; 17]).unwrap_err().0, 17);
}
}