Skip to main content

mlt_core/convert/mvt/
decode.rs

1//! Decode MVT bytes into [`FeatureCollection`] or row-oriented [`TileLayer`]s.
2
3use std::collections::{BTreeMap, HashMap};
4
5use fast_mvt::{MvtLayer, MvtLayerRef, MvtReaderRef, MvtValue, MvtValueRef};
6use serde_json::Value;
7
8use crate::geojson::{Feature, FeatureCollection};
9use crate::tile::{PropValue, TileFeature, TileLayer};
10use crate::{MltError, MltResult};
11
12/// Parse MVT bytes into a list of layers, each holding its raw features.
13fn read_mvt_layers(data: &[u8]) -> MltResult<Vec<MvtLayer>> {
14    let layers = MvtReaderRef::new(data)?.to_tile()?.layers;
15    if layers.iter().any(|layer| layer.name.is_empty()) {
16        return Err(MltError::MissingLayerName);
17    }
18    Ok(layers)
19}
20
21/// Parse MVT binary data and convert to a [`FeatureCollection`].
22pub fn mvt_to_feature_collection(data: impl AsRef<[u8]>) -> MltResult<FeatureCollection> {
23    let mut features = Vec::new();
24
25    for layer in read_mvt_layers(data.as_ref())? {
26        for feat in layer.features {
27            let mut properties = feat
28                .properties
29                .into_iter()
30                .map(|(k, v)| Ok((k, Value::try_from(v)?)))
31                .collect::<MltResult<BTreeMap<_, _>>>()?;
32            properties.insert("_layer".into(), Value::String(layer.name.clone()));
33            properties.insert("_extent".into(), Value::Number(layer.extent.get().into()));
34            features.push(Feature {
35                geometry: feat.geometry,
36                id: feat.id,
37                properties,
38                ty: "Feature".into(),
39            });
40        }
41    }
42
43    Ok(FeatureCollection {
44        features,
45        ty: "FeatureCollection".into(),
46    })
47}
48
49/// Parse MVT binary data and convert each layer to a row-oriented [`TileLayer`].
50///
51/// Each MVT layer becomes one [`TileLayer`].  Property column types are inferred
52/// from all features in the layer: the first non-null value seen for each column
53/// determines its type, with `I64`+`U64` widened to `I64` and `F32`+`F64` widened
54/// to `F64`; all other type conflicts fall back to `Str`.
55pub fn mvt_to_tile_layers(data: impl AsRef<[u8]>) -> MltResult<Vec<TileLayer>> {
56    MvtReaderRef::new(data.as_ref())?
57        .layers()
58        .map(tile_layer_from_ref)
59        .collect()
60}
61
62/// Build a [`TileLayer`] straight from the borrowed reader.
63fn tile_layer_from_ref(layer: MvtLayerRef<'_>) -> MltResult<TileLayer> {
64    let name = layer.name();
65    if name.is_empty() {
66        return Err(MltError::MissingLayerName);
67    }
68
69    // First pass: collect property names (insertion-ordered) and infer column types.
70    let mut col_names: Vec<String> = Vec::new();
71    let mut col_index: HashMap<&str, usize> = HashMap::new();
72    let mut col_types: Vec<InferredType> = Vec::new();
73    // Each value with its column, so the second pass resolves no keys.
74    let mut values: Vec<(usize, MvtValueRef<'_>)> = Vec::new();
75    let mut feature_ends: Vec<usize> = Vec::with_capacity(layer.feature_count());
76
77    for feat in layer.features() {
78        for prop in feat.properties() {
79            let (key, value) = prop?;
80            let idx = if let Some(&idx) = col_index.get(key) {
81                idx
82            } else {
83                let idx = col_names.len();
84                col_names.push(key.to_string());
85                col_index.insert(key, idx);
86                col_types.push(InferredType::Unknown);
87                idx
88            };
89            // One bounds check rather than one per index expression.
90            let slot = &mut col_types[idx];
91            *slot = slot.merge(InferredType::from_mvt(value));
92            values.push((idx, value));
93        }
94        feature_ends.push(values.len());
95    }
96
97    // Columns that were only ever null fall back to Str.
98    for t in &mut col_types {
99        if *t == InferredType::Unknown {
100            *t = InferredType::Str;
101        }
102    }
103
104    // Second pass: build TileFeature objects.
105    let mut tile_features = Vec::with_capacity(layer.feature_count());
106    let mut start = 0;
107    for (feat, &end) in layer.features().zip(&feature_ends) {
108        // Start every slot with a typed null; fill in present values below.
109        let mut properties: Vec<PropValue> = col_types.iter().map(|t| t.typed_null()).collect();
110        for &(idx, value) in &values[start..end] {
111            if !matches!(value, MvtValueRef::Null) {
112                properties[idx] = col_types[idx].convert(value.into_owned());
113            }
114        }
115        start = end;
116        tile_features.push(TileFeature {
117            id: feat.id(),
118            geometry: feat.geometry()?,
119            properties,
120        });
121    }
122
123    TileLayer::from_parts(name, layer.extent(), col_names, tile_features)
124}
125
126impl TryFrom<MvtLayer> for TileLayer {
127    type Error = MltError;
128
129    fn try_from(layer: MvtLayer) -> Result<Self, Self::Error> {
130        if layer.name.is_empty() {
131            return Err(MltError::MissingLayerName);
132        }
133
134        // First pass: collect property names (insertion-ordered) and infer column types.
135        let mut col_names: Vec<String> = Vec::new();
136        let mut col_index: HashMap<String, usize> = HashMap::new();
137        let mut col_types: Vec<InferredType> = Vec::new();
138
139        for feat in &layer.features {
140            for (key, val) in &feat.properties {
141                let idx = *col_index.entry(key.clone()).or_insert_with(|| {
142                    let i = col_names.len();
143                    col_names.push(key.clone());
144                    col_types.push(InferredType::Unknown);
145                    i
146                });
147                let slot = &mut col_types[idx];
148                *slot = slot.merge(InferredType::from_mvt(as_value_ref(val)));
149            }
150        }
151
152        // Columns that were only ever null fall back to Str.
153        for t in &mut col_types {
154            if *t == InferredType::Unknown {
155                *t = InferredType::Str;
156            }
157        }
158
159        // Second pass: build TileFeature objects.
160        let mut tile_features = Vec::with_capacity(layer.features.len());
161        for feat in layer.features {
162            // Start every slot with a typed null; fill in present values below.
163            let mut properties: Vec<PropValue> = col_types.iter().map(|t| t.typed_null()).collect();
164            for (key, val) in feat.properties {
165                if let Some(&idx) = col_index.get(&key)
166                    && !matches!(val, MvtValue::Null)
167                {
168                    properties[idx] = col_types[idx].convert(val);
169                }
170            }
171            tile_features.push(TileFeature {
172                id: feat.id,
173                geometry: feat.geometry,
174                properties,
175            });
176        }
177
178        Self::from_parts(layer.name, layer.extent.get(), col_names, tile_features)
179    }
180}
181
182/// Borrow an owned [`MvtValue`], so both conversion paths share one inference pass.
183fn as_value_ref(value: &MvtValue) -> MvtValueRef<'_> {
184    match value {
185        MvtValue::String(s) => MvtValueRef::String(s),
186        MvtValue::Float(f) => MvtValueRef::Float(*f),
187        MvtValue::Double(f) => MvtValueRef::Double(*f),
188        MvtValue::Int(i) => MvtValueRef::Int(*i),
189        MvtValue::UInt(u) => MvtValueRef::UInt(*u),
190        MvtValue::SInt(i) => MvtValueRef::SInt(*i),
191        MvtValue::Bool(b) => MvtValueRef::Bool(*b),
192        MvtValue::Null => MvtValueRef::Null,
193    }
194}
195
196/// Column type inferred from MVT property values across all features in a layer.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198enum InferredType {
199    Unknown,
200    Bool,
201    I64,
202    U64,
203    F32,
204    F64,
205    Str,
206}
207
208impl InferredType {
209    fn from_mvt(val: MvtValueRef<'_>) -> Self {
210        match val {
211            MvtValueRef::Bool(_) => Self::Bool,
212            MvtValueRef::Int(_) | MvtValueRef::SInt(_) => Self::I64,
213            MvtValueRef::UInt(_) => Self::U64,
214            MvtValueRef::Float(_) => Self::F32,
215            MvtValueRef::Double(_) => Self::F64,
216            MvtValueRef::String(_) => Self::Str,
217            MvtValueRef::Null => Self::Unknown,
218        }
219    }
220
221    /// Merge with another type, widening when necessary.
222    fn merge(self, other: Self) -> Self {
223        if self == Self::Unknown {
224            return other;
225        }
226        if other == Self::Unknown || self == other {
227            return self;
228        }
229        if matches!(
230            (self, other),
231            (Self::I64, Self::U64) | (Self::U64, Self::I64)
232        ) {
233            return Self::I64;
234        }
235        if matches!(
236            (self, other),
237            (Self::F32, Self::F64) | (Self::F64, Self::F32)
238        ) {
239            return Self::F64;
240        }
241        Self::Str
242    }
243
244    fn typed_null(self) -> PropValue {
245        match self {
246            Self::Unknown | Self::Str => PropValue::Str(None),
247            Self::Bool => PropValue::Bool(None),
248            Self::I64 => PropValue::I64(None),
249            Self::U64 => PropValue::U64(None),
250            Self::F32 => PropValue::F32(None),
251            Self::F64 => PropValue::F64(None),
252        }
253    }
254
255    /// Convert an owned [`MvtValue`] into a [`PropValue`] matching this column type.
256    fn convert(self, val: MvtValue) -> PropValue {
257        match (self, val) {
258            (_, MvtValue::Null) => self.typed_null(),
259            (Self::Bool, MvtValue::Bool(b)) => PropValue::Bool(Some(b)),
260            (Self::I64, MvtValue::Int(i) | MvtValue::SInt(i)) => PropValue::I64(Some(i)),
261            (Self::I64, MvtValue::UInt(u)) if i64::try_from(u).is_ok() => {
262                // Value must be within 0..i64::MAX
263                #[expect(clippy::cast_possible_wrap, reason = "checked above")]
264                PropValue::I64(Some(u as i64))
265            }
266            (Self::U64, MvtValue::UInt(u)) => PropValue::U64(Some(u)),
267            (Self::F32, MvtValue::Float(f)) => PropValue::F32(Some(f)),
268            (Self::F64, MvtValue::Double(f)) => PropValue::F64(Some(f)),
269            (Self::F64, MvtValue::Float(f)) => PropValue::F64(Some(f64::from(f))),
270            (_, MvtValue::String(s)) => PropValue::Str(Some(s)),
271            // Type conflict at runtime: fall back to a debug string.
272            (_, v) => PropValue::Str(Some(format!("{v:?}"))),
273        }
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    #[test]
282    fn malformed_tags_are_reported() {
283        for (tags, expected) in [
284            (&[5, 0][..], "invalid key index 5"),
285            (&[0, 9][..], "invalid value index 9"),
286            (&[0][..], "invalid feature tags length: 1"),
287        ] {
288            let err = mvt_to_tile_layers(mvt_with_tags(tags))
289                .expect_err("malformed tags must error")
290                .to_string();
291            assert!(err.contains(expected), "got {err:?}, wanted {expected:?}");
292        }
293    }
294
295    /// Minimal hand-written MVT tile with one point feature carrying `tags`.
296    fn mvt_with_tags(tags: &[u32]) -> Vec<u8> {
297        fn field(number: u32, wire: u32) -> u8 {
298            u8::try_from((number << 3) | wire).expect("small field number")
299        }
300        fn varint(mut value: u64, out: &mut Vec<u8>) {
301            loop {
302                let byte = u8::try_from(value & 0x7f).expect("masked");
303                value >>= 7;
304                if value == 0 {
305                    out.push(byte);
306                    return;
307                }
308                out.push(byte | 0x80);
309            }
310        }
311        fn packed(number: u32, values: &[u64], out: &mut Vec<u8>) {
312            let mut body = Vec::new();
313            for value in values {
314                varint(*value, &mut body);
315            }
316            out.push(field(number, 2));
317            varint(u64::try_from(body.len()).expect("small"), out);
318            out.extend(&body);
319        }
320        fn bytes(number: u32, body: &[u8], out: &mut Vec<u8>) {
321            out.push(field(number, 2));
322            varint(u64::try_from(body.len()).expect("small"), out);
323            out.extend(body);
324        }
325
326        let mut feat = Vec::new();
327        packed(
328            2,
329            &tags.iter().copied().map(u64::from).collect::<Vec<_>>(),
330            &mut feat,
331        );
332        feat.push(field(3, 0));
333        varint(1, &mut feat); // POINT
334        packed(4, &[9, 2, 2], &mut feat); // MoveTo(1, 1)
335
336        let mut layer = Vec::new();
337        layer.push(field(15, 0));
338        varint(2, &mut layer); // version
339        bytes(1, b"l", &mut layer); // name
340        bytes(2, &feat, &mut layer); // features
341        bytes(3, b"k", &mut layer); // keys
342        layer.push(field(5, 0));
343        varint(4096, &mut layer); // extent
344
345        let mut tile = Vec::new();
346        bytes(3, &layer, &mut tile);
347        tile
348    }
349}