statime/datastructures/common/
port_identity.rs

1use super::clock_identity::ClockIdentity;
2use crate::datastructures::{WireFormat, WireFormatError};
3
4/// Identity of a single port of a PTP instance
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7pub struct PortIdentity {
8    /// Identity of the clock this port is part of
9    pub clock_identity: ClockIdentity,
10    /// Index of the port (1-based).
11    pub port_number: u16,
12}
13
14impl WireFormat for PortIdentity {
15    fn serialize(&self, buffer: &mut [u8]) -> Result<(), WireFormatError> {
16        self.clock_identity.serialize(&mut buffer[0..8])?;
17        buffer[8..10].copy_from_slice(&self.port_number.to_be_bytes());
18        Ok(())
19    }
20
21    fn deserialize(buffer: &[u8]) -> Result<Self, WireFormatError> {
22        Ok(Self {
23            clock_identity: ClockIdentity::deserialize(&buffer[0..8])?,
24            port_number: u16::from_be_bytes(buffer[8..10].try_into().unwrap()),
25        })
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32
33    #[test]
34    fn timestamp_wireformat() {
35        let representations = [
36            (
37                [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x15, 0xb3u8],
38                PortIdentity {
39                    clock_identity: ClockIdentity([0, 1, 2, 3, 4, 5, 6, 7]),
40                    port_number: 5555,
41                },
42            ),
43            (
44                [0x40, 0x6d, 0x16, 0x36, 0xc4, 0x24, 0x0e, 0x38, 0x04, 0xd2u8],
45                PortIdentity {
46                    clock_identity: ClockIdentity([64, 109, 22, 54, 196, 36, 14, 56]),
47                    port_number: 1234,
48                },
49            ),
50        ];
51
52        for (byte_representation, object_representation) in representations {
53            // Test the serialization output
54            let mut serialization_buffer = [0; 10];
55            object_representation
56                .serialize(&mut serialization_buffer)
57                .unwrap();
58            assert_eq!(serialization_buffer, byte_representation);
59
60            // Test the deserialization output
61            let deserialized_data = PortIdentity::deserialize(&byte_representation).unwrap();
62            assert_eq!(deserialized_data, object_representation);
63        }
64    }
65}