simple_tlv/
slice.rs

1use core::convert::TryFrom;
2use crate::{Length, Result};
3
4/// Slice of at most `Length::max()` bytes.
5#[derive(Copy, Clone, Debug, Eq, PartialEq)]
6pub struct Slice<'a> {
7    /// Inner value
8    inner: &'a [u8],
9
10    /// Precomputed `Length` (avoids possible panicking conversions)
11    length: Length,
12}
13
14impl<'a> Slice<'a> {
15    /// Create a new [`Slice`], ensuring that the provided `slice` value
16    /// is shorter than `Length::max()`.
17    pub fn new(slice: &'a [u8]) -> Result<Self> {
18        Ok(Self {
19            inner: slice,
20            length: Length::try_from(slice.len())?,
21        })
22    }
23
24    /// Borrow the inner byte slice
25    pub fn as_bytes(&self) -> &'a [u8] {
26        self.inner
27    }
28
29    /// Get the [`Length`] of this [`Slice`]
30    pub fn length(self) -> Length {
31        self.length
32    }
33
34    /// Is this [`Slice`] empty?
35    pub fn is_empty(self) -> bool {
36        self.length() == Length::zero()
37    }
38}
39
40impl AsRef<[u8]> for Slice<'_> {
41    fn as_ref(&self) -> &[u8] {
42        self.as_bytes()
43    }
44}
45