koibumi-core 0.0.9

The core library for Koibumi, an experimental Bitmessage client
Documentation
use std::io::{self, Read, Write};

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

/// A "ping" message that is used to keep a network connection alive.
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Ping {
    payload: Vec<u8>,
}

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

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

    /// Constructs a ping 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 Ping {
    fn write_to(&self, w: &mut dyn Write) -> io::Result<()> {
        self.payload.write_to(w)?;
        Ok(())
    }
}

impl SizedReadFrom for Ping {
    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 Ping {
    const COMMAND: Command = Command::PING;
}

#[test]
fn test_ping_write_to() {
    let test = Ping::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_ping_sized_read_from() {
    use std::io::Cursor;

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