ssp/types/encryption/
count.rs

1use crate::{std::fmt, tuple_struct};
2
3tuple_struct!(
4    SequenceCount,
5    u32,
6    r"
7 A 4 byte unsigned integer representing the sequence count of encrypted packages.
8
9 Encrypted packets are sequenced using this count; this is reset to 0 after a power cycle,
10 and each time the encryption keys are successfully negotiated.
11
12 The count is incremented by the host and device each time they successfully encrypt and transmit a packet, and each time a received packet is successfully decrypted.
13
14 After a packet is successfully decrypted the COUNT in the packet should be compared with the internal COUNT, if they do not match then the packet is discarded.
15"
16);
17
18impl From<&[u8]> for SequenceCount {
19    fn from(val: &[u8]) -> Self {
20        match val.len() {
21            0 => Self::new(),
22            1 => u32::from_le_bytes([val[0], 0, 0, 0]).into(),
23            2 => u32::from_le_bytes([val[0], val[1], 0, 0]).into(),
24            3 => u32::from_le_bytes([val[0], val[1], val[2], 0]).into(),
25            _ => u32::from_le_bytes([val[0], val[1], val[2], val[3]]).into(),
26        }
27    }
28}
29
30impl<const N: usize> From<[u8; N]> for SequenceCount {
31    fn from(val: [u8; N]) -> Self {
32        val.as_ref().into()
33    }
34}
35
36impl<const N: usize> From<&[u8; N]> for SequenceCount {
37    fn from(val: &[u8; N]) -> Self {
38        val.as_ref().into()
39    }
40}
41
42impl fmt::Display for SequenceCount {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(f, "{}", self.as_inner())
45    }
46}