mlt-core 0.18.0

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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
//! In-memory model types specific to tag `0x02` (v2) layers.

use num_enum::TryFromPrimitive;

use crate::codecs::morton::{deinterleave_u64, interleave_u32};
use crate::codecs::presence_coding::PresenceCoding;
use crate::codecs::varint::parse_varint;
use crate::decoder::{ColumnStorage, GeometryType, ParsedMValue, ParsedNested, StreamMeta};
use crate::{
    Analyze as _, DecodeState, Layer01, Lazy, LazyParsed, MValueColumn, MltError, MltRefResult,
    MltResult, Nested, Parsed,
};

/// A tag `0x02` layer: the shared [`Layer01`] core plus the columns only v2 has.
///
/// v1 is a subset of v2, so a later version that diverges further gets its own type
/// here rather than more optional fields on the shared one.
#[cfg(feature = "unstable-v2")]
#[derive(Debug, Clone)]
pub struct Layer02<'a, S: DecodeState = Lazy> {
    pub(crate) layer: Layer01<'a, S>,
    /// Nested columns, each a tree over the features it marks present.
    pub(crate) nested: Vec<Nested<'a, S>>,
    /// Vertex-scoped columns, each running over every vertex of every feature
    /// it marks present.
    pub(crate) m_values: Vec<MValueColumn<'a, S>>,
    /// The layer layout byte as parsed. Decoding resolves all three of its fields
    /// away, so it is kept for tools reporting on how a tile is stored.
    pub(crate) layout: LayerLayout,
}

#[cfg(feature = "unstable-v2")]
pub type ParsedLayer02<'a> = Layer02<'a, Parsed>;

#[cfg(feature = "unstable-v2")]
impl<'a, S: DecodeState> Layer02<'a, S> {
    /// The parts this layer shares with every other version.
    #[must_use]
    pub fn layer(&self) -> &Layer01<'a, S> {
        &self.layer
    }

    /// Drop the v2-only columns, keeping the shared core.
    #[must_use]
    pub fn into_layer(self) -> Layer01<'a, S> {
        self.layer
    }

    /// The layer layout byte this layer was written with.
    #[must_use]
    pub fn layout(&self) -> LayerLayout {
        self.layout
    }
}

#[cfg(feature = "unstable-v2")]
impl Layer02<'_, Lazy> {
    /// Walk every stream in this layer, including the v2-only nested and m-value columns.
    pub fn for_each_stream(&self, cb: &mut dyn FnMut(StreamMeta)) {
        self.layer.for_each_stream(cb);
        for nested in &self.nested {
            if let LazyParsed::Raw(raw) = nested {
                raw.for_each_stream(cb);
            }
        }
        for mvalue in &self.m_values {
            if let LazyParsed::Raw(raw) = mvalue {
                raw.for_each_stream(cb);
            }
        }
    }

    /// Walk every column's storage descriptor, including v2-only string m-values and nested string leaves.
    pub fn for_each_column_storage(&self, cb: &mut dyn FnMut(ColumnStorage)) {
        self.layer.for_each_column_storage(cb);
        for mvalue in &self.m_values {
            if let LazyParsed::Raw(raw) = mvalue
                && let Some(storage) = raw.storage()
            {
                cb(storage);
            }
        }
        for nested in &self.nested {
            if let LazyParsed::Raw(raw) = nested {
                raw.for_each_string_storage(cb);
            }
        }
    }
}

#[cfg(feature = "unstable-v2")]
impl ParsedLayer02<'_> {
    #[must_use]
    pub fn m_values(&self) -> &[ParsedMValue<'_>] {
        &self.m_values
    }

    #[must_use]
    pub fn nested(&self) -> &[ParsedNested<'_>] {
        &self.nested
    }
}

/// Data type of a v2 property column, the low nibble of the column type byte.
///
/// Unlike v1's [`super::ColumnType`] there are no `Opt` variants - nullability
/// lives in the high nibble, see [`Presence02`] - and geometry is not a column
/// (the layer's geometry section precedes the counted columns).
/// A string column spends one code, its layout living in the extension bits of
/// its leading stream's encoding byte, see
/// [`StrLayout`](super::stream::header02::StrLayout).
#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromPrimitive)]
#[repr(u8)]
pub(crate) enum DataType02 {
    Id = 0x00,
    LongId = 0x01,
    Bool = 0x02,
    I8 = 0x03,
    U8 = 0x04,
    I32 = 0x05,
    U32 = 0x06,
    I64 = 0x07,
    U64 = 0x08,
    F32 = 0x09,
    F64 = 0x0A,
    Str = 0x0B,
    Struct = 0x0C,
    List = 0x0D,
    Map = 0x0E,
}

impl DataType02 {
    /// Whether the column definition includes a name field.
    /// ID columns use implicit naming, same as v1.
    #[must_use]
    pub(crate) fn has_name(self) -> bool {
        !matches!(self, Self::Id | Self::LongId)
    }
}

/// The interior nodes, the three data types that hold other nodes rather than values.
///
/// Split from [`DataType02`] so a nested column's root, which one of these must be,
/// cannot be a scalar.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Interior02 {
    Struct,
    List,
    Map,
}

impl Interior02 {
    /// Whether a node of this kind ends the implied counts, which a lengths stream does.
    #[must_use]
    pub(crate) fn has_lengths(self) -> bool {
        matches!(self, Self::List | Self::Map)
    }
}

impl From<Interior02> for DataType02 {
    fn from(interior: Interior02) -> Self {
        match interior {
            Interior02::Struct => Self::Struct,
            Interior02::List => Self::List,
            Interior02::Map => Self::Map,
        }
    }
}

/// Where a nested node's presence lives, the high nibble of its node type byte.
///
/// A node below a nested column's root cannot use the layer's shared bitfields,
/// which run over features, so only two nibbles are assigned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NodePresence {
    /// Every value the parent hands this node is present and nothing is stored.
    AllPresent,
    /// A `Bool`-family presence stream follows the node type byte and the field name.
    Stream,
}

impl NodePresence {
    /// Nibble of [`Self::AllPresent`], already shifted into place.
    const ALL_PRESENT: u8 = 0b0000_0000;

    /// Nibble of [`Self::Stream`], already shifted into place.
    const STREAM: u8 = 0b0001_0000;

    /// Nibble bit that says this node's children are shape-coded, already shifted into place.
    ///
    /// Nibble values `0b0010` and `0b0011` are reserved, so this sits above them.
    pub(crate) const SHAPES: u8 = 0b0100_0000;

    /// Read a masked nibble, or [`None`] for one this version has no meaning for.
    ///
    /// The shapes bit is a separate axis and is masked off by the caller.
    #[must_use]
    pub(crate) fn parse(nibble: u8) -> Option<Self> {
        match nibble & !Self::SHAPES {
            Self::ALL_PRESENT => Some(Self::AllPresent),
            Self::STREAM => Some(Self::Stream),
            _ => None,
        }
    }

    #[must_use]
    fn to_nibble(self) -> u8 {
        match self {
            Self::AllPresent => Self::ALL_PRESENT,
            Self::Stream => Self::STREAM,
        }
    }
}

/// What a nested node holds: a leaf's values, or more nodes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NodeKind02 {
    Leaf(ValueType02),
    Struct,
    List,
    Map,
}

impl NodeKind02 {
    /// The interior this kind names, or [`None`] for a leaf.
    #[must_use]
    pub(crate) fn interior(self) -> Option<Interior02> {
        match self {
            Self::Leaf(_) => None,
            Self::Struct => Some(Interior02::Struct),
            Self::List => Some(Interior02::List),
            Self::Map => Some(Interior02::Map),
        }
    }
}

impl From<NodeKind02> for DataType02 {
    fn from(kind: NodeKind02) -> Self {
        match kind {
            NodeKind02::Leaf(values) => values.into(),
            NodeKind02::Struct => Self::Struct,
            NodeKind02::List => Self::List,
            NodeKind02::Map => Self::Map,
        }
    }
}

/// The type byte every node below a nested column's root begins with:
/// [`NodePresence`] in bits 7-4, the data type in bits 3-0.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct NodeType02 {
    pub(crate) presence: NodePresence,
    /// Whether this node's children's structure is coded as one shape id per row.
    pub(crate) shapes: bool,
    pub(crate) data: NodeKind02,
}

impl NodeType02 {
    #[must_use]
    pub(crate) fn new(presence: NodePresence, data: NodeKind02) -> Self {
        Self {
            presence,
            shapes: false,
            data,
        }
    }

    /// The same node type with its children's structure coded as row shapes.
    #[must_use]
    pub(crate) fn shaped(mut self) -> Self {
        self.shapes = true;
        self
    }

    /// Read a wire byte, rejecting the nibbles a node cannot hold.
    pub(crate) fn parse(byte: u8) -> MltResult<Self> {
        let err = || MltError::ParsingColumnType(byte);
        let (nibble, data) = ColumnType02::fields(byte);
        let presence = NodePresence::parse(nibble).ok_or_else(err)?;
        let shapes = nibble & NodePresence::SHAPES != 0;
        let data = DataType02::try_from(data).map_err(|_| err())?;
        let data = match data {
            DataType02::Id | DataType02::LongId => return Err(err()),
            DataType02::Struct => NodeKind02::Struct,
            DataType02::List => NodeKind02::List,
            DataType02::Map => NodeKind02::Map,
            DataType02::Bool => NodeKind02::Leaf(ValueType02::Bool),
            DataType02::I8 => NodeKind02::Leaf(ValueType02::I8),
            DataType02::U8 => NodeKind02::Leaf(ValueType02::U8),
            DataType02::I32 => NodeKind02::Leaf(ValueType02::I32),
            DataType02::U32 => NodeKind02::Leaf(ValueType02::U32),
            DataType02::I64 => NodeKind02::Leaf(ValueType02::I64),
            DataType02::U64 => NodeKind02::Leaf(ValueType02::U64),
            DataType02::F32 => NodeKind02::Leaf(ValueType02::F32),
            DataType02::F64 => NodeKind02::Leaf(ValueType02::F64),
            DataType02::Str => NodeKind02::Leaf(ValueType02::Str),
        };
        Ok(Self {
            presence,
            shapes,
            data,
        })
    }

    #[must_use]
    pub(crate) fn to_byte(self) -> u8 {
        self.presence.to_nibble()
            | if self.shapes { NodePresence::SHAPES } else { 0 }
            | DataType02::from(self.data) as u8
    }
}

/// The type of the values a v2 column holds, the data types that name values.
///
/// Split from [`DataType02`] so a feature id, which is a feature's own rather
/// than one of its values, cannot stand in for a value type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ValueType02 {
    Bool,
    I8,
    U8,
    I32,
    U32,
    I64,
    U64,
    F32,
    F64,
    Str,
}

impl From<ValueType02> for DataType02 {
    fn from(values: ValueType02) -> Self {
        match values {
            ValueType02::Bool => Self::Bool,
            ValueType02::I8 => Self::I8,
            ValueType02::U8 => Self::U8,
            ValueType02::I32 => Self::I32,
            ValueType02::U32 => Self::U32,
            ValueType02::I64 => Self::I64,
            ValueType02::U64 => Self::U64,
            ValueType02::F32 => Self::F32,
            ValueType02::F64 => Self::F64,
            ValueType02::Str => Self::Str,
        }
    }
}

/// The width of a v2 id column, which is all its data type says beyond it being one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IdWidth02 {
    Id32,
    Id64,
}

impl From<IdWidth02> for DataType02 {
    fn from(width: IdWidth02) -> Self {
        match width {
            IdWidth02::Id32 => Self::Id,
            IdWidth02::Id64 => Self::LongId,
        }
    }
}

/// How a shared dictionary stores its corpus, read from the high nibble of its column type byte.
///
/// A shared-dictionary column has no values of its own, so the nibble that names
/// [`Presence02`] elsewhere names the corpus encoding here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum SharedDictKind {
    /// Two streams: the entry lengths, then the entries.
    Plain = 0b0000_0000,
    /// Four streams: the entry lengths, the symbol lengths, the symbol table, then the corpus.
    Fsst = 0b0001_0000,
}

impl SharedDictKind {
    /// Read a masked nibble, or [`None`] for one this version has no meaning for.
    #[must_use]
    pub(crate) fn parse(nibble: u8) -> Option<Self> {
        match nibble {
            0b0000_0000 => Some(Self::Plain),
            0b0001_0000 => Some(Self::Fsst),
            _ => None,
        }
    }
}

/// Where a v2 column's presence bits live and how they are coded, the high nibble
/// of the column type byte.
///
/// Nibble `0` says there are none; `1`-`3` name a [`PresenceCoding`] the column
/// carries itself; `4`-`10` point at one of the layer's shared bitfields; `11`-`15`
/// are reserved.
///
/// The coding rides in the nibble rather than in a byte of its own because the
/// bitmap is still the right answer for most columns, and a tag byte would charge
/// every one of those for the two that are not.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Presence02 {
    /// Every feature has a value and nothing is stored.
    AllPresent,
    /// The column carries its own presence bits, in this coding, after its name.
    Inline(PresenceCoding),
    /// The column reads the layer's shared presence bitfield at this index, so
    /// columns that are null on the same features store one bitfield between them.
    /// See [`LayerLayout::shared_presence`].
    Shared(u8),
}

impl Presence02 {
    /// Nibble of [`Self::AllPresent`], already shifted into place.
    const ALL_PRESENT: u8 = 0b0000_0000;

    /// Nibble of `Shared(0)`; `Shared(i)` is this plus `i << 4`.
    const SHARED_BASE: u8 = 0b0100_0000;

    /// Read a masked presence nibble against a layer that stores `shared_count`
    /// shared bitfields.
    ///
    /// Returns [`None`] for a reference past the last bitfield the layer declared,
    /// which is unreadable.
    #[must_use]
    pub(crate) fn parse(nibble: u8, shared_count: u8) -> Option<Self> {
        match nibble {
            Self::ALL_PRESENT => Some(Self::AllPresent),
            _ if nibble < Self::SHARED_BASE => {
                PresenceCoding::from_byte(nibble >> 4).map(Self::Inline)
            }
            _ => {
                let index = (nibble - Self::SHARED_BASE) >> 4;
                (index < shared_count).then_some(Self::Shared(index))
            }
        }
    }

    /// Whether some features may be null, whichever bitfield holds the answer.
    #[must_use]
    pub(crate) fn is_optional(self) -> bool {
        !matches!(self, Self::AllPresent)
    }

    #[must_use]
    fn to_nibble(self) -> u8 {
        match self {
            Self::AllPresent => Self::ALL_PRESENT,
            Self::Inline(coding) => (coding as u8) << 4,
            Self::Shared(index) => {
                debug_assert!(index < LayerLayout::MAX_SHARED_PRESENCE);
                Self::SHARED_BASE + (index << 4)
            }
        }
    }
}

/// The v2 column type byte: [`Presence02`] in bits 7-4, [`DataType02`] in bits 3-0.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ColumnType02 {
    pub(crate) presence: Presence02,
    pub(crate) data: DataType02,
}

impl ColumnType02 {
    /// Mask of the byte holding the [`Presence02`].
    pub(crate) const PRESENCE_MASK: u8 = 0b1111_0000;

    /// Mask of the byte holding the [`DataType02`].
    pub(crate) const DATA_TYPE_MASK: u8 = 0b0000_1111;

    #[must_use]
    pub(crate) fn new(presence: Presence02, data: DataType02) -> Self {
        Self { presence, data }
    }

    /// Split a wire byte into its two masked fields, without validating either.
    /// Values stay in place, so they compare directly against the enum variants.
    #[must_use]
    pub(crate) fn fields(byte: u8) -> (u8, u8) {
        (byte & Self::PRESENCE_MASK, byte & Self::DATA_TYPE_MASK)
    }

    /// Split a wire byte into its two fields, rejecting reserved bit patterns.
    ///
    /// `shared_count` is [`LayerLayout::shared_presence`] of the enclosing layer,
    /// so a column pointing past the last shared bitfield is rejected here rather
    /// than resolved to a missing one later.
    pub(crate) fn parse(byte: u8, shared_count: u8) -> MltResult<Self> {
        let err = || MltError::ParsingColumnType(byte);
        let (presence, data) = Self::fields(byte);
        let data = DataType02::try_from(data).map_err(|_| err())?;
        let presence = Presence02::parse(presence, shared_count).ok_or_else(err)?;
        Ok(Self { presence, data })
    }

    /// Read this column type as whichever of the two columns its data type names.
    #[must_use]
    pub(crate) fn split(self) -> ColumnKind02 {
        let values = |values| {
            ColumnKind02::Values(ValuesColumn02 {
                presence: self.presence,
                values,
            })
        };
        match self.data {
            DataType02::Id => ColumnKind02::Id(IdWidth02::Id32),
            DataType02::LongId => ColumnKind02::Id(IdWidth02::Id64),
            DataType02::Bool => values(ValueType02::Bool),
            DataType02::I8 => values(ValueType02::I8),
            DataType02::U8 => values(ValueType02::U8),
            DataType02::I32 => values(ValueType02::I32),
            DataType02::U32 => values(ValueType02::U32),
            DataType02::I64 => values(ValueType02::I64),
            DataType02::U64 => values(ValueType02::U64),
            DataType02::F32 => values(ValueType02::F32),
            DataType02::F64 => values(ValueType02::F64),
            DataType02::Str => values(ValueType02::Str),
            DataType02::Struct => ColumnKind02::Nested(NestedColumn02 {
                presence: self.presence,
                root: Interior02::Struct,
            }),
            DataType02::List => ColumnKind02::Nested(NestedColumn02 {
                presence: self.presence,
                root: Interior02::List,
            }),
            DataType02::Map => ColumnKind02::Nested(NestedColumn02 {
                presence: self.presence,
                root: Interior02::Map,
            }),
        }
    }

    #[must_use]
    pub(crate) fn to_byte(self) -> u8 {
        self.presence.to_nibble() | self.data as u8
    }
}

/// What a v2 column type byte names: a feature's id, or one column of its values.
///
/// The two read different fields after the byte - an id column has no name of its
/// own - so nothing but this split can name what follows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ColumnKind02 {
    Id(IdWidth02),
    Values(ValuesColumn02),
    /// The root of a nested column, whose body is a tree of nodes rather than a stream set.
    Nested(NestedColumn02),
}

/// A nested column's root: where its presence bitfield lives, and which interior it is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct NestedColumn02 {
    pub(crate) presence: Presence02,
    pub(crate) root: Interior02,
}

/// A v2 column of values: where its presence bitfield lives, and what its values are.
///
/// Holding one is proof the column is not an id, so the streams and containers a
/// column of values reads never have to consider one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ValuesColumn02 {
    pub(crate) presence: Presence02,
    pub(crate) values: ValueType02,
}

impl ValuesColumn02 {
    /// Read the type byte of an [m-value column](super::root02), which holds neither
    /// a feature id nor a shared dictionary.
    ///
    /// An id belongs to a feature rather than a vertex, and a shared dictionary
    /// introduces counted columns, which the m-value section does not hold.
    pub(crate) fn parse_m_value(byte: u8, shared_count: u8) -> MltResult<Self> {
        match ColumnType02::parse(byte, shared_count)?.split() {
            ColumnKind02::Values(column) => Ok(column),
            ColumnKind02::Id(_) | ColumnKind02::Nested(_) => Err(MltError::ParsingColumnType(byte)),
        }
    }
}

impl From<ValuesColumn02> for ColumnType02 {
    fn from(column: ValuesColumn02) -> Self {
        Self::new(column.presence, column.values.into())
    }
}

/// A v2 column type byte, read as whichever of the two column shapes its data type nibble names.
///
/// The two shapes read the high nibble differently, so nothing but this split can name it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Column02 {
    /// A column of values: [`Presence02`] in the high nibble, [`DataType02`] in the low.
    Values(ColumnType02),
    /// A shared dictionary and the columns indexing it: [`SharedDictKind`] in the high nibble.
    SharedDict(SharedDictKind),
}

impl Column02 {
    /// Data type nibble of [`Self::SharedDict`], the one value no [`DataType02`] takes.
    pub(crate) const SHARED_DICT: u8 = 0x0F;

    /// Read a wire byte in the terms of the shape its data type nibble names.
    ///
    /// `shared_count` is [`LayerLayout::shared_presence`] of the enclosing layer.
    pub(crate) fn parse(byte: u8, shared_count: u8) -> MltResult<Self> {
        let err = || MltError::ParsingColumnType(byte);
        let (high, data) = ColumnType02::fields(byte);
        if data == Self::SHARED_DICT {
            return SharedDictKind::parse(high)
                .map(Self::SharedDict)
                .ok_or_else(err);
        }
        ColumnType02::parse(byte, shared_count).map(Self::Values)
    }
}

/// v2 geometry section layout, the low nibble of the layer layout byte.
///
/// Selects which geometry streams are present and in what fixed order,
/// replacing v1's `stream_count` varint and per-stream `stream_type` bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, TryFromPrimitive, strum::IntoStaticStr)]
#[repr(u8)]
pub enum GeoLayout {
    /// `Types`, `Vertices`
    Points = 0x00,
    /// `Types`, `VertexData` (dict), `VertexOffsets`
    PointsDict = 0x01,
    /// `Types`, `GeoLengths`, `Vertices`
    MultiPoints = 0x02,
    /// `Types`, `GeoLengths`, `VertexData` (dict), `VertexOffsets`
    MultiPointsDict = 0x03,
    /// `Types`, `PartLengths`, `Vertices`
    Lines = 0x04,
    /// `Types`, `PartLengths`, `VertexData` (dict), `VertexOffsets`
    LinesDict = 0x05,
    /// `Types`, `GeoLengths`, `PartLengths`, `Vertices`
    MultiLines = 0x06,
    /// `Types`, `GeoLengths`, `PartLengths`, `VertexData` (dict), `VertexOffsets`
    MultiLinesDict = 0x07,
    /// `Types`, `PartLengths`, `RingLengths`, `Vertices`
    Polygons = 0x08,
    /// `Types`, `PartLengths`, `RingLengths`, `VertexData` (dict), `VertexOffsets`
    PolygonsDict = 0x09,
    /// `Types`, `GeoLengths`, `PartLengths`, `RingLengths`, `Vertices`
    MultiPolygons = 0x0A,
    /// `Types`, `GeoLengths`, `PartLengths`, `RingLengths`, `VertexData` (dict), `VertexOffsets`
    MultiPolygonsDict = 0x0B,
    /// `Types`, `TriLengths`, `IndexBuffer`, `Vertices`
    TessPolygons = 0x0C,
    /// `Types`, `GeoLengths`, `PartLengths`, `RingLengths`, `TriLengths`, `IndexBuffer`, `Vertices`
    TessPolygonsWithOutlines = 0x0D,
}

/// How a v2 geometry section stores its vertices, which [`GeoLayout`] names alongside the topology.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum VertexStorage {
    /// One entry per vertex, in a single stream.
    Plain,
    /// The distinct vertices once, then one index per vertex into them.
    Dict,
}

/// The nesting of a v2 geometry section below the geometry level, carrying the streams that name it.
///
/// A ring level with no part level above it is not a shape the geometry model can
/// produce, so it is not a shape this type can hold.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Topology {
    /// No nesting: a geometry addresses its vertices directly.
    Flat,
    /// One part per geometry, each addressing its vertices directly.
    Parts(Vec<u32>),
    /// One part per geometry, each addressing a run of rings.
    PartsAndRings { parts: Vec<u32>, rings: Vec<u32> },
}

impl Topology {
    /// The part and ring length streams, in wire order.
    pub(crate) fn streams(&self) -> (Option<&[u32]>, Option<&[u32]>) {
        match self {
            Self::Flat => (None, None),
            Self::Parts(parts) => (Some(parts), None),
            Self::PartsAndRings { parts, rings } => (Some(parts), Some(rings)),
        }
    }

    /// Widen to the full part-and-ring nesting, padding a level this layer never used.
    #[must_use]
    pub(crate) fn with_rings(self) -> Self {
        match self {
            Self::Flat => Self::PartsAndRings {
                parts: Vec::new(),
                rings: Vec::new(),
            },
            Self::Parts(parts) => Self::PartsAndRings {
                parts,
                rings: Vec::new(),
            },
            rings @ Self::PartsAndRings { .. } => rings,
        }
    }
}

impl GeoLayout {
    /// Layout for a stream set with plain or dictionary vertices.
    ///
    /// `has_geo` is independent of the nesting below it: any [`Topology`] can be
    /// addressed either per feature or per sub-geometry.
    #[must_use]
    pub(crate) fn from_topology(
        topology: &Topology,
        has_geo: bool,
        vertices: VertexStorage,
    ) -> Self {
        use VertexStorage as V;
        match (topology, has_geo, vertices) {
            (Topology::Flat, false, V::Plain) => Self::Points,
            (Topology::Flat, false, V::Dict) => Self::PointsDict,
            (Topology::Flat, true, V::Plain) => Self::MultiPoints,
            (Topology::Flat, true, V::Dict) => Self::MultiPointsDict,
            (Topology::Parts(_), false, V::Plain) => Self::Lines,
            (Topology::Parts(_), false, V::Dict) => Self::LinesDict,
            (Topology::Parts(_), true, V::Plain) => Self::MultiLines,
            (Topology::Parts(_), true, V::Dict) => Self::MultiLinesDict,
            (Topology::PartsAndRings { .. }, false, V::Plain) => Self::Polygons,
            (Topology::PartsAndRings { .. }, false, V::Dict) => Self::PolygonsDict,
            (Topology::PartsAndRings { .. }, true, V::Plain) => Self::MultiPolygons,
            (Topology::PartsAndRings { .. }, true, V::Dict) => Self::MultiPolygonsDict,
        }
    }

    /// Layout for a tessellated stream set, which keeps its vertices plain.
    ///
    /// Tessellation pairs with the full outline topology or with none of it, so a
    /// layer holding only part of it pads the streams it is missing with empty ones.
    #[must_use]
    pub(crate) fn tessellated(has_outlines: bool) -> Self {
        if has_outlines {
            Self::TessPolygonsWithOutlines
        } else {
            Self::TessPolygons
        }
    }

    #[must_use]
    pub(crate) fn has_geo_lengths(self) -> bool {
        matches!(
            self,
            Self::MultiPoints
                | Self::MultiPointsDict
                | Self::MultiLines
                | Self::MultiLinesDict
                | Self::MultiPolygons
                | Self::MultiPolygonsDict
                | Self::TessPolygonsWithOutlines
        )
    }

    #[must_use]
    pub(crate) fn has_part_lengths(self) -> bool {
        matches!(
            self,
            Self::Lines
                | Self::LinesDict
                | Self::MultiLines
                | Self::MultiLinesDict
                | Self::Polygons
                | Self::PolygonsDict
                | Self::MultiPolygons
                | Self::MultiPolygonsDict
                | Self::TessPolygonsWithOutlines
        )
    }

    #[must_use]
    pub(crate) fn has_ring_lengths(self) -> bool {
        matches!(
            self,
            Self::Polygons
                | Self::PolygonsDict
                | Self::MultiPolygons
                | Self::MultiPolygonsDict
                | Self::TessPolygonsWithOutlines
        )
    }

    /// Whether vertex data is stored as a dictionary + offsets pair.
    #[must_use]
    pub(crate) fn is_dict(self) -> bool {
        matches!(
            self,
            Self::PointsDict
                | Self::MultiPointsDict
                | Self::LinesDict
                | Self::MultiLinesDict
                | Self::PolygonsDict
                | Self::MultiPolygonsDict
        )
    }

    /// Whether the topology gives every feature's vertex count, which an
    /// [m-value column](super::root02) needs to read its values back per feature.
    ///
    /// A point layer holds one vertex per feature, so a vertex-scoped column there
    /// is a property column. A tessellated layer without outlines has no per-feature
    /// vertex count at all.
    #[must_use]
    pub(crate) fn allows_m_values(self) -> bool {
        !matches!(self, Self::Points | Self::PointsDict | Self::TessPolygons)
    }

    /// Whether tessellation streams (`TriLengths`, `IndexBuffer`) are present.
    #[must_use]
    pub(crate) fn is_tess(self) -> bool {
        matches!(self, Self::TessPolygons | Self::TessPolygonsWithOutlines)
    }
}

/// The v2 extent code, the low nibble of the [`LayerHeader02`] byte.
///
/// v2 stores only power-of-two extents, so the nibble holds `log2(extent) - 6`
/// rather than the extent itself: `0x0` is 64 and `0xF` is 2097152.
/// Every code is assigned, so no nibble is rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Extent02(u8);

impl Extent02 {
    /// Mask of the nibble holding the extent code.
    const MAX_EXPONENT: u8 = 0b0000_1111;
    pub(crate) const EXPONENT_MASK: u8 = Self::MAX_EXPONENT;

    /// Exponent of the smallest extent, which the code is offset by.
    const EXPONENT_OFFSET: u32 = 6;

    /// Code an extent, rejecting one that is not a power of two in `64..=2097152`.
    pub(crate) fn new(extent: u32) -> MltResult<Self> {
        if extent.is_power_of_two()
            && let Some(code) = extent.ilog2().checked_sub(Self::EXPONENT_OFFSET)
            && code <= u32::from(Self::MAX_EXPONENT)
        {
            #[expect(clippy::cast_possible_truncation, reason = "16 < 256")]
            Ok(Self(code as u8))
        } else {
            Err(MltError::UnsupportedExtent02(extent))
        }
    }

    /// Read the code out of a header byte, ignoring the fields above it.
    #[must_use]
    pub(crate) fn from_byte(byte: u8) -> Self {
        Self(byte & Self::EXPONENT_MASK)
    }

    /// The extent itself, always a power of two in `64..=2097152`.
    #[must_use]
    pub(crate) fn get(self) -> u32 {
        1 << (u32::from(self.0) + Self::EXPONENT_OFFSET)
    }

    #[must_use]
    pub(crate) fn to_nibble(self) -> u8 {
        self.0
    }
}

/// The v2 layer header byte: an m-value flag in bit 7, the uniform geometry type
/// in bits 6-4, the [`Extent02`] code in bits 3-0.
///
/// The m-value flag sits here rather than in the [`LayerLayout`] byte.
/// That leaves the layout byte's high nibble whole for the shared presence count.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct LayerHeader02 {
    /// Whether an [m-value section](super::root02) ends the layer body, after the
    /// counted columns.
    pub(crate) m_values: bool,
    /// The type every feature has, when the geometry section writes no types stream.
    ///
    /// Such a types stream is a single run holding nothing this nibble cannot.
    pub(crate) uniform_type: Option<GeometryType>,
    pub(crate) extent: Extent02,
}

impl LayerHeader02 {
    /// Mask of the bit saying an [m-value section](super::root02) ends the body.
    pub(crate) const M_VALUES_MASK: u8 = 0b1000_0000;

    /// Mask of the nibble holding the uniform geometry type.
    pub(crate) const UNIFORM_TYPE_MASK: u8 = 0b0111_0000;

    /// Uniform type code of a layer whose geometry section leads with a types stream.
    const TYPES_STREAM: u8 = 0;

    #[must_use]
    pub(crate) fn new(
        extent: Extent02,
        uniform_type: Option<GeometryType>,
        m_values: bool,
    ) -> Self {
        Self {
            m_values,
            uniform_type,
            extent,
        }
    }

    /// Split a wire byte into its three fields, without validating any of them.
    /// The m-value flag stays in place, the other two are shifted down.
    #[must_use]
    fn fields(byte: u8) -> (u8, u8, u8) {
        (
            byte & Self::M_VALUES_MASK,
            (byte & Self::UNIFORM_TYPE_MASK) >> 4,
            byte & Extent02::EXPONENT_MASK,
        )
    }

    /// Read the uniform type nibble of a wire byte, rejecting the one code no
    /// geometry type takes.
    fn parse_uniform_type(byte: u8) -> MltResult<Option<GeometryType>> {
        let (_, nibble, _) = Self::fields(byte);
        if nibble == Self::TYPES_STREAM {
            return Ok(None);
        }
        GeometryType::try_from(nibble - 1)
            .map(Some)
            .map_err(|_| MltError::ParsingLayerHeader02(byte))
    }

    /// Split a wire byte into its three fields, rejecting reserved bit patterns.
    pub(crate) fn parse(byte: u8) -> MltResult<Self> {
        let (m_values, _, _) = Self::fields(byte);
        Ok(Self {
            m_values: m_values != 0,
            uniform_type: Self::parse_uniform_type(byte)?,
            extent: Extent02::from_byte(byte),
        })
    }

    #[must_use]
    pub(crate) fn to_byte(self) -> u8 {
        let m_values = if self.m_values {
            Self::M_VALUES_MASK
        } else {
            0
        };
        let uniform = self
            .uniform_type
            .map_or(Self::TYPES_STREAM, |t| t as u8 + 1);
        m_values | (uniform << 4) | self.extent.to_nibble()
    }
}

/// The v2 layer layout byte: the shared coding flag in bit 7, the shared presence
/// bitfield count in bits 6-4, [`GeoLayout`] in bits 3-0.
///
/// It sits at the layer root, right after the layer header byte, and every
/// bit of it is spent. Decoding resolves all three fields away, so a layer keeps
/// the parsed byte for tools reporting on how a tile is stored.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LayerLayout {
    /// How many shared presence bitfields the layer stores, at most 7.
    ///
    /// The bitfields themselves follow this byte immediately, before the geometry
    /// section, in index order. Columns read one through their shared presence
    /// nibble, so a set of columns that are null on the same features pays for one
    /// bitfield rather than one each.
    pub shared_presence: u8,
    /// Whether each shared bitfield leads with the byte naming its presence coding.
    /// Without it every shared bitfield is a plain bitmap.
    pub shared_coded: bool,
    /// Which streams the geometry section holds, and in what order.
    pub geometry: GeoLayout,
}

impl LayerLayout {
    /// Bit of the byte saying the shared bitfields carry their coding.
    pub(crate) const SHARED_CODED_BIT: u8 = 0b1000_0000;

    /// Mask of the byte holding the shared presence column count.
    pub(crate) const SHARED_PRESENCE_MASK: u8 = 0b0111_0000;

    /// Mask of the byte holding the [`GeoLayout`].
    pub(crate) const GEO_LAYOUT_MASK: u8 = 0b0000_1111;

    /// Largest shared presence column count a layer can use, which is all its
    /// three bits can hold.
    pub(crate) const MAX_SHARED_PRESENCE: u8 = 7;

    #[must_use]
    pub(crate) fn new(geometry: GeoLayout, shared_presence: u8, shared_coded: bool) -> Self {
        debug_assert!(shared_presence <= Self::MAX_SHARED_PRESENCE);
        debug_assert!(shared_presence > 0 || !shared_coded);
        Self {
            shared_presence,
            shared_coded,
            geometry,
        }
    }

    /// Split a wire byte into its three fields, without validating any.
    #[must_use]
    pub(crate) fn fields(byte: u8) -> (bool, u8, u8) {
        (
            byte & Self::SHARED_CODED_BIT != 0,
            (byte & Self::SHARED_PRESENCE_MASK) >> 4,
            byte & Self::GEO_LAYOUT_MASK,
        )
    }

    /// Split a wire byte into its fields, rejecting reserved bit patterns.
    pub(crate) fn parse(byte: u8) -> MltResult<Self> {
        let (shared_coded, shared_presence, geometry) = Self::fields(byte);
        // A coding flag with no bitfield to code has a canonical spelling without it.
        if shared_coded && shared_presence == 0 {
            return Err(MltError::ParsingLayerLayout02(byte));
        }
        let geometry =
            GeoLayout::try_from(geometry).map_err(|_| MltError::ParsingGeoLayout(geometry))?;
        Ok(Self {
            shared_presence,
            shared_coded,
            geometry,
        })
    }

    #[must_use]
    pub(crate) fn to_byte(self) -> u8 {
        debug_assert!(self.shared_presence <= Self::MAX_SHARED_PRESENCE);
        let coded = if self.shared_coded {
            Self::SHARED_CODED_BIT
        } else {
            0
        };
        coded | (self.shared_presence << 4) | self.geometry as u8
    }
}

/// The column counts a v2 layer writes between its geometry section and its columns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ColumnCounts {
    /// Counted columns: ids, properties and nested columns.
    pub(crate) columns: u32,
    /// M-value columns, zero when the header byte has no m-value section.
    pub(crate) m_values: u32,
}

impl ColumnCounts {
    /// Parse the counts varint, a Morton code of both counts when the header byte says an m-value section follows.
    pub(crate) fn parse(input: &[u8], m_values: bool) -> MltRefResult<'_, Self> {
        if !m_values {
            let (input, columns) = parse_varint::<u32>(input)?;
            return Ok((
                input,
                Self {
                    columns,
                    m_values: 0,
                },
            ));
        }
        let (input, code) = parse_varint::<u64>(input)?;
        let (columns, m_values) = deinterleave_u64(code);
        if m_values == 0 {
            return Err(MltError::EmptyMValueSection);
        }
        Ok((input, Self { columns, m_values }))
    }

    /// The varint value the counts are written as, the inverse of [`Self::parse`].
    #[must_use]
    pub(crate) fn to_varint(self) -> u64 {
        if self.m_values == 0 {
            u64::from(self.columns)
        } else {
            interleave_u32(self.columns, self.m_values)
        }
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    /// Shared bitfield count of a layer that declares as many as the byte allows.
    const ALL_SHARED: u8 = LayerLayout::MAX_SHARED_PRESENCE;

    fn parts_and_rings() -> Topology {
        Topology::PartsAndRings {
            parts: vec![1],
            rings: vec![4],
        }
    }

    #[rstest]
    #[case::id(0b0000_0000, Presence02::AllPresent, DataType02::Id)]
    #[case::opt_id(
        0b0001_0000,
        Presence02::Inline(PresenceCoding::Bitmap),
        DataType02::Id
    )]
    #[case::i32(0b0000_0101, Presence02::AllPresent, DataType02::I32)]
    #[case::opt_f64(
        0b0001_1010,
        Presence02::Inline(PresenceCoding::Bitmap),
        DataType02::F64
    )]
    #[case::runs(0b0010_0101, Presence02::Inline(PresenceCoding::Runs), DataType02::I32)]
    #[case::indices(
        0b0011_1010,
        Presence02::Inline(PresenceCoding::Indices),
        DataType02::F64
    )]
    #[case::str(0b0000_1011, Presence02::AllPresent, DataType02::Str)]
    #[case::first_shared(0b0100_0101, Presence02::Shared(0), DataType02::I32)]
    #[case::last_shared(0b1010_1010, Presence02::Shared(6), DataType02::F64)]
    fn column_type_byte_roundtrip(
        #[case] byte: u8,
        #[case] presence: Presence02,
        #[case] data: DataType02,
    ) {
        let typ = ColumnType02::parse(byte, ALL_SHARED).unwrap();
        assert_eq!(typ, ColumnType02::new(presence, data));
        assert_eq!(typ.to_byte(), byte);
    }

    #[rstest]
    #[case::values(
        0b0001_0101,
        Column02::Values(ColumnType02::new(
            Presence02::Inline(PresenceCoding::Bitmap),
            DataType02::I32
        ))
    )]
    #[case::plain_shared_dict(0b0000_1111, Column02::SharedDict(SharedDictKind::Plain))]
    #[case::fsst_shared_dict(0b0001_1111, Column02::SharedDict(SharedDictKind::Fsst))]
    fn column_byte_names_the_shape_it_holds(#[case] byte: u8, #[case] column: Column02) {
        assert_eq!(Column02::parse(byte, ALL_SHARED).unwrap(), column);
    }

    #[rstest]
    #[case::smallest(64, 0x00)]
    #[case::mvt_default(4096, 0x06)]
    #[case::wider_than_a_morton_code(65_536, 0x0A)]
    #[case::largest(2_097_152, 0x0F)]
    fn an_extent_round_trips_through_its_nibble(#[case] extent: u32, #[case] byte: u8) {
        let coded = Extent02::new(extent).unwrap();
        assert_eq!(coded.to_nibble(), byte);
        assert_eq!(coded.get(), extent);
        assert_eq!(Extent02::from_byte(byte), coded);
    }

    #[rstest]
    #[case::zero(0)]
    #[case::one(1)]
    #[case::below_the_smallest(32)]
    #[case::not_a_power_of_two(80)]
    #[case::a_multiple_of_the_smallest(192)]
    #[case::a_power_of_two_plus_a_multiple_of_the_smallest(33_024)]
    #[case::just_over_the_largest(2_097_153)]
    #[case::a_power_of_two_over_the_largest(4_194_304)]
    fn an_extent_outside_the_nibble_is_rejected(#[case] extent: u32) {
        let err = Extent02::new(extent).unwrap_err();
        assert!(matches!(err, MltError::UnsupportedExtent02(e) if e == extent));
    }

    #[rstest]
    #[case::extent_only(0x06, false, None, 4096)]
    #[case::m_values(0x86, true, None, 4096)]
    #[case::uniform_points(0x16, false, Some(GeometryType::Point), 4096)]
    #[case::uniform_multi_polygons(0x60, false, Some(GeometryType::MultiPolygon), 64)]
    #[case::m_values_over_a_uniform_type(0xCF, true, Some(GeometryType::MultiPoint), 2_097_152)]
    fn layer_header_byte_roundtrip(
        #[case] byte: u8,
        #[case] m_values: bool,
        #[case] uniform_type: Option<GeometryType>,
        #[case] extent: u32,
    ) {
        let header = LayerHeader02::parse(byte).unwrap();
        assert_eq!(
            header,
            LayerHeader02::new(Extent02::new(extent).unwrap(), uniform_type, m_values)
        );
        assert_eq!(header.extent.get(), extent);
        assert_eq!(header.to_byte(), byte);
    }

    #[rstest]
    #[case::reserved_uniform_type(0x70)]
    #[case::reserved_uniform_type_over_an_extent(0x7F)]
    #[case::reserved_uniform_type_with_m_values(0xF6)]
    fn layer_header_byte_rejects_the_reserved_uniform_type(#[case] byte: u8) {
        let err = LayerHeader02::parse(byte).unwrap_err();
        assert!(matches!(err, MltError::ParsingLayerHeader02(b) if b == byte));
    }

    #[rstest]
    #[case::reserved_shared_dict_corpus(0b0010_1111, ALL_SHARED)]
    #[case::shared_ref_past_declared_count_over_a_nested_root(0b1001_1100, 4)]
    fn column_byte_rejects_unassigned(#[case] byte: u8, #[case] shared_count: u8) {
        let err = Column02::parse(byte, shared_count).unwrap_err();
        assert!(matches!(err, MltError::ParsingColumnType(b) if b == byte));
    }

    #[rstest]
    #[case::shared_dict_is_not_a_data_type(0b0000_1111, ALL_SHARED)]
    #[case::shared_ref_past_declared_count_over_a_nested_root(0b1001_1100, 4)]
    #[case::shared_ref_past_declared_count(0b1001_0101, 3)]
    #[case::shared_ref_one_past_the_last_bitfield(0b1011_0101, ALL_SHARED)]
    #[case::reserved_shared_nibble(0b1111_0101, ALL_SHARED)]
    #[case::shared_ref_without_shared_columns(0b0100_0101, 0)]
    #[case::shared_ref_past_declared_count(0b0101_0101, 1)]
    #[case::unassigned_inline_coding(0b0101_0101, 0)]
    fn column_type_byte_rejects_unassigned(#[case] byte: u8, #[case] shared_count: u8) {
        let err = ColumnType02::parse(byte, shared_count).unwrap_err();
        assert!(matches!(err, MltError::ParsingColumnType(b) if b == byte));
    }

    #[rstest]
    #[case::points(Topology::Flat, false, VertexStorage::Plain, GeoLayout::Points)]
    #[case::points_dict(Topology::Flat, false, VertexStorage::Dict, GeoLayout::PointsDict)]
    #[case::multi_points(Topology::Flat, true, VertexStorage::Plain, GeoLayout::MultiPoints)]
    #[case::lines_dict(Topology::Parts(vec![2]), false, VertexStorage::Dict, GeoLayout::LinesDict)]
    #[case::multi_lines(Topology::Parts(vec![2]), true, VertexStorage::Plain, GeoLayout::MultiLines)]
    #[case::polygons(parts_and_rings(), false, VertexStorage::Plain, GeoLayout::Polygons)]
    #[case::multi_polygons_dict(
        parts_and_rings(),
        true,
        VertexStorage::Dict,
        GeoLayout::MultiPolygonsDict
    )]
    fn a_stream_set_picks_its_layout(
        #[case] topology: Topology,
        #[case] has_geo: bool,
        #[case] vertices: VertexStorage,
        #[case] expected: GeoLayout,
    ) {
        let layout = GeoLayout::from_topology(&topology, has_geo, vertices);
        let (parts, rings) = topology.streams();
        assert_eq!(layout, expected);
        assert_eq!(layout.has_geo_lengths(), has_geo);
        assert_eq!(layout.has_part_lengths(), parts.is_some());
        assert_eq!(layout.has_ring_lengths(), rings.is_some());
        assert_eq!(layout.is_dict(), vertices == VertexStorage::Dict);
        assert!(!layout.is_tess());
    }

    #[rstest]
    #[case::tess(false, GeoLayout::TessPolygons)]
    #[case::tess_with_outlines(true, GeoLayout::TessPolygonsWithOutlines)]
    fn a_tessellated_stream_set_picks_its_layout(
        #[case] has_outlines: bool,
        #[case] expected: GeoLayout,
    ) {
        let layout = GeoLayout::tessellated(has_outlines);
        assert_eq!(layout, expected);
        assert!(layout.is_tess());
        assert!(!layout.is_dict());
        assert_eq!(layout.has_geo_lengths(), has_outlines);
        assert_eq!(layout.has_part_lengths(), has_outlines);
        assert_eq!(layout.has_ring_lengths(), has_outlines);
    }

    #[rstest]
    #[case::flat(Topology::Flat)]
    #[case::parts(Topology::Parts(vec![2]))]
    #[case::parts_and_rings(parts_and_rings())]
    fn a_topology_widened_to_rings_keeps_both_streams(#[case] topology: Topology) {
        let widened = topology.with_rings();
        let (parts, rings) = widened.streams();
        assert!(parts.is_some() && rings.is_some());
    }

    #[rstest]
    #[case::points(0b0000_0000, 0, false, GeoLayout::Points)]
    #[case::multi_polygons(0b0000_1010, 0, false, GeoLayout::MultiPolygons)]
    #[case::one_shared_presence(0b0001_0100, 1, false, GeoLayout::Lines)]
    #[case::max_shared_presence(0b0111_0000, ALL_SHARED, false, GeoLayout::Points)]
    #[case::one_coded_shared_presence(0b1001_0100, 1, true, GeoLayout::Lines)]
    #[case::max_coded_shared_presence(0b1111_0110, ALL_SHARED, true, GeoLayout::MultiLines)]
    fn layer_layout_byte_roundtrip(
        #[case] byte: u8,
        #[case] shared_presence: u8,
        #[case] shared_coded: bool,
        #[case] geometry: GeoLayout,
    ) {
        let layout = LayerLayout::parse(byte).unwrap();
        assert_eq!(
            layout,
            LayerLayout::new(geometry, shared_presence, shared_coded)
        );
        assert_eq!(layout.to_byte(), byte);
    }

    #[rstest]
    #[case::no_bitfield(0b1000_0000)]
    #[case::no_bitfield_over_a_geo_layout(0b1000_1010)]
    fn layer_layout_byte_rejects_a_coding_flag_with_nothing_to_code(#[case] byte: u8) {
        let err = LayerLayout::parse(byte).unwrap_err();
        assert!(matches!(err, MltError::ParsingLayerLayout02(b) if b == byte));
    }

    #[rstest]
    #[case::bool(0b0000_0010, ValueType02::Bool)]
    #[case::opt_i32(0b0001_0101, ValueType02::I32)]
    #[case::shared_f64(0b0100_1010, ValueType02::F64)]
    #[case::str(0b0000_1011, ValueType02::Str)]
    fn m_value_type_byte_roundtrip(#[case] byte: u8, #[case] values: ValueType02) {
        let column = ValuesColumn02::parse_m_value(byte, ALL_SHARED).unwrap();
        assert_eq!(column.values, values);
        assert_eq!(ColumnType02::from(column).to_byte(), byte);
    }

    #[rstest]
    #[case::id(0b0000_0000)]
    #[case::opt_id(0b0001_0000)]
    #[case::long_id(0b0000_0001)]
    #[case::shared_dict(0b0000_1111)]
    #[case::struct_root(0b0000_1100)]
    #[case::list_root(0b0000_1101)]
    #[case::map_root(0b0000_1110)]
    fn m_value_type_byte_rejects_what_a_vertex_cannot_hold(#[case] byte: u8) {
        let err = ValuesColumn02::parse_m_value(byte, ALL_SHARED).unwrap_err();
        assert!(matches!(err, MltError::ParsingColumnType(b) if b == byte));
    }

    #[test]
    fn an_m_value_column_cannot_name_a_bitfield_the_layer_lacks() {
        let byte = 0b1001_0101;
        let err = ValuesColumn02::parse_m_value(byte, 4).unwrap_err();
        assert!(matches!(err, MltError::ParsingColumnType(b) if b == byte));
    }

    #[rstest]
    #[case::points(GeoLayout::Points, false)]
    #[case::points_dict(GeoLayout::PointsDict, false)]
    #[case::multi_points(GeoLayout::MultiPoints, true)]
    #[case::lines(GeoLayout::Lines, true)]
    #[case::multi_polygons_dict(GeoLayout::MultiPolygonsDict, true)]
    #[case::tess_polygons(GeoLayout::TessPolygons, false)]
    #[case::tess_polygons_with_outlines(GeoLayout::TessPolygonsWithOutlines, true)]
    fn only_a_layout_with_per_feature_vertex_counts_takes_m_values(
        #[case] layout: GeoLayout,
        #[case] allowed: bool,
    ) {
        assert_eq!(layout.allows_m_values(), allowed);
    }

    #[rstest]
    #[case::i32_leaf(
        0b0000_0101,
        NodePresence::AllPresent,
        NodeKind02::Leaf(ValueType02::I32)
    )]
    #[case::optional_str_leaf(
        0b0001_1011,
        NodePresence::Stream,
        NodeKind02::Leaf(ValueType02::Str)
    )]
    #[case::struct_node(0b0000_1100, NodePresence::AllPresent, NodeKind02::Struct)]
    #[case::optional_list_node(0b0001_1101, NodePresence::Stream, NodeKind02::List)]
    #[case::map_node(0b0000_1110, NodePresence::AllPresent, NodeKind02::Map)]
    fn node_type_byte_roundtrip(
        #[case] byte: u8,
        #[case] presence: NodePresence,
        #[case] data: NodeKind02,
    ) {
        let typ = NodeType02::parse(byte).unwrap();
        assert_eq!(typ, NodeType02::new(presence, data));
        assert_eq!(typ.to_byte(), byte);
    }

    #[rstest]
    #[case::shaped_struct(0b0100_1100, NodePresence::AllPresent, NodeKind02::Struct)]
    #[case::shaped_map_over_nulls(0b0101_1110, NodePresence::Stream, NodeKind02::Map)]
    fn the_shapes_bit_reads_beside_a_nodes_own_presence(
        #[case] byte: u8,
        #[case] presence: NodePresence,
        #[case] data: NodeKind02,
    ) {
        let typ = NodeType02::parse(byte).unwrap();
        assert_eq!(typ, NodeType02::new(presence, data).shaped());
        assert!(typ.shapes);
        assert_eq!(typ.to_byte(), byte);
    }

    #[rstest]
    #[case::id_is_a_features_own(0b0000_0000)]
    #[case::long_id_is_a_features_own(0b0000_0001)]
    #[case::shared_dict_introduces_columns(0b0000_1111)]
    #[case::reserved_node_presence(0b0010_0101)]
    #[case::reserved_node_presence_top(0b1111_0101)]
    fn node_type_byte_rejects_what_a_node_cannot_hold(#[case] byte: u8) {
        let err = NodeType02::parse(byte).unwrap_err();
        assert!(matches!(err, MltError::ParsingColumnType(b) if b == byte));
    }

    #[rstest]
    #[case::struct_root(0b0000_1100, Interior02::Struct)]
    #[case::list_root(0b0001_1101, Interior02::List)]
    #[case::map_root(0b0010_1110, Interior02::Map)]
    fn a_nested_root_reads_as_the_interior_its_nibble_names(
        #[case] byte: u8,
        #[case] root: Interior02,
    ) {
        let typ = ColumnType02::parse(byte, ALL_SHARED).unwrap();
        let ColumnKind02::Nested(column) = typ.split() else {
            panic!("expected a nested root")
        };
        assert_eq!(column.root, root);
        assert_eq!(typ.to_byte(), byte);
    }

    fn varint(value: u64) -> Vec<u8> {
        let mut buf = [0u8; 10];
        let written = integer_encoding::VarInt::encode_var(value, &mut buf);
        buf[..written].to_vec()
    }

    #[rstest]
    #[case::no_m_values(false, 0, 0, &[0x00])]
    #[case::three_columns(false, 3, 0, &[0x03])]
    #[case::one_m_value(true, 0, 1, &[0x02])]
    #[case::three_columns_two_m_values(true, 3, 2, &[0b0000_1101])]
    #[case::one_byte_limits(true, 15, 7, &[0x7F])]
    #[case::sixteen_columns_spill_over(true, 16, 1, &[0x82, 0x02])]
    #[case::eight_m_values_spill_over(true, 0, 8, &[0x80, 0x01])]
    fn column_counts_roundtrip(
        #[case] m_values: bool,
        #[case] columns: u32,
        #[case] m_value_columns: u32,
        #[case] bytes: &[u8],
    ) {
        let counts = ColumnCounts {
            columns,
            m_values: m_value_columns,
        };
        assert_eq!(varint(counts.to_varint()), bytes);
        assert_eq!(
            ColumnCounts::parse(bytes, m_values).unwrap(),
            (&[][..], counts)
        );
    }

    #[rstest]
    #[case::no_columns(&[0x00])]
    #[case::columns_only(&[0x05])]
    fn column_counts_reject_a_flagged_section_without_m_values(#[case] bytes: &[u8]) {
        let err = ColumnCounts::parse(bytes, true).unwrap_err();
        assert!(matches!(err, MltError::EmptyMValueSection));
    }

    #[rstest]
    #[case::unassigned_geo_layout(0b0000_1110)]
    #[case::unassigned_geo_layout_with_shared(0b0010_1111)]
    fn layer_layout_byte_rejects_unassigned_geo_layout(#[case] byte: u8) {
        let err = LayerLayout::parse(byte).unwrap_err();
        assert!(
            matches!(err, MltError::ParsingGeoLayout(b) if b == byte & LayerLayout::GEO_LAYOUT_MASK)
        );
    }
}