saluki_io/buf/cursor.rs
1/// A cursor over the unread bytes of a buffer, which advances the buffer as bytes are taken.
2///
3/// The cursor borrows the buffer's bytes immutably and its read index exclusively. Bytes taken with
4/// [`take`](Self::take) therefore stay valid for the whole borrow, even after the cursor is dropped, and the buffer
5/// can't be written to, collapsed, or cleared until they're gone. Taking bytes is the only way to get bytes that
6/// outlive the cursor, so any such bytes have already been advanced past.
7pub struct ReadCursor<'a> {
8 bytes: &'a [u8],
9 read_idx: &'a mut usize,
10 capacity: usize,
11}
12
13impl<'a> ReadCursor<'a> {
14 /// Creates a cursor over `bytes`, starting at `*read_idx`.
15 ///
16 /// `read_idx` must be the buffer's own read index, and `capacity` the largest number of bytes the buffer can hold.
17 /// Crate-private, so the only cursors are ones that advance a real buffer.
18 ///
19 /// # Panics
20 ///
21 /// Panics if `*read_idx` is greater than `bytes.len()`, or `capacity` is less than `bytes.len()`.
22 pub(crate) fn new(bytes: &'a [u8], read_idx: &'a mut usize, capacity: usize) -> Self {
23 assert!(*read_idx <= bytes.len(), "read index past the end of the buffer");
24 assert!(capacity >= bytes.len(), "capacity smaller than the buffer");
25 Self {
26 bytes,
27 read_idx,
28 capacity,
29 }
30 }
31
32 /// Returns the unread bytes.
33 ///
34 /// The returned slice borrows the cursor, so it can't be held while bytes are taken.
35 pub fn unread(&self) -> &[u8] {
36 &self.bytes[*self.read_idx..]
37 }
38
39 /// Returns the largest number of bytes the underlying buffer can hold.
40 pub const fn capacity(&self) -> usize {
41 self.capacity
42 }
43
44 /// Advances past the first `n` unread bytes, and returns them.
45 ///
46 /// # Panics
47 ///
48 /// Panics if `n` is greater than the number of unread bytes. The buffer is left unchanged.
49 pub fn take(&mut self, n: usize) -> &'a [u8] {
50 let start = *self.read_idx;
51 assert!(n <= self.bytes.len() - start, "took past the end of the buffer");
52 *self.read_idx = start + n;
53 &self.bytes[start..start + n]
54 }
55}
56
57#[cfg(test)]
58mod tests {
59 use super::*;
60
61 #[test]
62 fn take_advances_and_outlives_the_cursor() {
63 let bytes = b"hello, world!";
64 let mut read_idx = 0;
65
66 let (first, second) = {
67 let mut cursor = ReadCursor::new(bytes, &mut read_idx, bytes.len());
68 let first = cursor.take(7);
69 assert_eq!(cursor.unread(), b"world!");
70 (first, cursor.take(6))
71 };
72
73 assert_eq!(first, b"hello, ");
74 assert_eq!(second, b"world!");
75 assert_eq!(read_idx, bytes.len());
76 }
77
78 #[test]
79 fn take_past_end_panics_without_advancing() {
80 let bytes = b"hello";
81 let mut read_idx = 1;
82 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
83 ReadCursor::new(bytes, &mut read_idx, bytes.len()).take(5);
84 }));
85 assert!(result.is_err());
86 assert_eq!(read_idx, 1);
87 }
88}