tcp-lib 0.1.0

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

use super::{Io, State};

/// Flow for reading a chunk of bytes from a TCP stream.
///
/// This flow should be used when you need to read a chunk of bytes
/// from a TCP stream. The chunk size depends on the I/O state's
/// internal read buffer capacity, which can be adjusted with
/// [`Read::with_capacity`].
#[derive(Debug)]
pub struct Flow {
    state: State,
}

impl Flow {
    /// Creates a new read flow using defaults.
    #[instrument(skip_all)]
    pub fn new() -> Self {
        let state = State::new();
        Self { state }
    }

    /// Creates a new read flow using the given read buffer capacity.
    #[instrument(skip_all)]
    pub fn with_capacity(capacity: usize) -> Self {
        let state = State::with_capacity(capacity);
        Self { state }
    }

    #[instrument(skip_all)]
    pub fn next(&mut self) -> Result<&[u8], Io> {
        match self.state.bytes_count.take() {
            Some(n) => Ok(&self.state.buffer[..n]),
            None => Err(Io::Read),
        }
    }
}

impl AsMut<State> for Flow {
    fn as_mut(&mut self) -> &mut State {
        &mut self.state
    }
}