cs_mwc_bch/messages/
ping.rs

1use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
2use messages::message::Payload;
3use std::io;
4use std::io::{Read, Write};
5use util::{Result, Serializable};
6
7/// Ping or pong payload
8#[derive(Debug, Default, PartialEq, Eq, Hash, Clone)]
9pub struct Ping {
10    /// Unique identifier nonce
11    pub nonce: u64,
12}
13
14impl Ping {
15    /// Size of the ping or pong payload in bytes
16    pub const SIZE: usize = 8;
17}
18
19impl Serializable<Ping> for Ping {
20    fn read(reader: &mut dyn Read) -> Result<Ping> {
21        let nonce = reader.read_u64::<LittleEndian>()?;
22        Ok(Ping { nonce })
23    }
24
25    fn write(&self, writer: &mut dyn Write) -> io::Result<()> {
26        writer.write_u64::<LittleEndian>(self.nonce)
27    }
28}
29
30impl Payload<Ping> for Ping {
31    fn size(&self) -> usize {
32        Ping::SIZE
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39    use hex;
40    use std::io::Cursor;
41
42    #[test]
43    fn read_bytes() {
44        let b = hex::decode("86b19332b96c657d".as_bytes()).unwrap();
45        let f = Ping::read(&mut Cursor::new(&b)).unwrap();
46        assert!(f.nonce == 9035747770062057862);
47    }
48
49    #[test]
50    fn write_read() {
51        let mut v = Vec::new();
52        let p = Ping { nonce: 13579 };
53        p.write(&mut v).unwrap();
54        assert!(v.len() == p.size());
55        assert!(Ping::read(&mut Cursor::new(&v)).unwrap() == p);
56    }
57}