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
use std::mem::take;
use std::str::from_utf8_unchecked;

/// An iterator over an [`ObjectPath`].
///
/// [`ObjectPath`]: crate::ObjectPath
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct Iter<'a> {
    data: &'a [u8],
}

impl<'a> Iter<'a> {
    pub(super) fn new(data: &'a [u8]) -> Self {
        // NB: trim leading '/'.
        Self { data: &data[1..] }
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<Self::Item> {
        if self.data.is_empty() {
            return None;
        }

        let data = match self.data.iter().position(|b| *b == b'/') {
            Some(n) => {
                let (head, tail) = self.data.split_at(n);
                self.data = &tail[1..];
                head
            }
            None => take(&mut self.data),
        };

        Some(unsafe { from_utf8_unchecked(data) })
    }
}

impl<'a> DoubleEndedIterator for Iter<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.data.is_empty() {
            return None;
        }

        let data = match self.data.iter().rposition(|b| *b == b'/') {
            Some(n) => {
                let (head, tail) = self.data.split_at(n);
                self.data = head;
                &tail[1..]
            }
            None => take(&mut self.data),
        };

        Some(unsafe { from_utf8_unchecked(data) })
    }
}