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
use crate::form::name::*;

/// A sliding-prefix view into a [`Name`].
///
/// A [`NameView`] maintains a sliding key view into a [`Name`]. The current key
/// ([`key()`]) can be [`shift()`ed](NameView::shift()) one key to the right.
/// The `Name` prefix including the current key can be extracted via
/// [`as_name()`] and the prefix _not_ including the current key via
/// [`parent()`].
///
/// [`key()`]: NameView::key()
/// [`as_name()`]: NameView::as_name()
/// [`parent()`]: NameView::parent()
///
/// This is best illustrated via an example:
///
/// ```rust
/// use rocket::form::name::NameView;
///
/// // The view begins at the first key. Illustrated: `(a).b[c:d]` where
/// // parenthesis enclose the current key.
/// let mut view = NameView::new("a.b[c:d]");
/// assert_eq!(view.key().unwrap(), "a");
/// assert_eq!(view.as_name(), "a");
/// assert_eq!(view.parent(), None);
///
/// // Shifted once to the right views the second key: `a.(b)[c:d]`.
/// view.shift();
/// assert_eq!(view.key().unwrap(), "b");
/// assert_eq!(view.as_name(), "a.b");
/// assert_eq!(view.parent().unwrap(), "a");
///
/// // Shifting again now has predictable results: `a.b[(c:d)]`.
/// view.shift();
/// assert_eq!(view.key().unwrap(), "c:d");
/// assert_eq!(view.as_name(), "a.b[c:d]");
/// assert_eq!(view.parent().unwrap(), "a.b");
///
/// // Shifting past the end means we have no further keys.
/// view.shift();
/// assert_eq!(view.key(), None);
/// assert_eq!(view.key_lossy(), "");
/// assert_eq!(view.as_name(), "a.b[c:d]");
/// assert_eq!(view.parent().unwrap(), "a.b[c:d]");
///
/// view.shift();
/// assert_eq!(view.key(), None);
/// assert_eq!(view.as_name(), "a.b[c:d]");
/// assert_eq!(view.parent().unwrap(), "a.b[c:d]");
/// ```
///
/// # Equality
///
/// `PartialEq`, `Eq`, and `Hash` all operate on the name prefix including the
/// current key. Only key values are compared; delimiters are insignificant.
/// Again, illustrated via examples:
///
/// ```rust
/// use rocket::form::name::NameView;
///
/// let mut view = NameView::new("a.b[c:d]");
/// assert_eq!(view, "a");
///
/// // Shifted once to the right views the second key: `a.(b)[c:d]`.
/// view.shift();
/// assert_eq!(view.key().unwrap(), "b");
/// assert_eq!(view.as_name(), "a.b");
/// assert_eq!(view, "a.b");
/// assert_eq!(view, "a[b]");
///
/// // Shifting again now has predictable results: `a.b[(c:d)]`.
/// view.shift();
/// assert_eq!(view, "a.b[c:d]");
/// assert_eq!(view, "a.b.c:d");
/// assert_eq!(view, "a[b].c:d");
/// assert_eq!(view, "a[b]c:d");
/// ```
#[derive(Copy, Clone)]
pub struct NameView<'v> {
    name: &'v Name,
    start: usize,
    end: usize,
}

impl<'v> NameView<'v> {
    /// Initializes a new `NameView` at the first key of `name`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket::form::name::NameView;
    ///
    /// let mut view = NameView::new("a.b[c:d]");
    /// assert_eq!(view.key().unwrap(), "a");
    /// assert_eq!(view.as_name(), "a");
    /// assert_eq!(view.parent(), None);
    /// ```
    pub fn new<N: Into<&'v Name>>(name: N) -> Self {
        let mut view = NameView { name: name.into(), start: 0, end: 0 };
        view.shift();
        view
    }

    /// Shifts the current key once to the right.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use rocket::form::name::NameView;
    ///
    /// let mut view = NameView::new("a.b[c:d][d.e]");
    /// assert_eq!(view.key().unwrap(), "a");
    ///
    /// view.shift();
    /// assert_eq!(view.key().unwrap(), "b");
    ///
    /// view.shift();
    /// assert_eq!(view.key().unwrap(), "c:d");
    ///
    /// view.shift();
    /// assert_eq!(view.key().unwrap(), "d.e");
    /// ```
    ///
    /// Malformed strings can have interesting results:
    ///
    /// ```rust
    /// use rocket::form::name::NameView;
    ///
    /// let mut view = NameView::new("a[c.d");
    /// assert_eq!(view.key_lossy(), "a");
    ///
    /// view.shift();
    /// assert_eq!(view.key_lossy(), "c.d");
    ///
    /// let mut view = NameView::new("a[c[.d]");
    /// assert_eq!(view.key_lossy(), "a");
    ///
    /// view.shift();
    /// assert_eq!(view.key_lossy(), "c[.d");
    ///
    /// view.shift();
    /// assert_eq!(view.key(), None);
    ///
    /// let mut view = NameView::new("foo[c[.d]]");
    /// assert_eq!(view.key_lossy(), "foo");
    ///
    /// view.shift();
    /// assert_eq!(view.key_lossy(), "c[.d");
    ///
    /// view.shift();
    /// assert_eq!(view.key_lossy(), "]");
    ///
    /// view.shift();
    /// assert_eq!(view.key(), None);
    /// ```
    pub fn shift(&mut self) {
        const START_DELIMS: &[char] = &['.', '['];

        let string = &self.name[self.end..];
        let bytes = string.as_bytes();
        let shift = match bytes.get(0) {
            None | Some(b'=') => 0,
            Some(b'[') => match memchr::memchr(b']', bytes) {
                Some(j) => j + 1,
                None => bytes.len(),
            },
            Some(b'.') => match string[1..].find(START_DELIMS) {
                Some(j) => j + 1,
                None => bytes.len(),
            },
            _ => match string.find(START_DELIMS) {
                Some(j) => j,
                None => bytes.len()
            }
        };

        debug_assert!(self.end + shift <= self.name.len());
        *self = NameView {
            name: self.name,
            start: self.end,
            end: self.end + shift,
        };
    }

    /// Returns the key currently viewed by `self` if it is non-empty.
    ///
    /// ```text
    ///                 food.bart[bar:foo].blam[0_0][][1000]=some-value
    /// name            |----------------------------------|
    /// non-empty key   |--| |--| |-----|  |--| |-|     |--|
    /// empty key                                  |-|
    /// ```
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket::form::name::NameView;
    ///
    /// let mut view = NameView::new("a[b]");
    /// assert_eq!(view.key().unwrap(), "a");
    ///
    /// view.shift();
    /// assert_eq!(view.key().unwrap(), "b");
    ///
    /// view.shift();
    /// assert_eq!(view.key(), None);
    /// # view.shift(); assert_eq!(view.key(), None);
    /// # view.shift(); assert_eq!(view.key(), None);
    /// ```
    pub fn key(&self) -> Option<&'v Key> {
        let lossy_key = self.key_lossy();
        if lossy_key.is_empty() {
            return None;
        }

        Some(lossy_key)
    }

    /// Returns the key currently viewed by `self`, even if it is non-empty.
    ///
    /// ```text
    ///                 food.bart[bar:foo].blam[0_0][][1000]=some-value
    /// name            |----------------------------------|
    /// non-empty key   |--| |--| |-----|  |--| |-|     |--|
    /// empty key                                  |-|
    /// ```
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket::form::name::NameView;
    ///
    /// let mut view = NameView::new("a[b]");
    /// assert_eq!(view.key_lossy(), "a");
    ///
    /// view.shift();
    /// assert_eq!(view.key_lossy(), "b");
    ///
    /// view.shift();
    /// assert_eq!(view.key_lossy(), "");
    /// # view.shift(); assert_eq!(view.key_lossy(), "");
    /// # view.shift(); assert_eq!(view.key_lossy(), "");
    /// ```
    pub fn key_lossy(&self) -> &'v Key {
        let view = &self.name[self.start..self.end];
        let key = match view.as_bytes().get(0) {
            Some(b'.') => &view[1..],
            Some(b'[') if view.ends_with(']') => &view[1..view.len() - 1],
            Some(b'[') if self.is_at_last() => &view[1..],
            _ => view
        };

        key.as_str().into()
    }

    /// Returns the `Name` _up to and including_ the current key.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket::form::name::NameView;
    ///
    /// let mut view = NameView::new("a[b]");
    /// assert_eq!(view.as_name(), "a");
    ///
    /// view.shift();
    /// assert_eq!(view.as_name(), "a[b]");
    /// # view.shift(); assert_eq!(view.as_name(), "a[b]");
    /// # view.shift(); assert_eq!(view.as_name(), "a[b]");
    /// ```
    pub fn as_name(&self) -> &'v Name {
        &self.name[..self.end]
    }

    /// Returns the `Name` _prior to_ the current key.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket::form::name::NameView;
    ///
    /// let mut view = NameView::new("a[b]");
    /// assert_eq!(view.parent(), None);
    ///
    /// view.shift();
    /// assert_eq!(view.parent().unwrap(), "a");
    ///
    /// view.shift();
    /// assert_eq!(view.parent().unwrap(), "a[b]");
    /// # view.shift(); assert_eq!(view.parent().unwrap(), "a[b]");
    /// # view.shift(); assert_eq!(view.parent().unwrap(), "a[b]");
    /// ```
    pub fn parent(&self) -> Option<&'v Name> {
        if self.start > 0 {
            Some(&self.name[..self.start])
        } else {
            None
        }
    }

    /// Returns the underlying `Name`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use rocket::form::name::NameView;
    ///
    /// let mut view = NameView::new("a[b]");
    /// assert_eq!(view.source(), "a[b]");
    ///
    /// view.shift();
    /// assert_eq!(view.source(), "a[b]");
    ///
    /// view.shift();
    /// assert_eq!(view.source(), "a[b]");
    ///
    /// # view.shift(); assert_eq!(view.source(), "a[b]");
    /// # view.shift(); assert_eq!(view.source(), "a[b]");
    /// ```
    pub fn source(&self) -> &'v Name {
        self.name
    }

    // This is the last key. The next `shift()` will exhaust `self`.
    fn is_at_last(&self) -> bool {
        self.end == self.name.len()
    }

    // There are no more keys. A `shift` will do nothing.
    pub(crate) fn exhausted(&self) -> bool {
        self.start == self.name.len()
    }
}

impl std::fmt::Debug for NameView<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.as_name().fmt(f)
    }
}

impl std::fmt::Display for NameView<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.as_name().fmt(f)
    }
}

impl<'a, 'b> PartialEq<NameView<'b>> for NameView<'a> {
    fn eq(&self, other: &NameView<'b>) -> bool {
        self.as_name() == other.as_name()
    }
}

impl<B: PartialEq<Name>> PartialEq<B> for NameView<'_> {
    fn eq(&self, other: &B) -> bool {
        other == self.as_name()
    }
}

impl Eq for NameView<'_> {  }

impl std::hash::Hash for NameView<'_> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.as_name().hash(state)
    }
}

impl std::borrow::Borrow<Name> for NameView<'_> {
    fn borrow(&self) -> &Name {
        self.as_name()
    }
}