Skip to main content

mlt_core/decoder/
layer.rs

1use crate::codecs::varint::parse_varint;
2#[cfg(feature = "unstable-v2")]
3use crate::decoder::root02::parse_layer02;
4use crate::decoder::{ColumnStorage, Layer01, ParsedLayer01, Unknown};
5#[cfg(feature = "unstable-v2")]
6use crate::decoder::{Layer02, ParsedLayer02};
7use crate::utils::{parse_u8, take};
8use crate::{
9    DecodeState, Decoder, Layer, Lazy, LazyParsed, MltError, MltRefResult, MltResult, ParsedLayer,
10    Parser,
11};
12
13impl<'a, S: DecodeState> Layer<'a, S> {
14    /// The layer's name whatever its tag, or `None` for a tag this build does not
15    /// know. A value, unlike a layer, cannot silently lose a version's columns.
16    #[must_use]
17    pub fn name(&self) -> Option<&'a str> {
18        match self {
19            Self::Tag01(l) => Some(l.name()),
20            #[cfg(feature = "unstable-v2")]
21            Self::Tag02(l) => Some(l.layer().name()),
22            Self::Unknown(_) => None,
23        }
24    }
25}
26
27impl<'a> Layer<'a> {
28    /// Parse a single tuple that consists of `size (varint)`, `tag (varint)`, and `value (bytes)`.
29    /// Reserves memory for decoded data against the parser's budget.
30    pub(crate) fn from_bytes(input: &'a [u8], parser: &mut Parser) -> MltRefResult<'a, Self> {
31        let (input, size) = parse_varint::<u32>(input)?;
32
33        // tag is a varint, but we know fewer than 127 tags for now,
34        // so we can use a faster u8 and fail if it is bigger than 127.
35        let (input, tag) = parse_u8(input)?;
36        // 1 byte must be parsed for the tag, so if size is 0, it's invalid
37        let size = size.checked_sub(1).ok_or(MltError::ZeroLayerSize)?;
38        let (input, value) = take(input, size)?;
39
40        let layer = match tag {
41            1 => Layer::Tag01(Layer01::from_bytes(value, parser)?),
42            #[cfg(feature = "unstable-v2")]
43            2 => Layer::Tag02(parse_layer02(value, parser)?),
44            tag => Layer::Unknown(Unknown { tag, value }),
45        };
46
47        Ok((input, layer))
48    }
49
50    /// Decode all columns and return a fully-decoded [`ParsedLayer`].
51    ///
52    /// Consumes `self`.  For partial / incremental decoding, destructure with
53    /// `Layer::Tag01(lazy)` and call the individual methods on [`Layer01`].
54    pub fn decode_all(self, dec: &mut Decoder) -> MltResult<ParsedLayer<'a>> {
55        match self {
56            Layer::Tag01(v) => Ok(Layer::Tag01(v.decode_all(dec)?)),
57            #[cfg(feature = "unstable-v2")]
58            Layer::Tag02(v) => Ok(Layer::Tag02(v.decode_all(dec)?)),
59            Layer::Unknown(u) => Ok(Layer::Unknown(u)),
60        }
61    }
62}
63
64impl<'a> Layer01<'a, Lazy> {
65    /// Call `cb` with the [`ColumnStorage`] of every column that has one to report.
66    ///
67    /// Decoding a string column reconstructs its values, leaving nothing to say whether
68    /// they arrived plain, dictionary-coded, FSST-compressed or front-coded, so a caller
69    /// reporting on how a tile is stored has to ask before [`Self::decode_all`] runs.
70    pub fn for_each_column_storage(&self, cb: &mut dyn FnMut(ColumnStorage)) {
71        for column in &self.properties {
72            if let LazyParsed::Raw(raw) = column
73                && let Some(storage) = raw.storage()
74            {
75                cb(storage);
76            }
77        }
78    }
79
80    /// Decode all columns and transition to [`Layer01<Parsed>`].
81    ///
82    /// Consumes `self` (a `Layer01<Lazy>`) and returns a `Layer01<Parsed>` where every
83    /// column field holds its parsed value directly, enabling infallible readonly access.
84    pub fn decode_all(self, dec: &mut Decoder) -> MltResult<ParsedLayer01<'a>> {
85        Ok(Layer01 {
86            name: self.name,
87            extent: self.extent,
88            id: self.id.map(|id| id.into_parsed(dec)).transpose()?,
89            geometry: self.geometry.into_parsed(dec)?,
90            properties: self
91                .properties
92                .into_iter()
93                .map(|p| p.into_parsed(dec))
94                .collect::<MltResult<Vec<_>>>()?,
95            #[cfg(fuzzing)]
96            layer_order: self.layer_order,
97        })
98    }
99}
100
101#[cfg(feature = "unstable-v2")]
102impl<'a> Layer02<'a, Lazy> {
103    /// Decode every column, shared and v2-only.
104    pub fn decode_all(self, dec: &mut Decoder) -> MltResult<ParsedLayer02<'a>> {
105        let layer = Layer02 {
106            layer: self.layer.decode_all(dec)?,
107            nested: self
108                .nested
109                .into_iter()
110                .map(|n| n.into_parsed(dec))
111                .collect::<MltResult<Vec<_>>>()?,
112            m_values: self
113                .m_values
114                .into_iter()
115                .map(|m| m.into_parsed(dec))
116                .collect::<MltResult<Vec<_>>>()?,
117            layout: self.layout,
118        };
119        // An m-value column's length is only checkable once the geometry is decoded
120        // too, which it now is. Every later walk of a column relies on this check.
121        for column in &layer.m_values {
122            column.check_length(&layer.layer.geometry)?;
123        }
124        Ok(layer)
125    }
126}