tcp_lib/write/
flow.rs

1use tracing::instrument;
2
3use super::{Io, State};
4
5/// Flow for writeing a chunk of bytes from a TCP stream.
6///
7/// This flow should be used when you need to write a chunk of bytes
8/// from a TCP stream. The chunk size depends on the I/O state's
9/// internal write buffer capacity, which can be adjusted with
10/// [`Write::with_capacity`].
11#[derive(Debug)]
12pub struct Flow {
13    state: State,
14}
15
16impl Flow {
17    /// Creates a new write flow using the given write buffer capacity.
18    #[instrument(skip_all)]
19    pub fn new(bytes: impl IntoIterator<Item = u8>) -> Self {
20        let state = State::new(bytes.into_iter().collect());
21        Self { state }
22    }
23
24    #[instrument(skip_all)]
25    pub fn next(&mut self) -> Result<&[u8], Io> {
26        match self.state.bytes_count.take() {
27            Some(n) => Ok(&self.state.buffer[..n]),
28            None => Err(Io::Write),
29        }
30    }
31}
32
33impl AsMut<State> for Flow {
34    fn as_mut(&mut self) -> &mut State {
35        &mut self.state
36    }
37}