zonai 0.0.2

Synchronous packet-framed TCP clients and servers
Documentation
//! Shared packet encoding and decoding traits.
//!
//! Protocol types implement [`PacketIn`] for decoding, [`PacketOut`] for
//! encoding, or both when the same type is used in both directions.
//!
//! ## Framing contract
//!
//! - Each trait call handles exactly one complete packet.
//! - A successful decoder must leave bytes for following packets unread.
//! - [`io::ErrorKind::UnexpectedEof`] means that a complete packet was not
//!   available. The server buffers and retries this condition; the blocking
//!   client treats it as a terminal packet I/O error.
//! - Encoders must produce at least one byte. Client and server APIs apply their
//!   configured encoded-packet size limits before writing to a socket.
//!
//! Framing, validation, and allocation limits are protocol responsibilities.
//! Decode untrusted lengths only after checking them against a protocol limit.

use std::io::{self, Read, Write};

/// Decodes one framed packet from an incoming byte stream.
pub trait PacketIn: Sized {
    /// Decode exactly one packet from `read`.
    ///
    /// Return [`io::ErrorKind::UnexpectedEof`] when more bytes are required.
    /// On success, leave bytes belonging to following packets unread.
    fn read(read: &mut impl Read) -> io::Result<Self>;
}

/// Encodes one framed packet to an outgoing byte stream.
pub trait PacketOut {
    /// Encode exactly one packet to `write`.
    fn write(&self, write: &mut impl Write) -> io::Result<()>;
}

#[cfg(any(feature = "client", feature = "server"))]
pub(crate) fn encode_bounded(packet: &impl PacketOut, limit: usize) -> io::Result<Vec<u8>> {
    let mut writer = BoundedVecWriter::new(limit);
    packet.write(&mut writer)?;
    let encoded = writer.into_inner();
    if encoded.is_empty() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "outgoing packet encoded zero bytes",
        ));
    }
    Ok(encoded)
}

#[cfg(any(feature = "client", feature = "server"))]
struct BoundedVecWriter {
    inner: Vec<u8>,
    limit: usize,
}

#[cfg(any(feature = "client", feature = "server"))]
impl BoundedVecWriter {
    fn new(limit: usize) -> Self {
        Self {
            inner: Vec::new(),
            limit,
        }
    }

    fn into_inner(self) -> Vec<u8> {
        self.inner
    }
}

#[cfg(any(feature = "client", feature = "server"))]
impl Write for BoundedVecWriter {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let Some(new_len) = self.inner.len().checked_add(buf.len()) else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "outgoing packet size overflow",
            ));
        };
        if new_len > self.limit {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "outgoing packet exceeded size limit",
            ));
        }
        self.inner.extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}