Skip to main content

statime_wire/common/
clock_identity.rs

1use crate::Error;
2
3/// The identity of a PTP node.
4///
5/// All ptp clocks in a network need a unique clock identity. A common approach
6/// is to use a mac address of the device to generate a unique identifier (see
7/// [`from_mac_address`](`Self::from_mac_address`)).
8///
9/// For more details, see *IEEE1588-2019 section 7.5.2.2.2*.
10#[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    /// Create a [`ClockIdentity`] from a mac address.
16    ///
17    /// Fills the first six bytes with the mac address and the rest with zeroes.
18    ///
19    /// # Example
20    /// ```
21    /// # use statime_wire::ClockIdentity;
22    /// let id = ClockIdentity::from_mac_address([0xA, 0xB, 0xC, 0xD, 0xE, 0xF]);
23    /// assert_eq!(id.0, [0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x0, 0x0]);
24    /// ```
25    #[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    /// Serialize a clock identity to a buffer of 8 bytes
35    ///
36    /// # Errors
37    /// Fails when the provided buffer is of insufficient length.
38    #[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    /// Deserialize a clock identity from a buffer of 8 bytes
51    ///
52    /// # Errors
53    /// Fails when the provided buffer is too short.
54    #[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            // Test the serialization output
97            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            // Test the deserialization output
104            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}