use crate::raw;
use crate::{ErrorKind, Result};
use core::fmt;
use uuid as uuid_crate;
pub struct Uuid {
raw: raw::TEEC_UUID,
}
impl Uuid {
pub fn parse_str(input: &str) -> Result<Uuid> {
let uuid = uuid_crate::Uuid::parse_str(input).map_err(|_| ErrorKind::BadFormat)?;
let (time_low, time_mid, time_hi_and_version, clock_seq_and_node) = uuid.as_fields();
Ok(Self::new_raw(
time_low,
time_mid,
time_hi_and_version,
*clock_seq_and_node,
))
}
pub fn from_bytes(bytes: [u8; 16]) -> Uuid {
let uuid = uuid_crate::Uuid::from_bytes(bytes);
let (time_low, time_mid, time_hi_and_version, clock_seq_and_node) = uuid.as_fields();
Self::new_raw(time_low, time_mid, time_hi_and_version, *clock_seq_and_node)
}
pub fn from_slice(b: &[u8]) -> Result<Uuid> {
let uuid = uuid_crate::Uuid::from_slice(b).map_err(|_| ErrorKind::BadFormat)?;
let (time_low, time_mid, time_hi_and_version, clock_seq_and_node) = uuid.as_fields();
Ok(Self::new_raw(
time_low,
time_mid,
time_hi_and_version,
*clock_seq_and_node,
))
}
pub fn new_raw(
time_low: u32,
time_mid: u16,
time_hi_and_version: u16,
clock_seq_and_nod: [u8; 8],
) -> Uuid {
let raw_uuid = raw::TEEC_UUID {
timeLow: time_low,
timeMid: time_mid,
timeHiAndVersion: time_hi_and_version,
clockSeqAndNode: clock_seq_and_nod,
};
Self { raw: raw_uuid }
}
pub fn as_raw_ptr(&self) -> *const raw::TEEC_UUID {
&self.raw
}
}
impl Clone for Uuid {
fn clone(&self) -> Self {
Self::new_raw(
self.raw.timeLow,
self.raw.timeMid,
self.raw.timeHiAndVersion,
self.raw.clockSeqAndNode,
)
}
}
impl fmt::Display for Uuid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{:08x}-{:04x}-{:04x}-{}-{}",
self.raw.timeLow,
self.raw.timeMid,
self.raw.timeHiAndVersion,
hex::encode(&self.raw.clockSeqAndNode[0..2]),
hex::encode(&self.raw.clockSeqAndNode[2..8]),
)
}
}
#[cfg(test)]
mod tests {
use super::Uuid;
#[test]
fn test_to_string() {
let uuids = [
"00173366-2aca-49bc-beb7-10c975e6131e", "11173366-0aca-49bc-beb7-10c975e6131e", "11173366-2aca-09bc-beb7-10c975e6131e", "11173366-2aca-19bc-beb7-10c975e6131e", ];
for origin in uuids.iter() {
let uuid = Uuid::parse_str(origin).expect("Test UUID should be valid");
let formatted = uuid.to_string();
assert_eq!(*origin, formatted);
}
}
}