numbat_codec/
nested_de_input_slice.rs

1use crate::{DecodeError, NestedDecode, NestedDecodeInput};
2
3/// A nested decode buffer implementation on referenced data.
4impl<'a> NestedDecodeInput for &'a [u8] {
5    fn remaining_len(&self) -> usize {
6        self.len()
7    }
8
9    fn read_into(&mut self, into: &mut [u8]) -> Result<(), DecodeError> {
10        if into.len() > self.len() {
11            return Err(DecodeError::INPUT_TOO_SHORT);
12        }
13        let len = into.len();
14        into.copy_from_slice(&self[..len]);
15        *self = &self[len..];
16        Ok(())
17    }
18
19    fn read_into_or_exit<ExitCtx: Clone>(
20        &mut self,
21        into: &mut [u8],
22        c: ExitCtx,
23        exit: fn(ExitCtx, DecodeError) -> !,
24    ) {
25        if into.len() > self.len() {
26            exit(c, DecodeError::INPUT_TOO_SHORT);
27        }
28        let len = into.len();
29        into.copy_from_slice(&self[..len]);
30        *self = &self[len..];
31    }
32}
33
34/// Convenience method, to avoid having to specify type when calling `dep_decode`.
35/// Especially useful in the macros.
36/// Also checks that the entire slice was used.
37/// The input doesn't need to be mutable because we are not changing the underlying data.
38pub fn dep_decode_from_byte_slice<D: NestedDecode>(input: &[u8]) -> Result<D, DecodeError> {
39    let mut_slice = &mut &*input;
40    let result = D::dep_decode(mut_slice);
41    if !mut_slice.is_empty() {
42        return Err(DecodeError::INPUT_TOO_LONG);
43    }
44    result
45}
46
47pub fn dep_decode_from_byte_slice_or_exit<D: NestedDecode, ExitCtx: Clone>(
48    input: &[u8],
49    c: ExitCtx,
50    exit: fn(ExitCtx, DecodeError) -> !,
51) -> D {
52    let mut_slice = &mut &*input;
53    let result = D::dep_decode_or_exit(mut_slice, c.clone(), exit);
54    if !mut_slice.is_empty() {
55        exit(c, DecodeError::INPUT_TOO_LONG);
56    }
57    result
58}