mctp_rs/
mctp_sequence_number.rs

1use bit_register::{NumBytes, TryFromBits, TryIntoBits};
2
3#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
4#[cfg_attr(feature = "defmt", derive(defmt::Format))]
5pub struct MctpSequenceNumber(u8);
6
7impl MctpSequenceNumber {
8    const MAX: u8 = 4;
9
10    pub fn new(value: u8) -> Self {
11        Self(value)
12    }
13
14    pub fn inc(&mut self) -> Self {
15        *self = self.next();
16        *self
17    }
18
19    pub fn next(&self) -> Self {
20        Self((self.0 + 1) % Self::MAX)
21    }
22}
23
24impl NumBytes for MctpSequenceNumber {
25    const NUM_BYTES: usize = 1;
26}
27
28impl TryIntoBits<u32> for MctpSequenceNumber {
29    fn try_into_bits(self) -> Result<u32, &'static str> {
30        Ok(self.0 as u32)
31    }
32}
33
34impl TryFromBits<u32> for MctpSequenceNumber {
35    fn try_from_bits(bits: u32) -> Result<Self, &'static str> {
36        if bits >= Self::MAX as u32 {
37            Err("sequence number out of range")
38        } else {
39            Ok(Self(bits as u8))
40        }
41    }
42}