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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use std::io::{self, Read, Write};

use crate::{
    io::{SizedReadFrom, WriteTo},
    message::Message,
    packet::Command,
};

/// A "pong" message that is sent as a reply to a ping message.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Pong {
    payload: Vec<u8>,
}

impl Default for Pong {
    fn default() -> Self {
        Self {
            payload: Vec::with_capacity(0),
        }
    }
}

impl Pong {
    /// Constructs a pong message with empty payload.
    pub fn new() -> Self {
        Self::default()
    }

    /// Constructs a  pong message with a payload.
    pub fn with_payload(payload: Vec<u8>) -> Self {
        Self { payload }
    }

    /// Returns the payload.
    pub fn payload(&self) -> &[u8] {
        &self.payload
    }
}

impl WriteTo for Pong {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        self.payload.write_to(w)?;
        Ok(())
    }
}

impl SizedReadFrom for Pong {
    fn sized_read_from(r: &mut dyn Read, len: usize) -> io::Result<Self>
    where
        Self: Sized,
    {
        Ok(Self {
            payload: Vec::<u8>::sized_read_from(r, len)?,
        })
    }
}

impl Message for Pong {
    const COMMAND: Command = Command::PONG;
}

#[test]
fn test_pong_write_to() {
    let test = Pong::with_payload(b"hello".to_vec());
    let mut bytes = Vec::new();
    test.write_to(&mut bytes).unwrap();
    let expected = [b'h', b'e', b'l', b'l', b'o'];
    assert_eq!(bytes, expected.to_vec());
}

#[test]
fn test_pong_sized_read_from() {
    use std::io::Cursor;

    let mut bytes = Cursor::new([b'h', b'e', b'l', b'l', b'o']);
    let test = Pong::sized_read_from(&mut bytes, 5).unwrap();
    let expected = Pong::with_payload(b"hello".to_vec());
    assert_eq!(test, expected);
}