1use std::borrow::Cow;
2#[cfg(feature = "unstable-v2")]
3use std::collections::HashSet;
4
5use derive_debug::Dbg;
6
7#[cfg(feature = "unstable-v2")]
8use crate::decoder::RleLayout;
9use crate::decoder::{DictionaryType, FastPForKind, GeometryValues, PhysicalEncoding, StreamType};
10use crate::encoder::geometry::VertexBufferType;
11use crate::encoder::{IntEncoder, StagedId, StagedProperty};
12#[cfg(feature = "unstable-v2")]
13use crate::encoder::{StagedInterior, StagedMValue, StagedNested, StagedNode};
14#[cfg(feature = "unstable-v2")]
15use crate::tile::MAX_NESTED_DEPTH;
16use crate::tile::{ColumnRole, Extent, reject_taken_name};
17use crate::{MltError, MltResult};
18
19#[derive(Debug, Clone, Default, PartialEq)]
21pub struct EncodedUnknown {
22 pub(crate) tag: u8,
23 pub(crate) value: Vec<u8>,
24}
25
26impl EncodedUnknown {
27 pub fn new(tag: u8, value: Vec<u8>) -> MltResult<Self> {
28 if tag == 1 {
29 return Err(MltError::ParsingColumnType(tag));
30 }
31 Ok(Self { tag, value })
32 }
33
34 #[must_use]
35 pub fn tag(&self) -> u32 {
36 u32::from(self.tag)
37 }
38
39 #[must_use]
40 pub fn data(&self) -> &[u8] {
41 &self.value
42 }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq)]
48pub struct CurveParams {
49 pub shift: u32,
50 pub bits: u32,
51}
52
53impl Default for CurveParams {
54 fn default() -> Self {
55 Self { shift: 0, bits: 1 }
56 }
57}
58
59impl CurveParams {
60 #[must_use]
62 pub fn from_vertices(vertices: &[i32]) -> Self {
63 if vertices.is_empty() {
64 return Self::default();
65 }
66 let (min, max) = vertices
67 .iter()
68 .fold((i32::MAX, i32::MIN), |(mn, mx), &v| (mn.min(v), mx.max(v)));
69 crate::codecs::hilbert::hilbert_curve_params_from_bounds(min, max)
70 }
71}
72
73#[derive(Debug, PartialEq, Clone)]
80pub struct StagedLayer {
81 pub(crate) name: String,
82 pub(crate) extent: Extent,
83 pub(crate) id: StagedId,
84 pub(crate) geometry: GeometryValues,
85 pub(crate) properties: Vec<StagedProperty>,
86 #[cfg(feature = "unstable-v2")]
88 pub(crate) m_values: Vec<StagedMValue>,
89 #[cfg(feature = "unstable-v2")]
91 pub(crate) nested: Vec<StagedNested>,
92}
93
94#[cfg_attr(not(feature = "__private"), allow(dead_code))]
95impl StagedLayer {
96 pub fn new(
97 name: impl Into<String>,
98 extent: u32,
99 id: StagedId,
100 geometry: GeometryValues,
101 properties: Vec<StagedProperty>,
102 ) -> MltResult<Self> {
103 let (name, extent, _) = validate_staged(name, extent, &id, &geometry, &properties)?;
104 Ok(Self {
105 name,
106 extent,
107 id,
108 geometry,
109 properties,
110 #[cfg(feature = "unstable-v2")]
111 m_values: Vec::new(),
112 #[cfg(feature = "unstable-v2")]
113 nested: Vec::new(),
114 })
115 }
116
117 #[cfg(feature = "unstable-v2")]
119 pub fn with_m_values(
120 name: impl Into<String>,
121 extent: u32,
122 id: StagedId,
123 geometry: GeometryValues,
124 properties: Vec<StagedProperty>,
125 m_values: Vec<StagedMValue>,
126 ) -> MltResult<Self> {
127 let (name, extent, columns) = validate_staged(name, extent, &id, &geometry, &properties)?;
128 validate_m_values(&geometry, &columns, &m_values)?;
129 Ok(Self {
130 name,
131 extent,
132 id,
133 geometry,
134 properties,
135 m_values,
136 nested: Vec::new(),
137 })
138 }
139
140 #[cfg(feature = "unstable-v2")]
142 pub fn with_nested(
143 name: impl Into<String>,
144 extent: u32,
145 id: StagedId,
146 geometry: GeometryValues,
147 properties: Vec<StagedProperty>,
148 m_values: Vec<StagedMValue>,
149 nested: Vec<StagedNested>,
150 ) -> MltResult<Self> {
151 let (name, extent, columns) = validate_staged(name, extent, &id, &geometry, &properties)?;
152 validate_m_values(&geometry, &columns, &m_values)?;
153 validate_nested(&geometry, &columns, &m_values, &nested)?;
154 Ok(Self {
155 name,
156 extent,
157 id,
158 geometry,
159 properties,
160 m_values,
161 nested,
162 })
163 }
164
165 #[must_use]
166 pub fn name(&self) -> &str {
167 &self.name
168 }
169
170 #[must_use]
171 pub fn extent(&self) -> Extent {
172 self.extent
173 }
174
175 #[must_use]
176 pub fn id(&self) -> &StagedId {
177 &self.id
178 }
179
180 #[must_use]
181 pub fn geometry(&self) -> &GeometryValues {
182 &self.geometry
183 }
184
185 #[must_use]
186 pub fn properties(&self) -> &[StagedProperty] {
187 &self.properties
188 }
189
190 #[cfg(feature = "unstable-v2")]
191 #[must_use]
192 pub fn m_values(&self) -> &[StagedMValue] {
193 &self.m_values
194 }
195
196 #[cfg(feature = "unstable-v2")]
197 #[must_use]
198 pub fn nested(&self) -> &[StagedNested] {
199 &self.nested
200 }
201}
202
203fn validate_staged<'p>(
205 name: impl Into<String>,
206 extent: u32,
207 id: &StagedId,
208 geometry: &GeometryValues,
209 properties: &'p [StagedProperty],
210) -> MltResult<(String, Extent, Vec<Cow<'p, str>>)> {
211 let name = name.into();
212 if name.is_empty() {
213 return Err(MltError::MissingLayerName);
214 }
215 let extent = Extent::new(extent)?;
216 let feature_count = geometry.feature_count();
217 if let Some(actual) = id.feature_count()
218 && actual != feature_count
219 {
220 return Err(MltError::StagedFeatureCountMismatch {
221 column: "id".into(),
222 expected: feature_count,
223 actual,
224 });
225 }
226 let mut columns: Vec<Cow<'p, str>> = Vec::with_capacity(properties.len());
229 for property in properties {
230 let actual = property.feature_count();
231 if actual != feature_count {
232 return Err(MltError::StagedFeatureCountMismatch {
233 column: property.name().to_string(),
234 expected: feature_count,
235 actual,
236 });
237 }
238 if let StagedProperty::SharedDict(sd) = property {
239 for item in &sd.items {
240 let name = format!("{}{}", sd.prefix, item.suffix);
241 reject_taken_name(&name, ColumnRole::Property, property_columns(&columns))?;
242 columns.push(Cow::Owned(name));
243 }
244 } else {
245 reject_taken_name(
246 property.name(),
247 ColumnRole::Property,
248 property_columns(&columns),
249 )?;
250 columns.push(Cow::Borrowed(property.name()));
251 }
252 }
253 Ok((name, extent, columns))
254}
255
256fn property_columns<'a>(
258 columns: &'a [Cow<'a, str>],
259) -> impl Iterator<Item = (&'a str, ColumnRole)> + 'a {
260 columns
261 .iter()
262 .map(|name| (name.as_ref(), ColumnRole::Property))
263}
264
265#[cfg(feature = "unstable-v2")]
268fn validate_m_values(
269 geometry: &GeometryValues,
270 columns: &[Cow<'_, str>],
271 m_values: &[StagedMValue],
272) -> MltResult<()> {
273 let feature_count = geometry.feature_count();
274 let mut seen: Vec<&str> = Vec::with_capacity(m_values.len());
275 for column in m_values {
276 reject_taken_name(
277 column.name(),
278 ColumnRole::MValue,
279 property_columns(columns).chain(seen.iter().map(|n| (*n, ColumnRole::MValue))),
280 )?;
281 seen.push(column.name());
282 if let Some(actual) = column.feature_count()
283 && actual != feature_count
284 {
285 return Err(MltError::StagedFeatureCountMismatch {
286 column: column.name().to_string(),
287 expected: feature_count,
288 actual,
289 });
290 }
291 let mut expected = 0;
292 for index in 0..feature_count {
293 let present = column
294 .presence
295 .as_ref()
296 .is_none_or(|mask| mask.get(index).copied().unwrap_or(false));
297 if present {
298 expected += geometry.vertex_count(index)?;
299 }
300 }
301 if expected != column.values().count() {
302 return Err(MltError::MValueColumnLengthMismatch {
303 name: column.name().to_string(),
304 expected,
305 actual: column.values().count(),
306 });
307 }
308 }
309 Ok(())
310}
311
312#[cfg(feature = "unstable-v2")]
315fn validate_nested(
316 geometry: &GeometryValues,
317 columns: &[Cow<'_, str>],
318 m_values: &[StagedMValue],
319 nested: &[StagedNested],
320) -> MltResult<()> {
321 let feature_count = geometry.feature_count();
322 let mut seen: Vec<&str> = Vec::with_capacity(nested.len());
323 for column in nested {
324 reject_taken_name(
325 column.name(),
326 ColumnRole::Nested,
327 property_columns(columns)
328 .chain(m_values.iter().map(|c| (c.name(), ColumnRole::MValue)))
329 .chain(seen.iter().map(|n| (*n, ColumnRole::Nested))),
330 )?;
331 seen.push(column.name());
332 if column.root.parent_count() != feature_count {
333 return Err(MltError::StagedFeatureCountMismatch {
334 column: column.name().to_string(),
335 expected: feature_count,
336 actual: column.root.parent_count(),
337 });
338 }
339 validate_nested_interior(&column.root, 1)?;
340 }
341 Ok(())
342}
343
344#[cfg(feature = "unstable-v2")]
346fn validate_nested_node(node: &StagedNode, depth: usize) -> MltResult<()> {
347 if depth > MAX_NESTED_DEPTH {
348 return Err(MltError::NestedTooDeep(depth));
349 }
350 match node {
351 StagedNode::Leaf(_) => Ok(()),
352 StagedNode::Interior(interior) => validate_nested_interior(interior, depth),
353 }
354}
355
356#[cfg(feature = "unstable-v2")]
358fn validate_nested_interior(interior: &StagedInterior, depth: usize) -> MltResult<()> {
359 match interior {
360 StagedInterior::Struct(node) => {
361 let mut seen: HashSet<&str> = HashSet::with_capacity(node.fields.len());
362 for (name, field) in &node.fields {
363 if !seen.insert(name.as_str()) {
364 return Err(MltError::DuplicateFieldName(name.clone()));
365 }
366 validate_nested_node(field, depth + 1)?;
367 }
368 Ok(())
369 }
370 StagedInterior::List(node) => validate_nested_node(&node.element, depth + 1),
371 StagedInterior::Map(node) => validate_nested_node(&node.value, depth + 1),
372 }
373}
374
375#[cfg(feature = "unstable-v2")]
377#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
378#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
379pub enum WireVersion {
380 #[default]
382 V01,
383 V02,
387}
388
389#[cfg(feature = "unstable-v2")]
390impl WireVersion {
391 #[must_use]
393 pub(crate) fn tag(self) -> u8 {
394 match self {
395 Self::V01 => 1,
396 Self::V02 => 2,
397 }
398 }
399
400 #[must_use]
402 pub(crate) fn fastpfor_kind(self) -> FastPForKind {
403 match self {
404 Self::V01 => FastPForKind::Block256Be,
405 Self::V02 => FastPForKind::Block128Le,
406 }
407 }
408
409 #[must_use]
411 pub(crate) fn rle_layout(self) -> RleLayout {
412 match self {
413 Self::V01 => RleLayout::Split,
414 Self::V02 => RleLayout::Interleaved,
415 }
416 }
417}
418
419#[derive(Debug, Clone, Copy, PartialEq, Hash)]
421#[expect(
422 clippy::struct_excessive_bools,
423 reason = "enums would not model this better, not a state machine"
424)]
425pub struct EncoderConfig {
426 #[cfg(feature = "unstable-v2")]
428 wire_version: WireVersion,
429 tessellate: bool,
431 attempt_spatial_morton_sort: bool,
433 attempt_spatial_hilbert_sort: bool,
435 attempt_id_sort: bool,
437 allow_fsst: bool,
439 allow_fastpfor: bool,
441 allow_shared_dict: bool,
443 #[cfg(feature = "unstable-v2")]
445 allow_float_dict: bool,
446 #[cfg(feature = "unstable-v2")]
448 allow_float_alp: bool,
449 #[cfg(feature = "unstable-v2")]
451 allow_packed_dict_codes: bool,
452 #[cfg(feature = "unstable-v2")]
454 allow_row_shapes: bool,
455}
456impl Default for EncoderConfig {
457 fn default() -> Self {
458 Self {
459 #[cfg(feature = "unstable-v2")]
460 wire_version: WireVersion::V01,
461 tessellate: false,
462 attempt_spatial_morton_sort: true,
463 attempt_spatial_hilbert_sort: true,
464 attempt_id_sort: true,
465 allow_fsst: true,
466 allow_fastpfor: true,
467 allow_shared_dict: true,
468 #[cfg(feature = "unstable-v2")]
470 allow_float_dict: false,
471 #[cfg(feature = "unstable-v2")]
472 allow_float_alp: false,
473 #[cfg(feature = "unstable-v2")]
474 allow_row_shapes: false,
475 #[cfg(feature = "unstable-v2")]
476 allow_packed_dict_codes: false,
477 }
478 }
479}
480
481impl EncoderConfig {
482 #[cfg(feature = "unstable-v2")]
483 #[must_use]
484 pub fn wire_version(self) -> WireVersion {
485 self.wire_version
486 }
487
488 #[must_use]
489 pub fn tessellate(self) -> bool {
490 self.tessellate
491 }
492
493 #[must_use]
494 pub fn attempt_spatial_morton_sort(self) -> bool {
495 self.attempt_spatial_morton_sort
496 }
497
498 #[must_use]
499 pub fn attempt_spatial_hilbert_sort(self) -> bool {
500 self.attempt_spatial_hilbert_sort
501 }
502
503 #[must_use]
504 pub fn attempt_id_sort(self) -> bool {
505 self.attempt_id_sort
506 }
507
508 #[must_use]
509 pub fn allow_fsst(self) -> bool {
510 self.allow_fsst
511 }
512
513 #[must_use]
514 pub fn allow_fastpfor(self) -> bool {
515 self.allow_fastpfor
516 }
517
518 #[must_use]
520 pub(crate) fn fastpfor(self) -> Option<PhysicalEncoding> {
521 #[cfg(feature = "unstable-v2")]
522 let kind = self.wire_version.fastpfor_kind();
523 #[cfg(not(feature = "unstable-v2"))]
524 let kind = FastPForKind::Block256Be;
525 self.allow_fastpfor
526 .then_some(PhysicalEncoding::FastPFor(kind))
527 }
528
529 #[must_use]
530 pub fn allow_shared_dict(self) -> bool {
531 self.allow_shared_dict
532 }
533
534 #[cfg(feature = "unstable-v2")]
536 #[must_use]
537 pub fn allow_row_shapes(self) -> bool {
538 self.allow_row_shapes
539 }
540
541 #[cfg(feature = "unstable-v2")]
543 #[must_use]
544 pub fn with_row_shapes(mut self, enabled: bool) -> Self {
545 self.allow_row_shapes = enabled;
546 self
547 }
548
549 #[cfg(feature = "unstable-v2")]
551 #[must_use]
552 pub fn allow_float_dict(self) -> bool {
553 self.allow_float_dict && self.wire_version != WireVersion::V01
554 }
555
556 #[cfg(feature = "unstable-v2")]
558 #[must_use]
559 pub fn allow_float_alp(self) -> bool {
560 self.allow_float_alp && self.wire_version != WireVersion::V01
561 }
562
563 #[cfg(feature = "unstable-v2")]
564 #[must_use]
565 pub fn with_wire_version(mut self, version: WireVersion) -> Self {
566 self.wire_version = version;
567 self
568 }
569
570 #[must_use]
571 pub fn with_tessellation(mut self, enabled: bool) -> Self {
572 self.tessellate = enabled;
573 self
574 }
575
576 #[must_use]
577 pub fn with_spatial_morton_sort(mut self, enabled: bool) -> Self {
578 self.attempt_spatial_morton_sort = enabled;
579 self
580 }
581
582 #[must_use]
583 pub fn with_spatial_hilbert_sort(mut self, enabled: bool) -> Self {
584 self.attempt_spatial_hilbert_sort = enabled;
585 self
586 }
587
588 #[must_use]
589 pub fn with_id_sort(mut self, enabled: bool) -> Self {
590 self.attempt_id_sort = enabled;
591 self
592 }
593
594 #[must_use]
595 pub fn with_fsst(mut self, enabled: bool) -> Self {
596 self.allow_fsst = enabled;
597 self
598 }
599
600 #[must_use]
601 pub fn with_fastpfor(mut self, enabled: bool) -> Self {
602 self.allow_fastpfor = enabled;
603 self
604 }
605
606 #[must_use]
607 pub fn with_shared_dict(mut self, enabled: bool) -> Self {
608 self.allow_shared_dict = enabled;
609 self
610 }
611
612 #[cfg(feature = "unstable-v2")]
616 #[must_use]
617 pub fn with_float_dict(mut self, enabled: bool) -> Self {
618 self.allow_float_dict = enabled;
619 self
620 }
621
622 #[cfg(feature = "unstable-v2")]
624 #[must_use]
625 pub fn with_float_alp(mut self, enabled: bool) -> Self {
626 self.allow_float_alp = enabled;
627 self
628 }
629
630 #[cfg(feature = "unstable-v2")]
632 #[must_use]
633 pub fn allow_packed_dict_codes(self) -> bool {
634 self.allow_packed_dict_codes && self.wire_version != WireVersion::V01
635 }
636
637 #[cfg(feature = "unstable-v2")]
640 #[must_use]
641 pub fn with_packed_dict_codes(mut self, enabled: bool) -> Self {
642 self.allow_packed_dict_codes = enabled;
643 self
644 }
645}
646
647#[derive(Debug, Clone, Copy, PartialEq, Eq)]
649pub enum StrEncoding {
650 Plain,
651 Dict,
652 Fsst,
653 FsstDict,
654 FrontDict,
655 FsstFrontDict,
656}
657
658#[derive(Debug, Clone, Copy, PartialEq, Eq)]
660pub enum FloatEncoding {
661 None,
662 #[cfg(feature = "unstable-v2")]
663 Dict,
664 #[cfg(feature = "unstable-v2")]
665 Alp,
666}
667
668#[derive(Debug, Clone, Copy, PartialEq)]
669pub enum ColumnKind {
670 Id,
671 Geometry,
672 Property,
673}
674
675#[cfg(feature = "unstable-v2")]
680#[derive(Clone, Copy, Debug)]
681pub struct StrAt<'a> {
682 pub name: &'a str,
683 pub subname: &'a str,
684}
685
686#[cfg(feature = "unstable-v2")]
687impl<'a> StrAt<'a> {
688 #[must_use]
689 pub const fn flat(name: &'a str) -> Self {
690 Self { name, subname: "" }
691 }
692
693 #[must_use]
694 pub const fn nested(name: &'a str, subname: &'a str) -> Self {
695 Self { name, subname }
696 }
697
698 pub(crate) fn ctx(self, stream_type: StreamType) -> StreamCtx<'a> {
699 StreamCtx::prop2(stream_type, self.name, self.subname)
700 }
701
702 pub(crate) fn qualified(self) -> Cow<'a, str> {
704 StreamCtx::prop2(StreamType::Present, self.name, self.subname).qualified()
705 }
706}
707
708#[derive(Clone, Copy, Debug, PartialEq)]
710pub struct StreamCtx<'a> {
711 pub kind: ColumnKind,
712 pub stream_type: StreamType,
713 pub name: &'a str,
714 pub subname: &'a str,
715}
716impl<'a> StreamCtx<'a> {
717 #[inline]
719 #[must_use]
720 pub const fn new(
721 kind: ColumnKind,
722 stream_type: StreamType,
723 name: &'a str,
724 subname: &'a str,
725 ) -> Self {
726 Self {
727 kind,
728 stream_type,
729 name,
730 subname,
731 }
732 }
733
734 #[inline]
735 #[must_use]
736 pub const fn id(stream_type: StreamType) -> Self {
737 Self::new(ColumnKind::Id, stream_type, "", "")
738 }
739
740 #[inline]
741 #[must_use]
742 pub const fn geom(stream_type: StreamType, name: &'a str) -> Self {
743 Self::new(ColumnKind::Geometry, stream_type, name, "")
744 }
745
746 #[inline]
747 #[must_use]
748 pub const fn prop(stream_type: StreamType, name: &'a str) -> Self {
749 Self::new(ColumnKind::Property, stream_type, name, "")
750 }
751
752 #[inline]
753 #[must_use]
754 pub const fn prop_data(name: &'a str) -> Self {
755 let stream_type = StreamType::Data(DictionaryType::None);
756 Self::new(ColumnKind::Property, stream_type, name, "")
757 }
758
759 #[inline]
760 #[must_use]
761 pub const fn prop2(stream_type: StreamType, prefix: &'a str, suffix: &'a str) -> Self {
762 Self::new(ColumnKind::Property, stream_type, prefix, suffix)
763 }
764
765 #[must_use]
767 pub fn qualified(&self) -> Cow<'a, str> {
768 if self.subname.is_empty() {
769 Cow::Borrowed(self.name)
770 } else {
771 Cow::Owned(format!("{}{}", self.name, self.subname))
772 }
773 }
774}
775
776#[derive(Dbg)]
780pub struct ExplicitEncoder {
781 pub vertex_buffer_type: VertexBufferType,
783 #[dbg(skip)]
785 pub force_stream: Box<dyn for<'a> Fn(&'a StreamCtx<'a>) -> bool>,
786 #[dbg(skip)]
788 pub get_int_encoder: Box<dyn for<'a> Fn(&'a StreamCtx<'a>) -> IntEncoder>,
789 #[dbg(skip)]
791 pub get_str_encoding: Box<dyn Fn(&str) -> StrEncoding>,
792 #[dbg(skip)]
794 pub get_float_encoding: Box<dyn Fn(&str) -> FloatEncoding>,
795}
796
797#[cfg(all(test, feature = "unstable-v2"))]
798mod tests {
799 use insta::assert_snapshot;
800
801 use super::*;
802 use crate::encoder::{StagedLeaf, StagedList, StagedStruct, StagedValues};
803
804 fn leaf() -> StagedNode {
805 StagedNode::Leaf(StagedLeaf::new(None, StagedValues::I32(vec![1])))
806 }
807
808 fn lists(depth: usize) -> StagedInterior {
810 let mut node = leaf();
811 for _ in 2..depth {
812 node = StagedNode::Interior(StagedInterior::List(StagedList::new(None, vec![1], node)));
813 }
814 StagedInterior::List(StagedList::new(None, vec![1], node))
815 }
816
817 #[test]
818 fn a_struct_repeating_a_field_name() {
819 let root =
820 StagedInterior::Struct(StagedStruct::new(None, vec![("a", leaf()), ("a", leaf())]));
821 assert_snapshot!(
822 validate_nested_interior(&root, 1).unwrap_err(),
823 @"duplicate field name in a struct node: a"
824 );
825 }
826
827 #[test]
828 fn a_tree_one_level_past_the_limit() {
829 assert_snapshot!(
830 validate_nested_interior(&lists(MAX_NESTED_DEPTH + 1), 1).unwrap_err(),
831 @"a nested column is 9 levels deep, more than the 8 the format allows"
832 );
833 }
834
835 #[test]
836 fn a_tree_at_the_limit() {
837 validate_nested_interior(&lists(MAX_NESTED_DEPTH), 1).expect("a tree at the limit");
838 }
839}