mpc_stark/network/stream_buffer.rs
1//! Defines an `std::io::Cursor` like buffer that tracks a cursor within a buffer that
2//! is incrementally consumed. We use this to allow partial fills across cancelled
3//! futures.
4//!
5//! This will be replaced when the more convenient `std::io::Cursor` is stabilized.
6
7/// A wrapper around a raw `&[u8]` buffer that tracks a cursor within the buffer
8/// to allow partial fills across cancelled futures
9///
10/// Similar to `tokio::io::ReadBuf` but takes ownership of the underlying buffer to
11/// avoid coloring interfaces with lifetime parameters
12///
13/// TODO: Replace this with `std::io::Cursor` once it is stabilized
14#[derive(Debug)]
15pub struct BufferWithCursor {
16 /// The underlying buffer
17 buffer: Vec<u8>,
18 /// The current cursor position
19 cursor: usize,
20}
21
22impl BufferWithCursor {
23 /// Create a new buffer with a cursor at the start of the buffer
24 pub fn new(buf: Vec<u8>) -> Self {
25 assert_eq!(
26 buf.len(),
27 buf.capacity(),
28 "buffer must be fully initialized"
29 );
30
31 Self {
32 buffer: buf,
33 cursor: 0,
34 }
35 }
36
37 /// The number of bytes remaining in the buffer
38 pub fn remaining(&self) -> usize {
39 self.buffer.capacity() - self.cursor
40 }
41
42 /// Whether the buffer is full
43 pub fn is_depleted(&self) -> bool {
44 self.remaining() == 0
45 }
46
47 /// Get a mutable reference to the empty section of the underlying buffer
48 pub fn get_remaining(&mut self) -> &mut [u8] {
49 &mut self.buffer[self.cursor..]
50 }
51
52 /// Advance the cursor by `n` bytes
53 pub fn advance_cursor(&mut self, n: usize) {
54 self.cursor += n
55 }
56
57 /// Take ownership of the underlying buffer
58 pub fn into_vec(self) -> Vec<u8> {
59 self.buffer
60 }
61}