1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use crate::errors::ErrorKind;

#[doc(hidden)]
#[derive(Copy, Clone, Debug)]
pub struct SliceWithStartOffset<'buf> {
    pub buffer: &'buf [u8],
    pub offset_from_start: usize,
}

impl<'buf> SliceWithStartOffset<'buf> {
    /// Length of the slize in bytes.
    pub fn len(&self) -> usize {
        self.buffer.len()
    }

    /// Returns true if the slice is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the inner buffer as a slice.
    pub fn as_slice(&self) -> &'buf [u8] {
        self.buffer
    }

    /// Returns a new slice which is advanced by `amount` bytes.
    pub fn advance(&self, amount: usize) -> core::result::Result<Self, ErrorKind> {
        let buffer = self.buffer.get(amount..).ok_or(ErrorKind::InvalidOffset)?;
        Ok(Self {
            buffer,
            offset_from_start: self.offset_from_start + amount,
        })
    }

    /// The same as [`SliceWithStartOffset::advance`], but converted to an array reference.
    pub fn advance_as_array<const N: usize>(
        &self,
        amount: usize,
    ) -> core::result::Result<ArrayWithStartOffset<'buf, N>, ErrorKind> {
        let buffer = self
            .buffer
            .get(amount..amount + N)
            .ok_or(ErrorKind::InvalidOffset)?;
        Ok(ArrayWithStartOffset {
            buffer: buffer.try_into().unwrap(),
            offset_from_start: self.offset_from_start + amount,
        })
    }

    /// # Safety
    /// TODO
    pub unsafe fn unchecked_advance_as_array<const N: usize>(
        &self,
        amount: usize,
    ) -> ArrayWithStartOffset<'buf, N> {
        let buffer = self.buffer.get_unchecked(amount..amount + N);
        ArrayWithStartOffset {
            buffer: buffer.try_into().unwrap(),
            offset_from_start: self.offset_from_start + amount,
        }
    }
}

#[doc(hidden)]
#[derive(Copy, Clone, Debug)]
pub struct ArrayWithStartOffset<'buf, const N: usize> {
    pub buffer: &'buf [u8; N],
    pub offset_from_start: usize,
}

impl<'buf, const N: usize> ArrayWithStartOffset<'buf, N> {
    /// Get inner buffer as an array reference
    pub fn as_array(&self) -> &'buf [u8; N] {
        self.buffer
    }

    /// Returns a new array which is advanced by `amount` bytes.
    pub fn advance_as_array<const K: usize>(
        &self,
        amount: usize,
    ) -> core::result::Result<ArrayWithStartOffset<'buf, K>, ErrorKind> {
        let buffer = self
            .buffer
            .get(amount..amount + K)
            .ok_or(ErrorKind::InvalidOffset)?;
        Ok(ArrayWithStartOffset {
            buffer: buffer.try_into().unwrap(),
            offset_from_start: self.offset_from_start + amount,
        })
    }
}