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