1
 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//! Forward proticol v1 version of high accuracy time representation.

use time::Tm;
use serde::ser::{Serialize, Serializer};
use byteorder::{BigEndian, WriteBytesExt};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EventTime {
    time: Tm,
}

impl EventTime {
    pub fn new(time: Tm) -> EventTime {
        EventTime { time: time }
    }

    pub fn get_time(&self) -> &Tm {
        &self.time
    }
}

impl Serialize for EventTime {
    // The signature of a serialize_with function must follow the pattern:
    //
    //    fn serialize<S>(&T, S) -> Result<S::Ok, S::Error> where S: Serializer
    //
    // although it may also be generic over the input types T.
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::Error;
        let mut buf = vec![];
        buf.write_u8(0xd7).map_err(Error::custom)?;
        buf.write_u8(0x00).map_err(Error::custom)?;
        buf.write_i32::<BigEndian>(self.clone().time.clone().to_timespec().sec as i32)
            .map_err(Error::custom)?;
        buf.write_i32::<BigEndian>(self.clone().time.clone().to_timespec().nsec as i32)
            .map_err(Error::custom)?;
        serializer.serialize_bytes(&buf)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use time;
    use time::Timespec;
    use rmp_serde::encode::Serializer;

    #[test]
    fn test_event_time_format() {
        let timespec = Timespec::new(1494245571, 0);
        let time = time::at(timespec);
        let event_time = EventTime::new(time);
        let mut buf = vec![];
        let _ = event_time
            .serialize(&mut Serializer::new(&mut buf))
            .unwrap();
        assert_eq!(
            vec![0xc4, 0x0a, 0xd7, 0x00, 0x59, 0x10, 0x60, 0xc3, 0x00, 0x00, 0x00, 0x00],
            buf
        );
    }
}