miniconf 0.21.0

Serialize/deserialize/access reflection for trees
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
use core::{convert::Infallible, num::NonZero};
use serde::{Serialize, Serializer, ser::SerializeMap as _};

use crate::{DescendError, ExactSize, IntoKeys, KeyError, Keys, NodeIter, Shape, Transcode};

#[cfg(feature = "sem")]
type StoredSem = Sem;
#[cfg(not(feature = "sem"))]
type StoredSem = ();

#[cfg(feature = "meta-node")]
type StoredNodeMeta = Meta;
#[cfg(not(feature = "meta-node"))]
type StoredNodeMeta = ();

#[cfg(feature = "meta-edge")]
type StoredEdgeMeta = Meta;
#[cfg(not(feature = "meta-edge"))]
type StoredEdgeMeta = ();

/// Structured semantics for a mutually exclusive named node.
pub const ONEOF_SEM: Sem = Sem::new(None, true, false);
/// Structured semantics for a node that may be absent at runtime.
pub const MAYBE_ABSENT_SEM: Sem = Sem::new(None, false, true);
/// Result of an exact key lookup.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Lookup {
    /// The number of keys consumed.
    pub depth: usize,
    /// The schema reached by the traversal.
    pub schema: &'static Schema,
}

#[cfg(feature = "defmt")]
impl defmt::Format for Lookup {
    fn format(&self, fmt: defmt::Formatter<'_>) {
        defmt::write!(
            fmt,
            "Lookup {{ depth: {=usize}, leaf: {=bool} }}",
            self.depth,
            self.schema.is_leaf()
        )
    }
}

/// Error returned by [`Schema::resolve_into()`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ResolveError {
    /// The traversal error.
    pub error: DescendError<()>,
    /// The longest valid consumed prefix.
    pub lookup: Lookup,
}

/// Structured machine-readable schema semantics.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub struct Sem {
    /// Semantic leaf type when known.
    #[serde(skip_serializing_if = "Option::is_none")]
    ty: Option<Ty>,
    /// This named internal node has mutually exclusive children.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    oneof: bool,
    /// This node may be absent at runtime.
    #[serde(skip_serializing_if = "core::ops::Not::not")]
    maybe_absent: bool,
}

impl Sem {
    /// Empty structured semantics.
    pub const EMPTY: Self = Self::new(None, false, false);

    /// Construct structured schema semantics.
    pub const fn new(ty: Option<Ty>, oneof: bool, maybe_absent: bool) -> Self {
        Self {
            ty,
            oneof,
            maybe_absent,
        }
    }

    /// Semantic leaf type when known.
    pub const fn ty(&self) -> Option<Ty> {
        self.ty
    }

    /// Whether the node has mutually exclusive children.
    pub const fn oneof(&self) -> bool {
        self.oneof
    }

    /// Whether the node may be absent at runtime.
    pub const fn maybe_absent(&self) -> bool {
        self.maybe_absent
    }

    /// Whether there is no semantic payload.
    pub const fn is_empty(&self) -> bool {
        self.ty.is_none() && !self.oneof && !self.maybe_absent
    }
}

#[cfg(feature = "sem")]
const fn store_sem(sem: Sem) -> StoredSem {
    sem
}

#[cfg(not(feature = "sem"))]
const fn store_sem(_sem: Sem) -> StoredSem {}

#[cfg(feature = "sem")]
const fn sem_ref(sem: &StoredSem) -> Option<&Sem> {
    Some(sem)
}

#[cfg(not(feature = "sem"))]
const fn sem_ref(_sem: &StoredSem) -> Option<&Sem> {
    None
}

#[cfg(feature = "meta-node")]
const fn store_node_meta(meta: Meta) -> StoredNodeMeta {
    meta
}

#[cfg(not(feature = "meta-node"))]
const fn store_node_meta(_meta: Meta) -> StoredNodeMeta {}

#[cfg(feature = "meta-node")]
const fn node_meta_ref(meta: &StoredNodeMeta) -> &Meta {
    meta
}

#[cfg(not(feature = "meta-node"))]
const fn node_meta_ref(_meta: &StoredNodeMeta) -> &Meta {
    &Meta::EMPTY
}

#[cfg(feature = "meta-edge")]
const fn store_edge_meta(meta: Meta) -> StoredEdgeMeta {
    meta
}

#[cfg(not(feature = "meta-edge"))]
const fn store_edge_meta(_meta: Meta) -> StoredEdgeMeta {}

#[cfg(feature = "meta-edge")]
const fn edge_meta_ref(meta: &StoredEdgeMeta) -> &Meta {
    meta
}

#[cfg(not(feature = "meta-edge"))]
const fn edge_meta_ref(_meta: &StoredEdgeMeta) -> &Meta {
    &Meta::EMPTY
}

/// Compact semantic leaf type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum Ty {
    /// Boolean.
    #[serde(rename = "bool")]
    Bool,
    /// 8-bit signed integer.
    #[serde(rename = "i8")]
    I8,
    /// 16-bit signed integer.
    #[serde(rename = "i16")]
    I16,
    /// 32-bit signed integer.
    #[serde(rename = "i32")]
    I32,
    /// 64-bit signed integer.
    #[serde(rename = "i64")]
    I64,
    /// 128-bit signed integer.
    #[serde(rename = "i128")]
    I128,
    /// Pointer-sized signed integer.
    #[serde(rename = "isize")]
    Isize,
    /// 8-bit unsigned integer.
    #[serde(rename = "u8")]
    U8,
    /// 16-bit unsigned integer.
    #[serde(rename = "u16")]
    U16,
    /// 32-bit unsigned integer.
    #[serde(rename = "u32")]
    U32,
    /// 64-bit unsigned integer.
    #[serde(rename = "u64")]
    U64,
    /// 128-bit unsigned integer.
    #[serde(rename = "u128")]
    U128,
    /// Pointer-sized unsigned integer.
    #[serde(rename = "usize")]
    Usize,
    /// 32-bit floating point number.
    #[serde(rename = "f32")]
    F32,
    /// 64-bit floating point number.
    #[serde(rename = "f64")]
    F64,
    /// String-like leaf.
    #[serde(rename = "str")]
    Str,
}

/// A numbered schema item
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize)]
pub struct Numbered {
    /// The child schema
    pub(crate) schema: &'static Schema,
    /// The edge metadata
    pub(crate) meta: StoredEdgeMeta,
}

impl Numbered {
    /// Create a new Numbered schema item with no edge metadata.
    pub const fn new(schema: &'static Schema, meta: Meta) -> Self {
        Self {
            schema,
            meta: store_edge_meta(meta),
        }
    }

    /// The child schema.
    pub const fn schema(&self) -> &'static Schema {
        self.schema
    }

    /// Edge metadata when present.
    pub const fn edge_meta(&self) -> &Meta {
        edge_meta_ref(&self.meta)
    }
}

/// A named schema item
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize)]
pub struct Named {
    /// The name of the item
    pub(crate) name: &'static str,
    /// The child schema
    pub(crate) schema: &'static Schema,
    /// The edge metadata
    pub(crate) meta: StoredEdgeMeta,
}

impl Named {
    /// Create a new Named schema item with no edge metadata.
    pub const fn new(name: &'static str, schema: &'static Schema, meta: Meta) -> Self {
        Self {
            name,
            schema,
            meta: store_edge_meta(meta),
        }
    }

    /// The child name.
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// The child schema.
    pub const fn schema(&self) -> &'static Schema {
        self.schema
    }

    /// Edge metadata when present.
    pub const fn edge_meta(&self) -> &Meta {
        edge_meta_ref(&self.meta)
    }
}

/// A representative schema item for a homogeneous array
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize)]
pub struct Homogeneous {
    /// The number of items
    pub(crate) len: NonZero<usize>,
    /// The schema of the child nodes
    pub(crate) schema: &'static Schema,
    /// The edge metadata
    pub(crate) meta: StoredEdgeMeta,
}

impl Homogeneous {
    /// Create a new Homogeneous schema item with no edge metadata.
    pub const fn new(len: usize, schema: &'static Schema, meta: Meta) -> Self {
        Self {
            len: NonZero::new(len).expect("Must have at least one child"),
            schema,
            meta: store_edge_meta(meta),
        }
    }

    /// The number of items.
    pub const fn len(&self) -> NonZero<usize> {
        self.len
    }

    /// The child schema.
    pub const fn schema(&self) -> &'static Schema {
        self.schema
    }

    /// Edge metadata when present.
    pub const fn edge_meta(&self) -> &Meta {
        edge_meta_ref(&self.meta)
    }
}

/// An internal node with children
///
/// Always non-empty
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize)]
pub enum Internal {
    /// Named children
    Named(&'static [Named]),
    /// Numbered heterogeneous children
    Numbered(&'static [Numbered]),
    /// Homogeneous numbered children
    Homogeneous(Homogeneous),
}

impl Internal {
    /// Return the number of direct child nodes
    pub const fn len(&self) -> NonZero<usize> {
        match self {
            Self::Named(n) => NonZero::new(n.len()).expect("Must have at least one child"),
            Self::Numbered(n) => NonZero::new(n.len()).expect("Must have at least one child"),
            Self::Homogeneous(h) => h.len,
        }
    }

    /// Return the child schema at the given index
    ///
    /// # Panics
    /// If the index is out of bounds
    pub const fn get_schema(&self, idx: usize) -> &Schema {
        match self {
            Self::Named(nameds) => nameds[idx].schema,
            Self::Numbered(numbereds) => numbereds[idx].schema,
            Self::Homogeneous(homogeneous) => homogeneous.schema,
        }
    }

    /// Return the edge metadata for the given child
    ///
    /// # Panics
    /// If the index is out of bounds
    pub const fn get_edge_meta(&self, idx: usize) -> &Meta {
        match self {
            Internal::Named(nameds) => nameds[idx].edge_meta(),
            Internal::Numbered(numbereds) => numbereds[idx].edge_meta(),
            Internal::Homogeneous(homogeneous) => homogeneous.edge_meta(),
        }
    }

    /// Perform a index-to-name lookup
    ///
    /// If this succeeds with None, it's a numbered or homogeneous internal node and the
    /// name is the formatted index.
    ///
    /// # Panics
    /// If the index is out of bounds
    pub const fn get_name(&self, idx: usize) -> Option<&str> {
        if let Self::Named(n) = self {
            Some(n[idx].name)
        } else {
            None
        }
    }

    /// Perform a name-to-index lookup
    pub fn get_index(&self, name: &str) -> Option<usize> {
        match self {
            Internal::Named(n) => n.iter().position(|n| n.name == name),
            Internal::Numbered(n) => name.parse().ok().filter(|i| *i < n.len()),
            Internal::Homogeneous(h, ..) => name.parse().ok().filter(|i| *i < h.len.get()),
        }
    }
}

/// Immutable schema metadata.
#[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Ord, Eq, Hash)]
pub struct Meta {
    items: &'static [(&'static str, &'static str)],
}

impl Meta {
    /// Empty metadata.
    pub const EMPTY: Self = Self { items: &[] };

    /// Construct metadata from a static list of key/value pairs.
    pub const fn new(items: &'static [(&'static str, &'static str)]) -> Self {
        Self { items }
    }

    /// Whether the metadata bag is empty.
    pub const fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Number of metadata entries.
    pub const fn len(&self) -> usize {
        self.items.len()
    }

    /// Metadata entries in declaration order.
    pub const fn as_slice(&self) -> &'static [(&'static str, &'static str)] {
        self.items
    }

    /// Iterate over metadata entries in declaration order.
    pub fn iter(&self) -> core::slice::Iter<'static, (&'static str, &'static str)> {
        self.items.iter()
    }

    /// Return the first metadata value for `key`.
    pub fn get(&self, key: &str) -> Option<&'static str> {
        self.items
            .iter()
            .find_map(|(have_key, have_value)| (*have_key == key).then_some(*have_value))
    }
}

impl Serialize for Meta {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(self.items.len()))?;
        for (key, value) in self.items {
            map.serialize_entry(key, value)?;
        }
        map.end()
    }
}

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

    const META: Meta = Meta::new(&[("doc", "node"), ("doc", "second")]);
    const EDGE_META: Meta = Meta::new(&[("unit", "V")]);
    const CHILD: Schema = Schema::leaf(META, Sem::new(Some(Ty::U16), false, false));
    const ROOT: Schema = Schema::Internal(InternalSchema::new(
        NodeSchema::new(META, ONEOF_SEM),
        Internal::Named(&[Named::new("value", &CHILD, EDGE_META)]),
    ));

    #[test]
    fn meta_iter_preserves_declaration_order_and_duplicates() {
        assert_eq!(META.len(), 2);
        assert_eq!(META.get("doc"), Some("node"));
        assert_eq!(
            META.iter().copied().collect::<std::vec::Vec<_>>(),
            [("doc", "node"), ("doc", "second")]
        );
    }

    #[test]
    fn feature_retention_contract_is_explicit() {
        #[cfg(feature = "sem")]
        {
            assert_eq!(ROOT.sem(), Some(&ONEOF_SEM));
            assert_eq!(CHILD.sem(), Some(&Sem::new(Some(Ty::U16), false, false)));
        }
        #[cfg(not(feature = "sem"))]
        {
            assert_eq!(ROOT.sem(), None);
            assert_eq!(CHILD.sem(), None);
        }

        #[cfg(feature = "meta-node")]
        assert_eq!(ROOT.node_meta().get("doc"), Some("node"));
        #[cfg(not(feature = "meta-node"))]
        assert!(ROOT.node_meta().is_empty());

        let internal = ROOT.internal().unwrap();
        #[cfg(feature = "meta-edge")]
        assert_eq!(internal.get_edge_meta(0).get("unit"), Some("V"));
        #[cfg(not(feature = "meta-edge"))]
        assert!(internal.get_edge_meta(0).is_empty());
    }
}

/// Shared static schema payload for one tree node.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize)]
pub struct NodeSchema {
    meta: StoredNodeMeta,
    sem: StoredSem,
}

impl NodeSchema {
    /// Empty node metadata and semantics.
    pub const EMPTY: Self = Self {
        meta: store_node_meta(Meta::EMPTY),
        sem: store_sem(Sem::EMPTY),
    };

    /// Construct a node schema from node metadata and semantics.
    pub const fn new(meta: Meta, sem: Sem) -> Self {
        Self {
            meta: store_node_meta(meta),
            sem: store_sem(sem),
        }
    }

    const fn sem(&self) -> Option<&Sem> {
        sem_ref(&self.sem)
    }

    const fn node_meta(&self) -> &Meta {
        node_meta_ref(&self.meta)
    }
}

/// Static schema payload for an internal node.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize)]
pub struct InternalSchema {
    node: NodeSchema,
    internal: Internal,
}

impl InternalSchema {
    /// Construct an internal schema from node payload and child layout.
    pub const fn new(node: NodeSchema, internal: Internal) -> Self {
        Self { node, internal }
    }

    const fn sem(&self) -> Option<&Sem> {
        self.node.sem()
    }

    const fn node_meta(&self) -> &Meta {
        self.node.node_meta()
    }

    /// Child layout strategy.
    pub const fn internal(&self) -> &Internal {
        &self.internal
    }
}

/// Static schema for one tree node.
///
/// `Schema` exposes the in-crate structural schema model. Its `Serialize`
/// implementation follows this Rust data model and is useful for inspection and
/// tests, but transport clients should prefer explicit projections such as
/// [`crate::compact_schema`] or [`crate::json_schema`] when they need a stable
/// schema payload contract.
///
/// Metadata and structured semantics are retained only when the corresponding
/// Cargo features are enabled:
///
/// - `sem` retains [`Sem`] payloads returned by [`Self::sem()`].
/// - `meta-node` retains metadata returned by [`Self::node_meta()`].
/// - `meta-edge` retains metadata returned by child edge accessors such as
///   [`Named::edge_meta()`], [`Numbered::edge_meta()`], and
///   [`Homogeneous::edge_meta()`].
///
/// Constructors and derive output accept metadata and semantics in all builds;
/// disabled retention features intentionally discard them and accessors return
/// `None` or [`Meta::EMPTY`].
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash, Serialize)]
pub enum Schema {
    /// Leaf node without children.
    Leaf(NodeSchema),
    /// Internal node with one child layout strategy.
    Internal(InternalSchema),
}

impl Default for Schema {
    fn default() -> Self {
        Self::LEAF
    }
}

impl Schema {
    /// A leaf without metadata or sem.
    pub const LEAF: Self = Self::Leaf(NodeSchema::EMPTY);

    /// Construct a leaf schema from node metadata and semantics.
    pub const fn leaf(meta: Meta, sem: Sem) -> Self {
        Self::Leaf(NodeSchema::new(meta, sem))
    }

    /// Construct a schema with the same shape and new node metadata and semantics.
    pub const fn rebuild(&self, meta: Meta, sem: Sem) -> Self {
        let node = NodeSchema::new(meta, sem);
        match self {
            Self::Leaf(_) => Self::Leaf(node),
            Self::Internal(schema) => Self::Internal(InternalSchema::new(node, schema.internal)),
        }
    }

    /// A leaf with a known semantic type.
    pub(crate) const fn leaf_ty(ty: Ty) -> Self {
        Self::leaf(Meta::EMPTY, Sem::new(Some(ty), false, false))
    }

    /// Create a new internal node schema with numbered children and without node metadata
    pub const fn numbered(numbered: &'static [Numbered]) -> Self {
        Self::Internal(InternalSchema::new(
            NodeSchema::EMPTY,
            Internal::Numbered(numbered),
        ))
    }

    /// Create a new internal node schema with named children and without node metadata
    pub const fn named(named: &'static [Named]) -> Self {
        Self::Internal(InternalSchema::new(
            NodeSchema::EMPTY,
            Internal::Named(named),
        ))
    }

    /// Create a new internal node schema with homogenous children and without node metadata
    pub const fn homogeneous(homogeneous: Homogeneous) -> Self {
        Self::Internal(InternalSchema::new(
            NodeSchema::EMPTY,
            Internal::Homogeneous(homogeneous),
        ))
    }

    /// Whether this node is a leaf
    pub const fn is_leaf(&self) -> bool {
        matches!(self, Self::Leaf(_))
    }

    /// Number of child nodes
    #[allow(clippy::len_without_is_empty)]
    pub const fn len(&self) -> usize {
        match self {
            Self::Leaf(_) => 0,
            Self::Internal(schema) => schema.internal().len().get(),
        }
    }

    /// Structured semantics when present.
    pub const fn sem(&self) -> Option<&Sem> {
        match self {
            Self::Leaf(schema) => schema.sem(),
            Self::Internal(schema) => schema.sem(),
        }
    }

    /// Node metadata.
    pub const fn node_meta(&self) -> &Meta {
        match self {
            Self::Leaf(node) => node.node_meta(),
            Self::Internal(schema) => schema.node_meta(),
        }
    }

    /// Internal schema when present.
    pub const fn internal(&self) -> Option<&Internal> {
        match self {
            Self::Leaf(_) => None,
            Self::Internal(schema) => Some(schema.internal()),
        }
    }

    /// Resolve the next selector segment from a normalized key cursor.
    pub fn next(&self, mut keys: impl Keys) -> Result<usize, KeyError> {
        keys.next(self.internal().ok_or(KeyError::TooLong)?)
    }

    /// Traverse from the root to a leaf using a normalized key cursor.
    ///
    /// If a leaf is found early (`keys` being longer than required)
    /// `Err(KeyError::TooLong)` is returned.
    /// If `keys` is exhausted before reaching a leaf node,
    /// `Err(KeyError::TooShort)` is returned.
    ///
    /// ```
    /// # #[cfg(feature = "derive")] {
    /// # use core::convert::Infallible;
    /// use miniconf::{IntoKeys, TreeSchema};
    /// #[derive(TreeSchema)]
    /// struct S {
    ///     foo: u32,
    ///     bar: [u16; 2],
    /// };
    /// let mut ret = [
    ///     (S::SCHEMA, Some(1usize)),
    ///     (<[u16; 2]>::SCHEMA, Some(0)),
    ///     (u16::SCHEMA, None),
    /// ].into_iter();
    /// let func = |schema, idx_internal: Option<_>| {
    ///     assert_eq!(ret.next().unwrap(), (schema, idx_internal.map(|(idx, _)| idx)));
    ///     Ok::<_, Infallible>(())
    /// };
    /// assert_eq!(S::SCHEMA.descend(["bar", "0"].into_keys(), func), Ok(()));
    /// # }
    /// ```
    ///
    /// # Args
    /// * `keys`: A normalized [`Keys`] cursor identifying the node.
    /// * `func`: A `FnMut` to be called for each (internal and leaf) node on the path.
    ///   Its arguments are the current node schema and optionally the traversed edge index and
    ///   internal schema.
    ///   Returning `Err(E)` aborts the traversal.
    ///   Returning `Ok(T)` continues the downward traversal.
    ///
    /// # Returns
    /// The leaf `func` call return value.
    pub fn descend<'a, T, E>(
        &'a self,
        mut keys: impl Keys,
        mut func: impl FnMut(&'a Self, Option<(usize, &'a Internal)>) -> Result<T, E>,
    ) -> Result<T, DescendError<E>> {
        let mut schema = self;
        while let Some(internal) = schema.internal() {
            let idx = keys.next(internal)?;
            func(schema, Some((idx, internal))).map_err(DescendError::Inner)?;
            schema = internal.get_schema(idx);
        }
        keys.finalize()?;
        func(schema, None).map_err(DescendError::Inner)
    }

    /// Look up edge and node metadata given a boundary key input.
    pub fn get_meta(&self, keys: impl IntoKeys) -> Result<(Option<&Meta>, &Meta), KeyError> {
        let mut edge = None;
        let mut node = self.node_meta();
        self.descend(keys.into_keys(), |schema, idx_internal| {
            if let Some((idx, internal)) = idx_internal {
                edge = Some(internal.get_edge_meta(idx));
            }
            node = schema.node_meta();
            Ok::<_, Infallible>(())
        })
        .map_err(|e| e.try_into().unwrap())?;
        Ok((edge, node))
    }

    fn walk(
        &'static self,
        mut keys: impl Keys,
        mut on_index: impl FnMut(usize, usize) -> bool,
    ) -> Result<Lookup, ResolveError> {
        let mut schema = self;
        let mut depth = 0;

        while let Some(internal) = schema.internal() {
            let idx = match keys.next(internal) {
                Ok(idx) => idx,
                Err(KeyError::TooShort) => {
                    debug_assert!(!schema.is_leaf());
                    return Ok(Lookup { depth, schema });
                }
                Err(err) => {
                    return Err(ResolveError {
                        error: err.into(),
                        lookup: Lookup { depth, schema },
                    });
                }
            };
            if !on_index(depth, idx) {
                return Err(ResolveError {
                    error: DescendError::Inner(()),
                    lookup: Lookup { depth, schema },
                });
            }
            depth += 1;
            schema = internal.get_schema(idx);
        }

        match keys.finalize() {
            Ok(()) => Ok(Lookup { depth, schema }),
            Err(KeyError::TooLong) => Err(ResolveError {
                error: KeyError::TooLong.into(),
                lookup: Lookup { depth, schema },
            }),
            Err(err) => unreachable!("unexpected finalize error: {err:?}"),
        }
    }

    /// Resolve a boundary key input while recording the consumed index prefix into `state`.
    ///
    /// On both success and failure, `state[..depth]` contains the longest valid consumed prefix.
    pub fn resolve_into(
        &'static self,
        keys: impl IntoKeys,
        state: &mut [usize],
    ) -> Result<Lookup, ResolveError> {
        self.walk(keys.into_keys(), |depth, idx| {
            let Some(slot) = state.get_mut(depth) else {
                return false;
            };
            *slot = idx;
            true
        })
    }

    /// Get the schema node identified exactly by a boundary key input.
    pub fn get(&'static self, keys: impl IntoKeys) -> Result<Lookup, KeyError> {
        self.walk(keys.into_keys(), |_, _| true)
            .map_err(|err| match err.error {
                DescendError::Key(err) => err,
                DescendError::Inner(()) => unreachable!("infallible exact lookup"),
            })
    }

    /// Transcode a boundary key input to a new key representation using its default configuration.
    ///
    /// This default-constructs the output and then calls [`Transcode::transcode_from()`].
    ///
    /// ```
    /// # #[cfg(feature = "derive")] {
    /// use miniconf::{ConstPath, Indices, JsonPath, JsonPathIter, Lookup, Packed, Path, TreeSchema};
    /// #[derive(TreeSchema)]
    /// struct S {
    ///     foo: u32,
    ///     bar: [u16; 5],
    /// };
    ///
    /// let idx = [1, 1];
    /// let sch = S::SCHEMA;
    ///
    /// let path = sch.transcode::<Path<String>>(idx).unwrap();
    /// assert_eq!(path.path.as_str(), "/bar/1");
    /// let path = sch.transcode::<ConstPath<String, ':'>>(idx).unwrap();
    /// assert_eq!(path.0.as_str(), ":bar:1");
    /// let path = sch.transcode::<JsonPath<String>>(idx).unwrap();
    /// assert_eq!(path.0.as_str(), ".bar[1]");
    /// let indices = sch
    ///     .transcode::<Indices<[usize; 2]>>(JsonPathIter::new(path.0.as_str()))
    ///     .unwrap();
    /// assert_eq!(indices.as_ref(), idx);
    /// let indices = sch.transcode::<Indices<[usize; 2]>>(["bar", "1"]).unwrap();
    /// assert_eq!(indices.as_ref(), [1, 1]);
    /// let packed = sch.transcode::<Packed>(["bar", "4"]).unwrap();
    /// assert_eq!(packed.into_lsb().get(), 0b1_1_100);
    /// let path = sch.transcode::<Path<String>>(packed).unwrap();
    /// assert_eq!(path.path.as_str(), "/bar/4");
    /// let lookup = sch.get(path.as_ref()).unwrap();
    /// assert_eq!((lookup.depth, lookup.schema.is_leaf()), (2, true));
    /// # }
    /// ```
    ///
    /// # Args
    /// * `keys`: A boundary [`IntoKeys`] input identifying the node.
    ///
    /// # Returns
    /// The transcoded target on success.
    pub fn transcode<N: Transcode + Default>(
        &self,
        keys: impl IntoKeys,
    ) -> Result<N, DescendError<N::Error>> {
        N::transcode(self, keys)
    }

    /// Summary bounds and counts for this schema.
    pub const fn shape(&self) -> Shape {
        Shape::new(self)
    }

    /// The maximum key depth.
    pub const fn max_depth(&self) -> usize {
        self.shape().max_depth
    }

    /// The maximum path length in bytes including `separator`.
    pub const fn max_length(&self, separator: &str) -> usize {
        self.shape().max_length(separator)
    }

    /// Return an iterator over nodes of a given type
    ///
    /// This is a walk of all leaf nodes.
    /// The iterator will walk all paths, including those that may be absent at
    /// runtime (see [the `Option` section on `TreeSchema`](crate::TreeSchema#option)).
    /// The iterator has an exact and trusted `size_hint()`.
    /// The `D` const generic of [`NodeIter`] is the maximum key depth.
    ///
    /// ```
    /// # #[cfg(feature = "derive")] {
    /// use miniconf::{ConstPath, Indices, JsonPath, Lookup, Packed, Path, TreeSchema};
    /// #[derive(TreeSchema)]
    /// struct S {
    ///     foo: u32,
    ///     bar: [u16; 2],
    /// };
    /// const MAX_DEPTH: usize = S::SCHEMA.max_depth();
    /// assert_eq!(MAX_DEPTH, 2);
    ///
    /// let paths: Vec<_> = S::SCHEMA
    ///     .nodes::<Path<String>, MAX_DEPTH>()
    ///     .map(|p| p.unwrap().into_inner())
    ///     .collect();
    /// assert_eq!(paths, ["/foo", "/bar/0", "/bar/1"]);
    ///
    /// let paths: Vec<_> = S::SCHEMA.nodes::<ConstPath<String, ':'>, MAX_DEPTH>()
    ///     .map(|p| p.unwrap().into_inner())
    ///     .collect();
    /// assert_eq!(paths, [":foo", ":bar:0", ":bar:1"]);
    ///
    /// let paths: Vec<_> = S::SCHEMA.nodes::<JsonPath<String>, MAX_DEPTH>()
    ///     .map(|p| p.unwrap().into_inner())
    ///     .collect();
    /// assert_eq!(paths, [".foo", ".bar[0]", ".bar[1]"]);
    ///
    /// let indices: Vec<_> = S::SCHEMA.nodes::<Indices<[_; 2]>, MAX_DEPTH>()
    ///     .map(|p| p.unwrap().into_inner())
    ///     .collect();
    /// assert_eq!(indices, [([0, 0], 1), ([1, 0], 2), ([1, 1], 2)]);
    ///
    /// let packed: Vec<_> = S::SCHEMA.nodes::<Packed, MAX_DEPTH>()
    ///     .map(|p| p.unwrap().into_lsb().get())
    ///     .collect();
    /// assert_eq!(packed, [0b1_0, 0b1_1_0, 0b1_1_1]);
    ///
    /// let nodes: Vec<_> = S::SCHEMA.nodes::<Path<String>, MAX_DEPTH>()
    ///     .map(|p| {
    ///         let p = p.unwrap();
    ///         let lookup = S::SCHEMA.get(p.as_ref()).unwrap();
    ///         ((lookup.depth, lookup.schema.is_leaf()), p.into_inner())
    ///     })
    ///     .collect();
    /// assert_eq!(
    ///     nodes,
    ///     [
    ///         ((1, true), "/foo".into()),
    ///         ((2, true), "/bar/0".into()),
    ///         ((2, true), "/bar/1".into()),
    ///     ]
    /// );
    /// # }
    /// ```
    pub const fn nodes<N: Transcode + Default, const D: usize>(
        &'static self,
    ) -> ExactSize<NodeIter<N, D>> {
        NodeIter::<N, D>::new(self).exact_size()
    }
}