tcp-lib 0.1.0

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

use super::{Io, State};

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

impl Flow {
    /// Creates a new write flow using the given write buffer capacity.
    #[instrument(skip_all)]
    pub fn new(bytes: impl IntoIterator<Item = u8>) -> Self {
        let state = State::new(bytes.into_iter().collect());
        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::Write),
        }
    }
}

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