1use std::fmt;
4
5use super::{Error, Result};
6
7#[derive(Debug, Clone, PartialEq, Eq, Hash)]
9pub struct Guid([u8; 16]);
10
11impl Guid {
12 pub fn new(bytes: [u8; 16]) -> Self {
14 Guid(bytes)
15 }
16
17 pub fn as_bytes(&self) -> &[u8; 16] {
19 &self.0
20 }
21}
22
23impl fmt::Display for Guid {
24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
25 write!(f, "{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
26 self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5], self.0[6], self.0[7],
27 self.0[8], self.0[9], self.0[10], self.0[11], self.0[12], self.0[13], self.0[14], self.0[15])
28 }
29}
30
31impl TryFrom<&str> for Guid {
32 type Error = Error;
33
34 fn try_from(s: &str) -> Result<Self> {
35 if s.len() != 32 {
36 return Err(Error::InvalidValue("guid".into()));
37 }
38
39 let mut bytes = [0u8; 16];
40 for (i, chunk) in s.as_bytes().chunks(2).enumerate() {
41 bytes[i] = u8::from_str_radix(std::str::from_utf8(chunk).unwrap(), 16)
42 .map_err(|_| Error::InvalidValue("guid".into()))?;
43 }
44
45 Ok(Guid(bytes))
46 }
47}