tcp_lib/read/state.rs
1use tracing::debug;
2
3/// The TCP I/O state, owned by flows and updated by handlers.
4///
5/// This struct represents the I/O state used by I/O handlers to take
6/// input and set output. It is usually owned by flows themselves, and
7/// serve as communication bridge between flows and I/O handlers.
8#[derive(Debug)]
9pub struct State {
10 pub(crate) buffer: Vec<u8>,
11 pub(crate) bytes_count: Option<usize>,
12}
13
14/// State constructors.
15///
16/// This implementation gathers functions for building new states.
17impl State {
18 pub(crate) const DEFAULT_CAPACITY: usize = 512;
19
20 /// Builds a new state using a default reading capacity defined by
21 /// [`State::DEFAULT_CAPACITY`].
22 ///
23 /// See [`State::with_capacity`] for building a state with a
24 /// different reading capacity.
25 pub(crate) fn new() -> Self {
26 Self::with_capacity(Self::DEFAULT_CAPACITY)
27 }
28
29 /// Builds a new state using the given reading capacity.
30 ///
31 /// See [`State::new`] for building a state with a default reading
32 /// capacity.
33 pub(crate) fn with_capacity(capacity: usize) -> Self {
34 debug!("preparing {capacity} bytes to be read");
35
36 Self {
37 buffer: vec![0; capacity],
38 bytes_count: None,
39 }
40 }
41
42 pub fn get_buffer_mut(&mut self) -> &mut [u8] {
43 &mut self.buffer
44 }
45
46 pub fn set_bytes_count(&mut self, bytes_count: usize) {
47 self.bytes_count.replace(bytes_count);
48 }
49}