| 1 | /// A wrapper around a slice that exposes no functions that can panic. |
| 2 | /// |
| 3 | /// Intentionally avoids implementing `Debug`, `Eq`, and `PartialEq` to avoid |
| 4 | /// creating a side channel that would leak information about the value. |
| 5 | #[derive (Clone, Copy)] |
| 6 | pub struct Slice<'a> { |
| 7 | bytes: &'a [u8], |
| 8 | } |
| 9 | |
| 10 | impl<'a> Slice<'a> { |
| 11 | #[inline ] |
| 12 | pub const fn new(bytes: &'a [u8]) -> Self { |
| 13 | Self { bytes } |
| 14 | } |
| 15 | |
| 16 | #[inline ] |
| 17 | pub fn get(&self, i: usize) -> Option<&u8> { |
| 18 | self.bytes.get(i) |
| 19 | } |
| 20 | |
| 21 | #[inline ] |
| 22 | pub fn subslice(&self, r: core::ops::Range<usize>) -> Option<Self> { |
| 23 | self.bytes.get(r).map(|bytes| Self { bytes }) |
| 24 | } |
| 25 | |
| 26 | #[inline ] |
| 27 | pub fn is_empty(&self) -> bool { |
| 28 | self.bytes.is_empty() |
| 29 | } |
| 30 | |
| 31 | #[inline ] |
| 32 | pub fn len(&self) -> usize { |
| 33 | self.bytes.len() |
| 34 | } |
| 35 | |
| 36 | #[inline ] |
| 37 | pub fn as_slice_less_safe(&self) -> &'a [u8] { |
| 38 | self.bytes |
| 39 | } |
| 40 | } |
| 41 | |