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
48
49
50
51
52
53
54
55
56
57
use crate::codecs::varint::parse_varint;
use crate::decoder::{Layer01, Unknown};
use crate::utils::{parse_u8, take};
use crate::{DecodeState, Decoder, Layer, MltError, MltRefResult, MltResult, ParsedLayer, Parser};
impl<'a, S: DecodeState> Layer<'a, S> {
/// Returns the inner `Layer01` if this is a Tag01 layer, or `None` otherwise.
#[must_use]
pub fn as_layer01(&self) -> Option<&Layer01<'a, S>> {
match self {
Self::Tag01(l) => Some(l),
Self::Unknown(_) => None,
}
}
/// Consumes this layer and returns the inner `Layer01`, or `None` if it is not a Tag01 layer.
#[must_use]
pub fn into_layer01(self) -> Option<Layer01<'a, S>> {
match self {
Self::Tag01(l) => Some(l),
Self::Unknown(_) => None,
}
}
}
impl<'a> Layer<'a> {
/// Parse a single tuple that consists of `size (varint)`, `tag (varint)`, and `value (bytes)`.
/// Reserves memory for decoded data against the parser's budget.
pub(crate) fn from_bytes(input: &'a [u8], parser: &mut Parser) -> MltRefResult<'a, Self> {
let (input, size) = parse_varint::<u32>(input)?;
// tag is a varint, but we know fewer than 127 tags for now,
// so we can use a faster u8 and fail if it is bigger than 127.
let (input, tag) = parse_u8(input)?;
// 1 byte must be parsed for the tag, so if size is 0, it's invalid
let size = size.checked_sub(1).ok_or(MltError::ZeroLayerSize)?;
let (input, value) = take(input, size)?;
let layer = match tag {
1 => Layer::Tag01(Layer01::from_bytes(value, parser)?),
tag => Layer::Unknown(Unknown { tag, value }),
};
Ok((input, layer))
}
/// Decode all columns and return a fully-decoded [`ParsedLayer`].
///
/// Consumes `self`. For partial / incremental decoding, destructure with
/// `Layer::Tag01(lazy)` and call the individual methods on [`Layer01`].
pub fn decode_all(self, dec: &mut Decoder) -> MltResult<ParsedLayer<'a>> {
match self {
Layer::Tag01(v) => Ok(Layer::Tag01(v.decode_all(dec)?)),
Layer::Unknown(u) => Ok(Layer::Unknown(u)),
}
}
}