ham_cats/whisker/
timestamp.rs

1#[derive(Debug, PartialEq, Eq, Clone)]
2pub struct Timestamp(u64);
3
4impl Timestamp {
5    /// Returns none if the given unix timestamp doesn't fit in 5 bytes
6    pub fn new(unix_time: u64) -> Option<Self> {
7        // must fit in 5 bytes
8        if unix_time > (1 << (5 * 8)) - 1 {
9            return None;
10        }
11
12        Some(Self(unix_time))
13    }
14
15    pub fn unix_time(&self) -> u64 {
16        self.0
17    }
18
19    /// Returns none if there is not enough space in the buffer
20    pub fn encode<'a>(&self, buf: &'a mut [u8]) -> Option<&'a [u8]> {
21        if buf.len() < 6 {
22            return None;
23        }
24
25        buf[0] = 5;
26        buf[1..6].copy_from_slice(&self.0.to_le_bytes()[0..5]);
27
28        Some(&buf[0..6])
29    }
30
31    pub fn decode(data: &[u8]) -> Option<Self> {
32        if data.len() < 6 {
33            return None;
34        }
35        if data[0] != 5 {
36            return None;
37        }
38
39        let mut extended_data = [0; 8];
40        extended_data[0..5].copy_from_slice(&data[1..6]);
41
42        Some(Self(u64::from_le_bytes(extended_data)))
43    }
44}