buffer_plz/
cursor.rs

1use bytes::BytesMut;
2
3// Cursor for the BytesMut
4#[derive(Debug)]
5pub struct Cursor<'a> {
6    inner: &'a mut BytesMut,
7    pos: usize,
8}
9
10impl<'a> Cursor<'a> {
11    pub fn new(inner: &'a mut BytesMut) -> Self {
12        Cursor { inner, pos: 0 }
13    }
14
15    pub fn into_inner(&mut self) -> BytesMut {
16        self.inner.split()
17    }
18
19    pub const fn position(&self) -> usize {
20        self.pos
21    }
22
23    pub fn set_position(&mut self, pos: usize) {
24        self.pos = pos;
25    }
26
27    pub fn reset(&mut self) {
28        self.pos = 0;
29    }
30
31    // Len of the inner value
32    #[allow(clippy::len_without_is_empty)]
33    pub fn len(&self) -> usize {
34        self.inner.len()
35    }
36
37    pub fn remaining(&self) -> &[u8] {
38        self.inner[self.pos..].as_ref()
39    }
40
41    // split at current position and reset
42    pub fn split_at_current_pos(&mut self) -> BytesMut {
43        let pos = self.pos;
44        self.reset();
45        self.inner.split_to(pos)
46    }
47}
48
49impl AsRef<[u8]> for Cursor<'_> {
50    fn as_ref(&self) -> &[u8] {
51        self.inner
52    }
53}
54
55impl AsMut<BytesMut> for Cursor<'_> {
56    fn as_mut(&mut self) -> &mut BytesMut {
57        self.inner
58    }
59}