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