statime_wire/common/
clock_identity.rs1use crate::Error;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord, Hash)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12pub struct ClockIdentity(pub [u8; 8]);
13
14impl ClockIdentity {
15 #[must_use]
26 pub fn from_mac_address(addr: [u8; 6]) -> Self {
27 let mut this = Self([0; 8]);
28
29 this.0[0..6].copy_from_slice(&addr);
30
31 this
32 }
33
34 #[allow(
39 clippy::missing_panics_doc,
40 reason = "Clippy can't see copy_from_slice will never panic here"
41 )]
42 pub fn serialize(self, buffer: &mut [u8]) -> Result<(), Error> {
43 buffer
44 .get_mut(0..self.0.len())
45 .ok_or(Error::BufferTooShort)?
46 .copy_from_slice(&self.0);
47 Ok(())
48 }
49
50 #[allow(
55 clippy::missing_panics_doc,
56 reason = "Clippy can't tell the try_into will never fail"
57 )]
58 pub fn deserialize(buffer: &[u8]) -> Result<Self, Error> {
59 Ok(Self(
60 buffer
61 .get(0..8)
62 .ok_or(Error::BufferTooShort)?
63 .try_into()
64 .unwrap(),
65 ))
66 }
67}
68
69#[cfg(feature = "std")]
70impl core::fmt::Display for ClockIdentity {
71 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
72 for (i, val) in self.0.iter().enumerate() {
73 if i != 0 {
74 write!(f, ":")?;
75 }
76
77 write!(f, "{val:02x}")?;
78 }
79
80 Ok(())
81 }
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 #[test]
89 fn timestamp_wireformat() {
90 let representations = [(
91 [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08u8],
92 ClockIdentity([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]),
93 )];
94
95 for (byte_representation, object_representation) in representations {
96 let mut serialization_buffer = [0; 8];
98 object_representation
99 .serialize(&mut serialization_buffer)
100 .unwrap();
101 assert_eq!(serialization_buffer, byte_representation);
102
103 let deserialized_data = ClockIdentity::deserialize(&byte_representation).unwrap();
105 assert_eq!(deserialized_data, object_representation);
106 }
107 }
108
109 #[test]
110 fn from_mac() {
111 let mac = [1, 2, 3, 4, 5, 6];
112 let id = ClockIdentity::from_mac_address(mac);
113 assert_eq!(id, ClockIdentity([1, 2, 3, 4, 5, 6, 0, 0]));
114 }
115}