mlt-core 0.14.1

MapLibre Tile library code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use derive_debug::Dbg;
use num_enum::TryFromPrimitive;

use crate::utils::formatter::{bytes_dbg, compact_dbg};
use crate::{MltError, MltResult};

/// Logical encoding technique used for a column, as stored in the tile
///
/// Variants are already shifted into the primary logical field of the v1 encoding byte (bits 7-5),
/// so that field is matched with a mask rather than shifted down first.
/// The secondary field (bits 4-2) holds the same patterns three bits lower.
#[derive(Debug, Clone, Copy, PartialEq, TryFromPrimitive)]
#[repr(u8)]
pub enum LogicalTechnique {
    None = 0b0000_0000,
    Delta = 0b0010_0000,
    ComponentwiseDelta = 0b0100_0000,
    Rle = 0b0110_0000,
    Morton = 0b1000_0000,
}

/// The combinations of the two [`LogicalTechnique`] fields that are legal on the wire
///
/// Each variant is the whole logical part of the v1 encoding byte, i.e. the primary field
/// (bits 7-5) or-ed with the secondary field (bits 4-2).
/// Any other pairing of the two fields is rejected while parsing.
#[derive(Debug, Clone, Copy, PartialEq, TryFromPrimitive)]
#[repr(u8)]
pub enum LogicalCombination {
    None = 0b0000_0000,
    Delta = 0b0010_0000,
    DeltaRle = 0b0010_1100,
    ComponentwiseDelta = 0b0100_0000,
    Rle = 0b0110_0000,
    Morton = 0b1000_0000,
    MortonDelta = 0b1000_0100,
    MortonRle = 0b1000_1100,
}

/// Which RLE stream layout the encoder should produce.
///
/// A data-less selector chosen up front by the wire format (see
/// [`WireVersion::rle_layout`](crate::encoder::WireVersion)); the realized
/// per-stream metadata is [`RleMeta`], whose variants mirror these.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RleLayout {
    /// Tag `0x01`: all run lengths first, then all values.
    Split,
    /// Tag `0x02`: `(run_length, value)` pairs. Requires the `unstable-v2` feature.
    #[cfg(feature = "unstable-v2")]
    Interleaved,
}

/// Metadata for RLE decoding, one variant per [`RleLayout`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum RleMeta {
    /// Tag `0x01`: physically-decoded words are `[run_len × runs][value × runs]`.
    /// `runs` is the split point; `num_rle_values` is the expanded element count.
    Split { runs: u32, num_rle_values: u32 },
    /// Tag `0x02`: physically-decoded words are `(run_len, value)` pairs. The run
    /// count is derived from the data length, so only the expanded element count
    /// (`num_rle_values`, from the stream's count context) is carried.
    /// Requires the `unstable-v2` feature.
    #[cfg(feature = "unstable-v2")]
    Interleaved { num_rle_values: u32 },
}

impl RleMeta {
    /// The total expanded element count, common to both layouts.
    #[cfg(feature = "unstable-v2")]
    #[must_use]
    pub(crate) fn num_rle_values(self) -> u32 {
        match self {
            Self::Split { num_rle_values, .. } => num_rle_values,
            #[cfg(feature = "unstable-v2")]
            Self::Interleaved { num_rle_values } => num_rle_values,
        }
    }
}

/// Metadata for Morton decoding
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Morton {
    /// Number of bits used
    pub(crate) bits: u32,
    /// Coordinate shift
    pub(crate) shift: u32,
}

impl Morton {
    pub fn new(bits: u32, shift: u32) -> MltResult<Self> {
        if bits <= 16 {
            Ok(Self { bits, shift })
        } else {
            Err(MltError::InvalidMortonBits(bits))
        }
    }
}

/// The decimal scaling an ALP column uses: `i = round(v * 10^e / 10^f)`.
/// Chosen before any value is seen, so it carries no frame of reference.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlpScale {
    /// Decimal exponent the values were scaled by.
    pub(crate) e: u8,
    /// Factor dividing out the trailing zeros `e` introduced, never exceeding `e`.
    pub(crate) f: u8,
}

/// ALP parameters: `v = (base + offset) * 10^f / 10^e`.
/// Written as three header varints, the stream itself holding the unsigned offsets.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Alp {
    pub(crate) scale: AlpScale,
    /// Frame of reference the offsets are measured from, the smallest scaled integer in the column.
    pub(crate) base: i64,
}

#[cfg(feature = "unstable-v2")]
impl AlpScale {
    /// Largest exponent the codes can carry, past which `v * 10^e` leaves the `i64` range.
    pub(crate) const MAX_EXPONENT: u8 = 18;

    /// Net power of ten the codes carry, which fixes their magnitude and so their stored size.
    /// The order [`candidates`](crate::codecs::alp::candidates) walks, and so what lets the
    /// encoder stop at the first scale that fits; only the tests holding that invariant name it.
    #[cfg(test)]
    pub(crate) fn net(self) -> u8 {
        self.e - self.f
    }
}

/// Flattened, since the nesting is an encoder concern and these appear in stream labels.
impl std::fmt::Debug for Alp {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Alp {{ e: {}, f: {}, base: {} }}",
            self.scale.e, self.scale.f, self.base
        )
    }
}

#[cfg(feature = "unstable-v2")]
impl Alp {
    pub(crate) fn new(e: u8, f: u8, base: i64) -> MltResult<Self> {
        if e <= AlpScale::MAX_EXPONENT && f <= e {
            Ok(Self {
                scale: AlpScale { e, f },
                base,
            })
        } else {
            Err(MltError::InvalidAlpParams(e, f))
        }
    }

    /// Measure a scaled integer from the frame of reference, giving the offset the stream stores.
    /// Wrapping, so a column spanning the whole `i64` range still subtracts exactly.
    #[expect(
        clippy::cast_sign_loss,
        reason = "the bit pattern is the point; `code_at` casts it back"
    )]
    pub(crate) fn offset_of(self, code: i64) -> u64 {
        (code as u64).wrapping_sub(self.base as u64)
    }

    /// Put a stored offset back on the frame of reference, inverting [`Self::offset_of`].
    #[expect(
        clippy::cast_possible_wrap,
        clippy::cast_sign_loss,
        reason = "the bit pattern is the point; inverts `offset_of` exactly"
    )]
    pub(crate) fn code_at(self, offset: u64) -> i64 {
        (self.base as u64).wrapping_add(offset) as i64
    }
}

/// What kind of values a stream holds, which fixes the encodings it can name.
/// Neither wire format stores it: v1 reads it from the column type, v2 from the stream's context.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValueKind {
    Int,
    Bool,
    Float,
    Vertex,
}

/// Logical encoding of a stream of integer values.
/// Covers the id columns, the integer property columns, and the geometry length and offset streams.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum IntLogical {
    None,
    Delta,
    Rle(RleMeta),
    DeltaRle(RleMeta),
}

/// Logical encoding of a bool column's data stream or a presence bitfield.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BoolLogical {
    /// A raw packed bitmap, one bit per value.
    None,
    /// A byte-RLE compressed bitmap.
    /// Its run parameters come from the stream's context rather than from its header.
    ByteRle(RleMeta),
}

/// Logical encoding of a float column's data stream.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FloatLogical {
    /// Fixed-width little-endian values, one per element.
    None,
    /// A decimal split across two integer streams, which v1 can name but no decoder here implements.
    /// One code per element, with the distinct values following as a second stream.
    /// Only the tag `0x02` codec reads or writes it.
    Dict,
    /// Integers scaled by these parameters.
    /// Only the tag `0x02` codec reads or writes it.
    Alp(Alp),
}

/// Logical encoding of a geometry vertex stream, whose values are interleaved coordinate pairs.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum VertexLogical {
    None,
    Delta,
    ComponentwiseDelta,
    Morton(Morton),
    MortonDelta(Morton),
    MortonRle(Morton),
}

/// How should the stream be interpreted at the logical level (second pass of decoding)
///
/// Split per [`ValueKind`] so a stream can name only the encodings its values can have.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum LogicalEncoding {
    Int(IntLogical),
    Bool(BoolLogical),
    Float(FloatLogical),
    Vertex(VertexLogical),
}

impl LogicalEncoding {
    /// The kind of values this encoding belongs to.
    #[must_use]
    pub fn kind(self) -> ValueKind {
        match self {
            Self::Int(_) => ValueKind::Int,
            Self::Bool(_) => ValueKind::Bool,
            Self::Float(_) => ValueKind::Float,
            Self::Vertex(_) => ValueKind::Vertex,
        }
    }

    /// The identity encoding for `kind`, i.e. values stored as they are.
    #[must_use]
    pub(crate) fn none(kind: ValueKind) -> Self {
        match kind {
            ValueKind::Int => Self::Int(IntLogical::None),
            ValueKind::Bool => Self::Bool(BoolLogical::None),
            ValueKind::Float => Self::Float(FloatLogical::None),
            ValueKind::Vertex => Self::Vertex(VertexLogical::None),
        }
    }

    /// Whether the stream's own logical pass is a no-op, so the physical words are already the output.
    /// True for a float dictionary's codes, which the column turns back into floats.
    /// Not true for ALP, whose offsets still need the frame of reference added back.
    #[must_use]
    pub(crate) fn is_identity(self) -> bool {
        matches!(
            self,
            Self::Int(IntLogical::None)
                | Self::Bool(BoolLogical::None)
                | Self::Float(FloatLogical::None | FloatLogical::Dict)
                | Self::Vertex(VertexLogical::None)
        )
    }
}

/// Carries the stream metadata needed to perform the logical decode pass.
///
/// Construct with [`LogicalValue::new`] after the physical decode pass fills a
/// `&[u32]` or `&[u64]` buffer, then call the appropriate `decode_*` method,
/// passing that slice as `data`.
#[derive(Debug, PartialEq)]
pub struct LogicalValue {
    pub(crate) meta: StreamMeta,
}

// Physical encoding types

/// Dictionary type used for a column, as stored in the tile
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, TryFromPrimitive)]
#[repr(u8)]
pub enum DictionaryType {
    None = 0b0000_0000,
    Single = 0b0000_0001,
    Shared = 0b0000_0010,
    Vertex = 0b0000_0011,
    Morton = 0b0000_0100,
    Fsst = 0b0000_0101,
}

/// Offset type used for a column, as stored in the tile
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, TryFromPrimitive)]
#[repr(u8)]
pub enum OffsetType {
    Vertex = 0b0000_0000,
    Index = 0b0000_0001,
    String = 0b0000_0010,
    Key = 0b0000_0011,
}

/// Length type used for a column, as stored in the tile
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, TryFromPrimitive)]
#[repr(u8)]
pub enum LengthType {
    VarBinary = 0b0000_0000,
    Geometries = 0b0000_0001,
    Parts = 0b0000_0010,
    Rings = 0b0000_0011,
    Triangles = 0b0000_0100,
    Symbol = 0b0000_0101,
    Dictionary = 0b0000_0110,
    /// A nested list or map node's lengths, one per present value of the node.
    #[cfg(feature = "unstable-v2")]
    Nested = 0b0000_0111,
}

/// How should the stream be interpreted at the physical level (first pass of decoding)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum StreamType {
    Present,
    Data(DictionaryType),
    Offset(OffsetType),
    Length(LengthType),
}

/// Physical encoding used for a column, as stored in the tile
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum PhysicalEncoding {
    None,
    /// Preferred, tends to produce the best compression ratio and decoding performance.
    /// But currently limited to 32-bit integer.
    FastPFor(FastPForKind),
    /// Can produce better results in combination with a heavyweight compression scheme like `Gzip`.
    /// Simple compression scheme where the encoding is easier to implement compared to `FastPfor`.
    VarInt,
    /// Every value in the same number of bits, which a leading payload byte names.
    /// Beats `VarInt` on the short, small-alphabet streams a dictionary's codes form,
    /// where `FastPFor`'s 128-value blocks are too coarse to pay for themselves.
    #[cfg(feature = "unstable-v2")]
    BitPacked,
}

/// The `FastPFor` block size and word order a wire version codes its integer streams with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum FastPForKind {
    /// 256-value blocks over big-endian words
    Block256Be,
    /// 128-value blocks over little-endian words
    #[cfg(feature = "unstable-v2")]
    Block128Le,
}

// RawStream types

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct IntEncoding {
    pub logical: LogicalEncoding,
    pub physical: PhysicalEncoding,
}

impl IntEncoding {
    #[must_use]
    pub(crate) const fn new(logical: LogicalEncoding, physical: PhysicalEncoding) -> Self {
        Self { logical, physical }
    }

    #[must_use]
    pub(crate) fn none(kind: ValueKind) -> Self {
        Self::new(LogicalEncoding::none(kind), PhysicalEncoding::None)
    }
}

/// Metadata about an encoded stream
#[derive(Clone, Copy, Dbg, PartialEq)]
pub struct StreamMeta {
    #[dbg(formatter = "compact_dbg")]
    pub stream_type: StreamType,
    #[dbg(formatter = "compact_dbg")]
    pub encoding: IntEncoding,
    pub(crate) num_values: u32,
}

impl StreamMeta {
    #[inline]
    pub(crate) fn new(stream_type: StreamType, encoding: IntEncoding, num_values: u32) -> Self {
        Self {
            stream_type,
            encoding,
            num_values,
        }
    }

    #[inline]
    pub(crate) fn new2(
        stream_type: StreamType,
        logical: LogicalEncoding,
        physical: PhysicalEncoding,
        num_values: usize,
    ) -> MltResult<Self> {
        let enc = IntEncoding::new(logical, physical);
        Ok(Self::new(stream_type, enc, u32::try_from(num_values)?))
    }

    #[inline]
    pub(crate) fn new_none(
        stream_type: StreamType,
        kind: ValueKind,
        num_values: usize,
    ) -> MltResult<Self> {
        let enc = IntEncoding::none(kind);
        Ok(Self::new(stream_type, enc, u32::try_from(num_values)?))
    }
}

/// Representation of an encoded stream
#[derive(Clone, Dbg, PartialEq)]
pub struct RawStream<'a> {
    pub meta: StreamMeta,
    #[dbg(formatter = "bytes_dbg")]
    pub(crate) data: &'a [u8],
}

impl<'a> RawStream<'a> {
    #[must_use]
    pub(crate) fn new(meta: StreamMeta, data: &'a [u8]) -> Self {
        Self { meta, data }
    }
}