Skip to main content

mln_engine/tile/
mlt.rs

1// MapLibre Tiles are decoded by the mlt-core crate. A tile's layers decode on
2// the first read, all at once, into columns the layer owns: mlt-core's
3// decoded layer borrows the tile's bytes, so it can't be kept beside them.
4// The geometry columns are mlt-core's own; the property columns are copied
5// out with one value or absence per feature. A feature is an index into the
6// columns, and reads its geometry from them when asked.
7//
8// A tile mlt-core can't decode, and one that uses FastPFOR where it isn't
9// enabled, is logged and reads as a tile without layers.
10
11use std::ops::Range;
12use std::sync::{Arc, OnceLock};
13
14use mln_style::constants::EXTENT;
15use mln_style::feature::{GeometryCollection, GeometryCoordinate, GeometryCoordinates, Identifier, PropertyMap, Value};
16use mln_style::geometry::FeatureType;
17use mln_style::hash::HashMap;
18use mlt_core::wire::{Analyze as _, LogicalEncoding, PhysicalEncoding};
19use mlt_core::{GeometryType, GeometryValues, ParsedLayer01, ParsedProperty};
20
21use crate::log_target;
22use crate::tile::TileError;
23use crate::tile::tile_data::FeatureGroups;
24
25struct MltData {
26    bytes: Arc<Vec<u8>>,
27    fast_pfor_enabled: bool,
28    /// The decoded layers, in tile order.
29    layers: OnceLock<Vec<Layer>>,
30}
31
32/// MapLibre Tile data. Cloning shares the bytes and the decoded layers.
33#[derive(Clone)]
34pub struct MltTile(Arc<MltData>);
35
36impl MltTile {
37    /// Tile data that decodes `bytes`; with `fast_pfor_enabled` false, a tile
38    /// that uses FastPFOR integer encoding has no layers.
39    #[must_use]
40    pub fn new(bytes: Arc<Vec<u8>>, fast_pfor_enabled: bool) -> Self {
41        MltTile(Arc::new(MltData { bytes, fast_pfor_enabled, layers: OnceLock::new() }))
42    }
43
44    /// The tile's bytes.
45    #[must_use]
46    pub fn bytes(&self) -> &Arc<Vec<u8>> {
47        &self.0.bytes
48    }
49
50    #[must_use]
51    pub(crate) fn fast_pfor_enabled(&self) -> bool {
52        self.0.fast_pfor_enabled
53    }
54
55    fn layers(&self) -> &[Layer] {
56        self.0.layers.get_or_init(|| {
57            decode(&self.0.bytes, self.0.fast_pfor_enabled).unwrap_or_else(|e| {
58                log::warn!(target: log_target::PARSE_TILE, "MLT parse failed: {e}");
59                Vec::new()
60            })
61        })
62    }
63
64    /// The first layer named `name`.
65    pub(crate) fn layer(&self, name: &str) -> Option<MltLayer<'_>> {
66        self.layers().iter().find(|layer| layer.name == name).map(MltLayer)
67    }
68
69    /// The names of the tile's layers, in tile order, duplicates included.
70    #[cfg(test)]
71    pub(crate) fn layer_names(&self) -> Vec<String> {
72        self.layers().iter().map(|layer| layer.name.clone()).collect()
73    }
74}
75
76/// Decodes the tile's layers; a layer of a version mlt-core reads but this
77/// doesn't is skipped.
78fn decode(data: &[u8], fast_pfor_enabled: bool) -> Result<Vec<Layer>, String> {
79    let error = |e: mlt_core::MltError| e.to_string();
80    let mut parser = mlt_core::Parser::default();
81    let mut decoder = mlt_core::Decoder::default();
82    let mut layers = Vec::new();
83    for layer in parser.parse_layers(data).map_err(error)? {
84        let mlt_core::Layer::Tag01(layer) = layer else {
85            continue;
86        };
87        if !fast_pfor_enabled && uses_fast_pfor(&layer) {
88            return Err("FastPFOR decoding is not enabled".to_owned());
89        }
90        layers.push(Layer::new(&layer.decode_all(&mut decoder).map_err(error)?)?);
91    }
92    Ok(layers)
93}
94
95/// Whether an integer or vertex stream of the layer uses FastPFOR.
96fn uses_fast_pfor(layer: &mlt_core::Layer01<'_>) -> bool {
97    let mut found = false;
98    layer.for_each_stream(&mut |meta| {
99        found |= matches!(meta.encoding.physical, PhysicalEncoding::FastPFor(_))
100            && matches!(meta.encoding.logical, LogicalEncoding::Int(_) | LogicalEncoding::Vertex(_));
101    });
102    found
103}
104
105/// A property column: each feature's value, `None` for an absent one.
106enum Values {
107    Bool(Vec<Option<bool>>),
108    Int(Vec<Option<i64>>),
109    Uint(Vec<Option<u64>>),
110    Double(Vec<Option<f64>>),
111    /// The strings back to back, and each feature's byte range in them.
112    Str {
113        data: String,
114        spans: Vec<Option<(u32, u32)>>,
115    },
116}
117
118impl Values {
119    fn strings<'a>(len: usize, get: impl Fn(usize) -> Option<&'a str>) -> Values {
120        let mut data = String::new();
121        let spans = (0..len)
122            .map(|i| {
123                get(i).map(|s| {
124                    let start = data.len() as u32;
125                    data.push_str(s);
126                    (start, data.len() as u32)
127                })
128            })
129            .collect();
130        Values::Str { data, spans }
131    }
132
133    /// The value of feature `i`; `None` for an absent value, also past the
134    /// end of the column.
135    fn get(&self, i: usize) -> Option<Value> {
136        match self {
137            Values::Bool(v) => v.get(i).copied().flatten().map(Value::Bool),
138            Values::Int(v) => v.get(i).copied().flatten().map(Value::Int),
139            Values::Uint(v) => v.get(i).copied().flatten().map(Value::Uint),
140            Values::Double(v) => v.get(i).copied().flatten().map(Value::Double),
141            Values::Str { data, spans } => spans
142                .get(i)
143                .copied()
144                .flatten()
145                .map(|(start, end)| Value::String(data[start as usize..end as usize].to_owned())),
146        }
147    }
148}
149
150struct Column {
151    values: Values,
152    /// Each string's code, numbered by first use, made by the first
153    /// [`Column::codes`]; `None` if the strings are too varied to be worth
154    /// coding.
155    string_codes: OnceLock<Option<Box<[u32]>>>,
156}
157
158/// Equal codes for equal values ([`Column::codes`]).
159struct ValueCodes<'a> {
160    values: &'a Values,
161    strings: &'a [u32],
162}
163
164impl ValueCodes<'_> {
165    /// The code of feature `i`'s value, `None` for an absent value.
166    fn get(&self, i: usize) -> Option<u64> {
167        match self.values {
168            Values::Bool(v) => v.get(i).copied().flatten().map(u64::from),
169            Values::Int(v) => v.get(i).copied().flatten().map(|x| x as u64),
170            Values::Uint(v) => v.get(i).copied().flatten(),
171            Values::Double(v) => v.get(i).copied().flatten().map(f64::to_bits),
172            Values::Str { .. } => self.strings.get(i).copied().filter(|&code| code != u32::MAX).map(u64::from),
173        }
174    }
175}
176
177impl Column {
178    fn new(values: Values) -> Self {
179        Column { values, string_codes: OnceLock::new() }
180    }
181
182    /// A code for each value, equal codes for equal values (equal values may
183    /// differ in code). Numbers and booleans are their bits; strings are
184    /// numbered, on the first call. `None` for a string column with more
185    /// distinct strings than about a quarter of its values.
186    fn codes(&self) -> Option<ValueCodes<'_>> {
187        let strings = match &self.values {
188            Values::Str { data, spans } => self
189                .string_codes
190                .get_or_init(|| {
191                    // Past about a quarter as many strings as values, the codes
192                    // would group little and cost about as much as reading
193                    // every value.
194                    let limit = spans.len() / 4 + 8;
195                    let mut index: HashMap<&str, u32> = HashMap::default();
196                    let mut codes = Vec::with_capacity(spans.len());
197                    for span in spans {
198                        codes.push(match *span {
199                            Some((start, end)) => {
200                                let next = index.len() as u32;
201                                let code = *index.entry(&data[start as usize..end as usize]).or_insert(next);
202                                if index.len() > limit {
203                                    return None;
204                                }
205                                code
206                            }
207                            None => u32::MAX,
208                        });
209                    }
210                    Some(codes.into_boxed_slice())
211                })
212                .as_deref()?,
213            _ => &[],
214        };
215        Some(ValueCodes { values: &self.values, strings })
216    }
217}
218
219/// The triangles of a layer's tessellated polygons.
220struct Triangles {
221    /// Three indices per triangle, each into its feature's decoded vertices
222    /// (see [`GeometryCollection::get_triangles`]).
223    indices: Arc<[u32]>,
224    /// Each feature's range of `indices`; `None` for a feature without
225    /// triangles.
226    of_feature: Vec<Option<Range<usize>>>,
227}
228
229/// The lines or rings of a feature, as the vertices they take.
230enum Parts {
231    /// A point, or the points of a multi-point, as one line.
232    Points(Vec<usize>),
233    Lines(Vec<Range<usize>>),
234    /// Polygon rings, which decoding closes.
235    Rings(Vec<Range<usize>>),
236}
237
238struct Layer {
239    name: String,
240    extent: u32,
241    geometry: GeometryValues,
242    ids: Option<Vec<Option<u64>>>,
243    /// The property columns in wire order; of two with the same name, the
244    /// first.
245    columns: Vec<(String, Column)>,
246    column_index: HashMap<String, usize>,
247    triangles: Option<Triangles>,
248}
249
250impl Layer {
251    fn new(parsed: &ParsedLayer01<'_>) -> Result<Layer, String> {
252        let mut layer = Layer {
253            name: parsed.name().to_owned(),
254            extent: parsed.extent().get(),
255            geometry: parsed.geometry_values().clone(),
256            ids: parsed.id().map(|id| id.iter_optional().collect()),
257            columns: Vec::new(),
258            column_index: HashMap::default(),
259            triangles: None,
260        };
261        let mut names = parsed.iterate_prop_names().map(|name| name.to_string());
262        let mut next_name = || names.next().ok_or_else(|| "property column count mismatch".to_owned());
263        for column in parsed.properties() {
264            let values = match column {
265                ParsedProperty::Bool(s) => Values::Bool(s.iter_optional().collect()),
266                ParsedProperty::I8(s) => Values::Int(s.iter_optional().map(|v| v.map(i64::from)).collect()),
267                ParsedProperty::U8(s) => Values::Uint(s.iter_optional().map(|v| v.map(u64::from)).collect()),
268                ParsedProperty::I32(s) => Values::Int(s.iter_optional().map(|v| v.map(i64::from)).collect()),
269                ParsedProperty::U32(s) => Values::Uint(s.iter_optional().map(|v| v.map(u64::from)).collect()),
270                ParsedProperty::I64(s) => Values::Int(s.iter_optional().collect()),
271                ParsedProperty::U64(s) => Values::Uint(s.iter_optional().collect()),
272                ParsedProperty::F32(s) => Values::Double(s.iter_optional().map(|v| v.map(f64::from)).collect()),
273                ParsedProperty::F64(s) => Values::Double(s.iter_optional().collect()),
274                ParsedProperty::Str(s) => Values::strings(s.feature_count(), |i| s.get(i as u32)),
275                ParsedProperty::SharedDict(dict) => {
276                    // One column per child, named prefix + suffix.
277                    for item in dict.items() {
278                        let values = Values::strings(item.feature_count(), |i| item.get(dict, i));
279                        layer.insert_column(next_name()?, values);
280                    }
281                    continue;
282                }
283                _ => return Err(format!("unsupported property column type {:?}", column.kind())),
284            };
285            layer.insert_column(next_name()?, values);
286        }
287        layer.triangles = layer.triangles();
288        Ok(layer)
289    }
290
291    fn insert_column(&mut self, name: String, values: Values) {
292        if !self.column_index.contains_key(&name) {
293            self.column_index.insert(name.clone(), self.columns.len());
294            self.columns.push((name, Column::new(values)));
295        }
296    }
297
298    fn column(&self, key: &str) -> Option<&Column> {
299        self.column_index.get(key).map(|&i| &self.columns[i].1)
300    }
301
302    fn len(&self) -> usize {
303        self.geometry.feature_count()
304    }
305
306    fn feature_type(&self, index: usize) -> FeatureType {
307        match self.geometry.vector_types()[index] {
308            GeometryType::Point | GeometryType::MultiPoint => FeatureType::Point,
309            GeometryType::LineString | GeometryType::MultiLineString => FeatureType::LineString,
310            GeometryType::Polygon | GeometryType::MultiPolygon => FeatureType::Polygon,
311        }
312    }
313
314    /// The lines or rings of feature `index`.
315    fn parts(&self, index: usize) -> Result<Parts, TileError> {
316        let values = &self.geometry;
317        let geometry_type = values.vector_types()[index];
318        let geoms = values.geometry_offsets();
319        let parts = values.part_offsets();
320        let rings = values.ring_offsets();
321        let malformed = |what: &str| TileError::Geometry(format!("MLT {what} out of range"));
322        let offset =
323            |level: &[u32], i: usize, what: &str| level.get(i).map(|&v| v as usize).ok_or_else(|| malformed(what));
324        let span = |level: &[u32], i: usize, what: &str| {
325            Ok::<_, TileError>(offset(level, i, what)?..offset(level, i + 1, what)?)
326        };
327        let no_topology = || TileError::Geometry(format!("MLT {geometry_type} geometry without topology"));
328        // The geometry, else this feature's first part.
329        let first = |i: usize| geoms.map_or(Ok(i), |g| offset(g, i, "geometry offset"));
330        // A line: a range of rings, else of parts.
331        let line = |part: usize, p: &[u32]| match rings {
332            Some(r) => span(r, offset(p, part, "part offset")?, "ring offset"),
333            None => span(p, part, "part offset"),
334        };
335
336        if parts.is_none() && values.index_buffer().is_some() {
337            // Tessellated without topology: only points can be read.
338            return match geometry_type {
339                GeometryType::Point => Ok(Parts::Points(vec![index])),
340                _ => Err(no_topology()),
341            };
342        }
343        Ok(match geometry_type {
344            GeometryType::Point => {
345                let mut i = first(index)?;
346                if let Some(p) = parts {
347                    i = offset(p, i, "part offset")?;
348                }
349                if let Some(r) = rings {
350                    i = offset(r, i, "ring offset")?;
351                }
352                Parts::Points(vec![i])
353            }
354            GeometryType::MultiPoint => {
355                let g = geoms.ok_or_else(no_topology)?;
356                let mut points = Vec::new();
357                for i in span(g, index, "geometry offset")? {
358                    points.push(match (parts, rings) {
359                        (Some(p), Some(r)) => offset(r, offset(p, i, "part offset")?, "ring offset")?,
360                        (Some(p), None) => offset(p, i, "part offset")?,
361                        (None, _) => i,
362                    });
363                }
364                Parts::Points(points)
365            }
366            GeometryType::LineString => Parts::Lines(vec![line(first(index)?, parts.ok_or_else(no_topology)?)?]),
367            GeometryType::MultiLineString => {
368                let lines = span(geoms.ok_or_else(no_topology)?, index, "geometry offset")?;
369                let mut result = Vec::with_capacity(lines.len());
370                for i in lines {
371                    result.push(line(i, parts.ok_or_else(no_topology)?)?);
372                }
373                Parts::Lines(result)
374            }
375            GeometryType::Polygon => {
376                let (p, r) = (parts.ok_or_else(no_topology)?, rings.ok_or_else(no_topology)?);
377                let mut result = Vec::new();
378                for i in span(p, first(index)?, "part offset")? {
379                    result.push(span(r, i, "ring offset")?);
380                }
381                Parts::Rings(result)
382            }
383            GeometryType::MultiPolygon => {
384                let polygons = span(geoms.ok_or_else(no_topology)?, index, "geometry offset")?;
385                let mut result = Vec::new();
386                for polygon in polygons {
387                    let (p, r) = (parts.ok_or_else(no_topology)?, rings.ok_or_else(no_topology)?);
388                    for i in span(p, polygon, "part offset")? {
389                        result.push(span(r, i, "ring offset")?);
390                    }
391                }
392                Parts::Rings(result)
393            }
394        })
395    }
396
397    /// The geometry of feature `index`, scaled to `util::EXTENT`. Decoding
398    /// closes polygon rings, which the tile stores without their closing
399    /// vertex.
400    fn geometry(&self, index: usize) -> Result<GeometryCollection, TileError> {
401        let vertices = self.geometry.vertices().unwrap_or(&[]);
402        let scale = f64::from(EXTENT) / f64::from(self.extent);
403        let vertex = |i: usize| -> Result<GeometryCoordinate, TileError> {
404            let v = vertices
405                .get(2 * i..2 * i + 2)
406                .ok_or_else(|| TileError::Geometry("MLT vertex out of range".to_owned()))?;
407            let convert = |c: i32| (f64::from(c) * scale).round() as i16;
408            Ok(GeometryCoordinate::new(convert(v[0]), convert(v[1])))
409        };
410        let line = |range: Range<usize>, close: bool| -> Result<GeometryCoordinates, TileError> {
411            let mut coords = Vec::with_capacity(range.len() + usize::from(close));
412            for i in range.clone() {
413                coords.push(vertex(i)?);
414            }
415            if close && let Some(&first) = coords.first() {
416                coords.push(first);
417            }
418            Ok(coords)
419        };
420        let mut geometry = match self.parts(index)? {
421            Parts::Points(points) => {
422                GeometryCollection::from(vec![points.into_iter().map(vertex).collect::<Result<Vec<_>, _>>()?])
423            }
424            Parts::Lines(lines) => {
425                GeometryCollection::from(lines.into_iter().map(|l| line(l, false)).collect::<Result<Vec<_>, _>>()?)
426            }
427            Parts::Rings(rings) => {
428                GeometryCollection::from(rings.into_iter().map(|r| line(r, true)).collect::<Result<Vec<_>, _>>()?)
429            }
430        };
431        if let Some(triangles) = &self.triangles
432            && let Some(Some(range)) = triangles.of_feature.get(index)
433        {
434            geometry.set_triangles(Arc::clone(&triangles.indices), range.clone());
435        }
436        Ok(geometry)
437    }
438
439    /// The triangles of the tessellated polygons: each polygon and
440    /// multi-polygon takes the next count of triangles from the index
441    /// buffer. A feature whose triangles name a vertex it doesn't have, or
442    /// that the counts run out before, has none.
443    fn triangles(&self) -> Option<Triangles> {
444        let values = &self.geometry;
445        let (indices, counts) = (values.index_buffer()?, values.triangle_offsets()?);
446        let mut rebased = Vec::with_capacity(indices.len());
447        let mut of_feature = vec![None; self.len()];
448        let (mut ring_lens, mut ring_shifts) = (Vec::new(), Vec::new());
449        let mut runs = counts.windows(2);
450        for (index, &t) in values.vector_types().iter().enumerate() {
451            if !matches!(t, GeometryType::Polygon | GeometryType::MultiPolygon) {
452                continue;
453            }
454            let Some(run) = runs.next() else { break };
455            let Some(corners) = indices.get(run[0] as usize * 3..run[1] as usize * 3) else { break };
456            if corners.is_empty() {
457                continue;
458            }
459            let (Ok(Parts::Rings(rings)), Ok(vertices)) = (self.parts(index), values.vertex_range(index)) else {
460                continue;
461            };
462            ring_lens.clear();
463            ring_lens.extend(rings.iter().map(|r| (r.len() as u32, (r.len() + usize::from(!r.is_empty())) as u32)));
464            let first = rebased.len();
465            if rebase_triangles(corners, vertices.start as u32, &ring_lens, &mut ring_shifts, &mut rebased) {
466                of_feature[index] = Some(first..rebased.len());
467            }
468        }
469        Some(Triangles { indices: Arc::from(rebased), of_feature })
470    }
471
472    /// Port-only: groups by geometry type and by each key's value code
473    /// ([`Column::codes`]): equal codes are equal values, and equal values
474    /// with distinct codes only split a group. A key without a column is
475    /// absent from every feature.
476    fn group_features(&self, keys: &[String]) -> Option<FeatureGroups> {
477        let count = self.len();
478        // Grouping costs about as much as evaluating each feature once.
479        let limit = count / 4 + 8;
480        let columns: Vec<ValueCodes<'_>> =
481            keys.iter().filter_map(|key| self.column(key)).map(Column::codes).collect::<Option<_>>()?;
482        let mut index: HashMap<Box<[Option<u64>]>, u32> = HashMap::default();
483        let mut codes = vec![None; columns.len() + 1];
484        let mut groups = FeatureGroups { of_feature: Vec::with_capacity(count), first: Vec::new() };
485        for i in 0..count {
486            codes[columns.len()] = Some(self.feature_type(i) as u64);
487            for (code, column) in codes.iter_mut().zip(&columns) {
488                *code = column.get(i);
489            }
490            let group = if let Some(&group) = index.get(codes.as_slice()) {
491                group
492            } else {
493                if groups.first.len() == limit {
494                    return None;
495                }
496                let group = groups.first.len() as u32;
497                index.insert(codes.as_slice().into(), group);
498                groups.first.push(i);
499                group
500            };
501            groups.of_feature.push(group);
502        }
503        Some(groups)
504    }
505}
506
507/// A layer of an [`MltTile`].
508#[derive(Clone, Copy)]
509pub struct MltLayer<'a>(&'a Layer);
510
511impl<'a> MltLayer<'a> {
512    pub(crate) fn name(self) -> &'a str {
513        &self.0.name
514    }
515
516    pub(crate) fn extent(self) -> u32 {
517        self.0.extent
518    }
519
520    pub(crate) fn len(self) -> usize {
521        self.0.len()
522    }
523
524    /// The feature at `index`; fails with [`TileError::OutOfRange`] past the
525    /// end.
526    pub(crate) fn feature(self, index: usize) -> Result<MltFeature<'a>, TileError> {
527        if index < self.len() {
528            Ok(MltFeature { layer: self.0, index })
529        } else {
530            Err(TileError::vector_range_check(index, self.len()))
531        }
532    }
533
534    pub(crate) fn group_features(self, keys: &[String]) -> Option<FeatureGroups> {
535        self.0.group_features(keys)
536    }
537}
538
539/// A feature of an [`MltLayer`].
540#[derive(Clone, Copy)]
541pub struct MltFeature<'a> {
542    layer: &'a Layer,
543    index: usize,
544}
545
546impl MltFeature<'_> {
547    pub(crate) fn get_type(&self) -> FeatureType {
548        self.layer.feature_type(self.index)
549    }
550
551    pub(crate) fn get_id(&self) -> Identifier {
552        let id = self.layer.ids.as_ref().and_then(|ids| ids.get(self.index).copied().flatten());
553        id.map_or(Identifier::Null, Identifier::Uint)
554    }
555
556    pub(crate) fn get_value(&self, key: &str) -> Option<Value> {
557        self.layer.column(key)?.values.get(self.index)
558    }
559
560    /// Every property; an absent value is a null.
561    pub(crate) fn get_properties(&self) -> PropertyMap {
562        (self.layer.columns.iter())
563            .map(|(key, column)| (key.clone(), column.values.get(self.index).unwrap_or(Value::Null)))
564            .collect()
565    }
566
567    pub(crate) fn geometry(&self) -> Result<GeometryCollection, TileError> {
568        self.layer.geometry(self.index)
569    }
570}
571
572/// Appends `corners`, the triangles of a feature as indices of the layer's
573/// vertices, to `out` as indices of the feature's decoded vertices; returns
574/// `false`, appending nothing, when a corner is not one of the feature's
575/// vertices.
576///
577/// `first_vertex` is the feature's first vertex in the layer, and `rings`
578/// the stored and decoded vertex counts of its rings. A ring decodes one
579/// vertex longer than it is stored when decoding closes it, which moves the
580/// vertices of the rings after it up by one. `ring_shifts` is scratch space.
581fn rebase_triangles(
582    corners: &[u32],
583    first_vertex: u32,
584    rings: &[(u32, u32)],
585    ring_shifts: &mut Vec<(u32, u32)>,
586    out: &mut Vec<u32>,
587) -> bool {
588    // The first stored vertex of each ring, and how far decoding moves it.
589    ring_shifts.clear();
590    let (mut stored, mut decoded) = (0u32, 0u32);
591    for &(stored_len, decoded_len) in rings {
592        ring_shifts.push((stored, decoded - stored));
593        stored += stored_len;
594        decoded += decoded_len;
595    }
596    // Only a closing vertex before the last ring moves any corner.
597    let moved = ring_shifts.last().is_some_and(|&(_, shift)| shift > 0);
598    let first = out.len();
599    for &corner in corners {
600        let i = corner.wrapping_sub(first_vertex);
601        if i >= stored {
602            out.truncate(first);
603            return false;
604        }
605        let shift = if moved { ring_shifts[ring_shifts.partition_point(|&(start, _)| start <= i) - 1].1 } else { 0 };
606        out.push(i + shift);
607    }
608    true
609}
610
611#[cfg(test)]
612mod tests {
613    use std::path::Path;
614
615    use geometry::Point;
616    use mln_style::feature::Value;
617    use mlt_core::encoder::{EncoderConfig, Network, Profile};
618    use mlt_core::geo_types::Coord;
619    use mlt_core::{LayerWriter, PropKind};
620
621    use super::*;
622
623    /// A layer "l" with a multi-point, a polygon and a line, an 8-bit
624    /// integer column, and a string column the line lacks.
625    fn tile() -> Vec<u8> {
626        let mut layer = LayerWriter::new("l", 2 * EXTENT as u32).unwrap();
627        let small = layer.add_property("small", PropKind::I8).unwrap();
628        let name = layer.add_property("name", PropKind::Str).unwrap();
629        let points = [Coord { x: 2, y: 4 }, Coord { x: 6, y: 8 }];
630        let ring = [Coord { x: 0, y: 0 }, Coord { x: 100, y: 0 }, Coord { x: 100, y: 100 }];
631        for (i, geometry_type) in
632            [GeometryType::MultiPoint, GeometryType::Polygon, GeometryType::LineString].into_iter().enumerate()
633        {
634            let mut feature = layer.feature(geometry_type);
635            match geometry_type {
636                GeometryType::MultiPoint => feature.points(points),
637                GeometryType::Polygon => feature.exterior_ring(ring),
638                _ => feature.line(points),
639            }
640            .unwrap();
641            feature.id(Some(i as u64 + 10));
642            feature.property(small, -(i as i8)).unwrap();
643            if geometry_type != GeometryType::LineString {
644                feature.property(name, "n").unwrap();
645            }
646            feature.finish().unwrap();
647        }
648        layer.encode(EncoderConfig::from_profile(Profile::Web(Network::Offline))).unwrap()
649    }
650
651    #[test]
652    fn features_read_their_columns() {
653        let tile = MltTile::new(Arc::new(tile()), false);
654        let layer = tile.layer("l").unwrap();
655        assert_eq!((layer.name(), layer.len()), ("l", 3));
656        let [multi_point, polygon, line] = [0, 1, 2].map(|i| layer.feature(i).unwrap());
657        assert!(layer.feature(3).is_err());
658
659        // A multi-point is a point feature, its points one line; an extent
660        // of twice `util::EXTENT` halves the coordinates.
661        assert_eq!(multi_point.get_type(), FeatureType::Point);
662        assert_eq!(*multi_point.geometry().unwrap(), [vec![Point::new(1, 2), Point::new(3, 4)]]);
663        assert_eq!(multi_point.get_id(), Identifier::Uint(10));
664        // Decoding closes a polygon's rings.
665        assert_eq!(polygon.get_type(), FeatureType::Polygon);
666        assert_eq!(
667            *polygon.geometry().unwrap(),
668            [vec![Point::new(0, 0), Point::new(50, 0), Point::new(50, 50), Point::new(0, 0)]]
669        );
670        assert_eq!(line.get_type(), FeatureType::LineString);
671
672        // 8-bit integers read as integers; an absent value is none, and a
673        // null among the properties.
674        assert_eq!(polygon.get_value("small"), Some(Value::Int(-1)));
675        assert_eq!(polygon.get_value("name"), Some(Value::String("n".to_owned())));
676        assert_eq!(line.get_value("name"), None);
677        assert_eq!(line.get_properties().get("name"), Some(&Value::Null));
678        assert_eq!(line.get_value("nothing"), None);
679    }
680
681    /// Clones share one decoding, which threads may race to make.
682    #[test]
683    fn clones_share_the_decoded_layers() {
684        let path = Path::new(&std::env::var_os("CARGO_MANIFEST_DIR").unwrap())
685            .join("testdata/test/fixtures/map/issue12432/0-0-0.mlt");
686        let tile = MltTile::new(Arc::new(std::fs::read(path).unwrap()), false);
687        let layers: Vec<usize> = std::thread::scope(|scope| {
688            let threads: Vec<_> = (0..4)
689                .map(|_| {
690                    let tile = tile.clone();
691                    scope.spawn(move || std::ptr::from_ref(tile.layer("admin").unwrap().0) as usize)
692                })
693                .collect();
694            threads.into_iter().map(|thread| thread.join().unwrap()).collect()
695        });
696        let here = std::ptr::from_ref(tile.layer("admin").unwrap().0) as usize;
697        assert!(layers.iter().all(|&layer| layer == here));
698    }
699
700    fn rebase(corners: &[u32], first_vertex: u32, rings: &[(u32, u32)]) -> Option<Vec<u32>> {
701        let mut out = vec![7];
702        let ok = rebase_triangles(corners, first_vertex, rings, &mut Vec::new(), &mut out);
703        assert_eq!(out[0], 7, "kept what was there");
704        ok.then(|| out[1..].to_vec())
705    }
706
707    #[test]
708    fn rebases_corners_past_closing_vertices() {
709        // A ring of 4 stored vertices closed by decoding, an empty ring, a
710        // ring stored closed, and a ring closed by decoding.
711        let rings = [(4, 5), (0, 0), (3, 3), (3, 4)];
712        assert_eq!(rebase(&[10, 13, 14, 16, 17, 19], 10, &rings), Some(vec![0, 3, 5, 7, 8, 10]));
713        // One ring: its closing vertex moves nothing.
714        assert_eq!(rebase(&[2, 3, 5], 2, &[(4, 5)]), Some(vec![0, 1, 3]));
715    }
716
717    #[test]
718    fn rejects_corners_outside_the_feature() {
719        let rings = [(4, 5), (3, 4)];
720        // Past the feature's last vertex.
721        assert_eq!(rebase(&[0, 1, 7], 0, &rings), None);
722        // Before its first.
723        assert_eq!(rebase(&[5, 6, 4], 5, &rings), None);
724        assert_eq!(rebase(&[0, 1, 2], 0, &[]), None);
725    }
726}