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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use crate::decoder::{
    value::{DecoderParameterizedValue, DecoderValue},
    DecoderError,
};

pub type DecoderBufferResult<'a, T> = Result<(T, DecoderBuffer<'a>), DecoderError>;

/// DecoderBuffer is a panic-free byte buffer for look-ahead decoding untrusted input
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct DecoderBuffer<'a> {
    bytes: &'a [u8],
}

impl<'a> DecoderBuffer<'a> {
    /// Create a new `DecoderBuffer` from a byte slice
    #[inline]
    pub const fn new(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }

    /// Move out the buffer's slice. This should be used with caution, as it
    /// removes any panic protection this struct provides.
    #[inline]
    pub fn into_less_safe_slice(self) -> &'a [u8] {
        self.bytes
    }
}

impl_buffer!(
    DecoderBuffer,
    DecoderBufferResult,
    DecoderValue,
    decode,
    DecoderParameterizedValue,
    decode_parameterized,
    split_at
);

impl<'a> From<&'a [u8]> for DecoderBuffer<'a> {
    #[inline]
    fn from(bytes: &'a [u8]) -> Self {
        Self::new(bytes)
    }
}