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
use core::{iter::Fuse, num::NonZero};

use crate::Traversal;

/// Data to look up field names and convert to indices
///
/// This struct used together with [`crate::TreeKey`].
pub struct KeyLookup {
    /// The number of top-level nodes.
    ///
    /// This is used by `impl Keys for Packed`.
    pub len: NonZero<usize>,

    /// Node names, if any.
    ///
    /// If nodes have names, this is a slice of them.
    /// If it is `Some`, it's `.len()` is guaranteed to be `LEN`.
    pub names: Option<&'static [&'static str]>,
}

impl KeyLookup {
    /// Return a homogenenous unnamed KeyLookup
    #[inline]
    pub const fn homogeneous(len: usize) -> Self {
        match NonZero::new(len) {
            Some(len) => Self { len, names: None },
            None => panic!("Internal nodes must have at least one leaf"),
        }
    }

    /// Perform a index-to-name lookup
    #[inline]
    pub fn lookup(&self, index: usize) -> Result<Option<&'static str>, Traversal> {
        match self.names {
            Some(names) => {
                debug_assert!(names.len() == self.len.get());
                match names.get(index) {
                    Some(name) => Ok(Some(name)),
                    None => Err(Traversal::NotFound(1)),
                }
            }
            None => {
                if index >= self.len.get() {
                    Err(Traversal::NotFound(1))
                } else {
                    Ok(None)
                }
            }
        }
    }

    /// Check that index is within range
    #[inline]
    pub fn clamp(&self, index: usize) -> Result<usize, Traversal> {
        if index >= self.len.get() {
            Err(Traversal::NotFound(1))
        } else {
            Ok(index)
        }
    }
}

/// Convert a `&str` key into a node index on a `KeyLookup`
pub trait Key {
    /// Convert the key `self` to a `usize` index
    fn find(&self, lookup: &KeyLookup) -> Result<usize, Traversal>;
}

impl<T: Key> Key for &T
where
    T: Key + ?Sized,
{
    #[inline]
    fn find(&self, lookup: &KeyLookup) -> Result<usize, Traversal> {
        (**self).find(lookup)
    }
}

impl<T: Key> Key for &mut T
where
    T: Key + ?Sized,
{
    #[inline]
    fn find(&self, lookup: &KeyLookup) -> Result<usize, Traversal> {
        (**self).find(lookup)
    }
}

// index
macro_rules! impl_key_integer {
    ($($t:ty)+) => {$(
        impl Key for $t {
            #[inline]
            fn find(&self, lookup: &KeyLookup) -> Result<usize, Traversal> {
                let index = (*self).try_into().or(Err(Traversal::NotFound(1)))?;
                lookup.clamp(index)
            }
        }
    )+};
}
impl_key_integer!(usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128);

// name
impl Key for str {
    #[inline]
    fn find(&self, lookup: &KeyLookup) -> Result<usize, Traversal> {
        let index = match lookup.names {
            Some(names) => names.iter().position(|n| *n == self),
            None => self.parse().ok(),
        }
        .ok_or(Traversal::NotFound(1))?;
        lookup.clamp(index)
    }
}

/// Capability to yield and look up [`Key`]s
pub trait Keys {
    /// Look up the next key in a [`KeyLookup`] and convert to `usize` index.
    ///
    /// This must be fused (like [`core::iter::FusedIterator`]).
    fn next(&mut self, lookup: &KeyLookup) -> Result<usize, Traversal>;

    /// Finalize the keys, ensure there are no more.
    ///
    /// This must be fused.
    fn finalize(&mut self) -> Result<(), Traversal>;

    /// Chain another `Keys` to this one.
    #[inline]
    fn chain<U: IntoKeys>(self, other: U) -> Chain<Self, U::IntoKeys>
    where
        Self: Sized,
    {
        Chain(self, other.into_keys())
    }
}

impl<T> Keys for &mut T
where
    T: Keys + ?Sized,
{
    #[inline]
    fn next(&mut self, lookup: &KeyLookup) -> Result<usize, Traversal> {
        (**self).next(lookup)
    }

    #[inline]
    fn finalize(&mut self) -> Result<(), Traversal> {
        (**self).finalize()
    }
}

/// [`Keys`]/[`IntoKeys`] for Iterators of [`Key`]
#[derive(Debug, Clone)]
#[repr(transparent)]
pub struct KeysIter<T>(Fuse<T>);

impl<T: Iterator> KeysIter<T> {
    #[inline]
    fn new(inner: T) -> Self {
        Self(inner.fuse())
    }
}

impl<T> Keys for KeysIter<T>
where
    T: Iterator,
    T::Item: Key,
{
    #[inline]
    fn next(&mut self, lookup: &KeyLookup) -> Result<usize, Traversal> {
        self.0.next().ok_or(Traversal::TooShort(0))?.find(lookup)
    }

    #[inline]
    fn finalize(&mut self) -> Result<(), Traversal> {
        self.0
            .next()
            .is_none()
            .then_some(())
            .ok_or(Traversal::TooLong(0))
    }
}

/// Be converted into a `Keys`
pub trait IntoKeys {
    /// The specific [`Keys`] implementor.
    type IntoKeys: Keys;

    /// Convert `self` into a [`Keys`] implementor.
    fn into_keys(self) -> Self::IntoKeys;
}

impl<T> IntoKeys for T
where
    T: IntoIterator,
    <T::IntoIter as Iterator>::Item: Key,
{
    type IntoKeys = KeysIter<T::IntoIter>;

    #[inline]
    fn into_keys(self) -> Self::IntoKeys {
        KeysIter::new(self.into_iter())
    }
}

impl<T> IntoKeys for KeysIter<T>
where
    T: Iterator,
    T::Item: Key,
{
    type IntoKeys = KeysIter<T>;

    #[inline]
    fn into_keys(self) -> Self::IntoKeys {
        self
    }
}

/// Concatenate two `Keys` of different types
pub struct Chain<T, U>(T, U);

impl<T, U> Chain<T, U> {
    /// Return a new concatenated `Keys`
    #[inline]
    pub fn new(t: T, u: U) -> Self {
        Self(t, u)
    }
}

impl<T: Keys, U: Keys> Keys for Chain<T, U> {
    #[inline]
    fn next(&mut self, lookup: &KeyLookup) -> Result<usize, Traversal> {
        match self.0.next(lookup) {
            Err(Traversal::TooShort(_)) => self.1.next(lookup),
            ret => ret,
        }
    }

    #[inline]
    fn finalize(&mut self) -> Result<(), Traversal> {
        self.0.finalize().and_then(|()| self.1.finalize())
    }
}

impl<T: Keys, U: Keys> IntoKeys for Chain<T, U> {
    type IntoKeys = Self;

    #[inline]
    fn into_keys(self) -> Self::IntoKeys {
        self
    }
}