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