packetwire 0.1.0

Bounded deterministic binary packet codec with stream and datagram framing
Documentation
use crate::{BinaryDecode, BinaryEncode, BinaryReader, BinaryWriter, ProtocolError, Result};

use crate::{packet, packet_set};

#[packet(id = 3)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Ping {
    pub(crate) sequence: u32,
    pub(crate) sent_at_micros: u64,
}

#[packet(id = 4)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Pong;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DebugLevel {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}

impl BinaryEncode for DebugLevel {
    fn encode(&self, writer: &mut BinaryWriter) -> Result<()> {
        let tag: u8 = match self {
            Self::Trace => 0,
            Self::Debug => 1,
            Self::Info => 2,
            Self::Warn => 3,
            Self::Error => 4,
        };
        tag.encode(writer)
    }
}

impl BinaryDecode for DebugLevel {
    fn decode(reader: &mut BinaryReader<'_>) -> Result<Self> {
        match u8::decode(reader)? {
            0 => Ok(Self::Trace),
            1 => Ok(Self::Debug),
            2 => Ok(Self::Info),
            3 => Ok(Self::Warn),
            4 => Ok(Self::Error),
            tag => Err(ProtocolError::InvalidEnumTag {
                type_name: "DebugLevel",
                tag: u64::from(tag),
            }),
        }
    }
}

#[packet(id = 5)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct DebugMessage {
    pub(crate) level: DebugLevel,
    pub(crate) target: String,
    pub(crate) message: String,
}

#[packet_set]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SamplePacket {
    Ping(Ping),
    Pong(Pong),
    DebugMessage(DebugMessage),
}