s2n_codec/decoder/
buffer.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::decoder::{
5    value::{DecoderParameterizedValue, DecoderValue},
6    DecoderError,
7};
8
9pub type DecoderBufferResult<'a, T> = Result<(T, DecoderBuffer<'a>), DecoderError>;
10
11/// DecoderBuffer is a panic-free byte buffer for look-ahead decoding untrusted input
12#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
13pub struct DecoderBuffer<'a> {
14    bytes: &'a [u8],
15}
16
17impl<'a> DecoderBuffer<'a> {
18    /// Create a new `DecoderBuffer` from a byte slice
19    #[inline]
20    pub const fn new(bytes: &'a [u8]) -> Self {
21        Self { bytes }
22    }
23
24    /// Move out the buffer's slice. This should be used with caution, as it
25    /// removes any panic protection this struct provides.
26    #[inline]
27    pub fn into_less_safe_slice(self) -> &'a [u8] {
28        self.bytes
29    }
30}
31
32impl_buffer!(
33    DecoderBuffer,
34    DecoderBufferResult,
35    DecoderValue,
36    decode,
37    DecoderParameterizedValue,
38    decode_parameterized,
39    split_at
40);
41
42impl<'a> From<&'a [u8]> for DecoderBuffer<'a> {
43    #[inline]
44    fn from(bytes: &'a [u8]) -> Self {
45        Self::new(bytes)
46    }
47}