tcp_lib/read/
flow.rs

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