tcp-lib 0.1.0

I/O-free library to manage TCP streams
Documentation
use tracing::debug;

/// The TCP I/O state, owned by flows and updated by handlers.
///
/// This struct represents the I/O state used by I/O handlers to take
/// input and set output. It is usually owned by flows themselves, and
/// serve as communication bridge between flows and I/O handlers.
#[derive(Debug)]
pub struct State {
    pub(crate) buffer: Vec<u8>,
    pub(crate) bytes_count: Option<usize>,
}

/// State constructors.
///
/// This implementation gathers functions for building new states.
impl State {
    pub(crate) const DEFAULT_CAPACITY: usize = 512;

    /// Builds a new state using a default reading capacity defined by
    /// [`State::DEFAULT_CAPACITY`].
    ///
    /// See [`State::with_capacity`] for building a state with a
    /// different reading capacity.
    pub(crate) fn new() -> Self {
        Self::with_capacity(Self::DEFAULT_CAPACITY)
    }

    /// Builds a new state using the given reading capacity.
    ///
    /// See [`State::new`] for building a state with a default reading
    /// capacity.
    pub(crate) fn with_capacity(capacity: usize) -> Self {
        debug!("preparing {capacity} bytes to be read");

        Self {
            buffer: vec![0; capacity],
            bytes_count: None,
        }
    }

    pub fn get_buffer_mut(&mut self) -> &mut [u8] {
        &mut self.buffer
    }

    pub fn set_bytes_count(&mut self, bytes_count: usize) {
        self.bytes_count.replace(bytes_count);
    }
}