Skip to main content

better_url/util/parts/path/segments/file/
iter.rs

1//! [`FilePathSegmentsIter`].
2
3use crate::prelude::*;
4
5/// An [`Iterator`] over the [`FilePathSegment`]s of a [`FilePathSegments`].
6#[derive(Debug, Clone)]
7pub struct FilePathSegmentsIter<'a>(SplitSlashes<'a>);
8
9impl<'a> FilePathSegmentsIter<'a> {
10    /// Create a new [`Self`] from a [`SplitSlashes`] without validity checks.
11    /// # Safety
12    /// Every output of [`SplitSlashes::next`] must be a valid input to [`FilePathSegment::new_unchecked`].
13    pub unsafe fn new_unchecked(value: SplitSlashes<'a>) -> Self {
14        Self(value)
15    }
16
17    /// Get the inner [`SplitSlashes`].
18    pub fn into_inner(self) -> SplitSlashes<'a> {
19        self.0
20    }
21
22    /// The range of the remainder as a [`str`].
23    pub fn range_str<B: RangeBounds<isize>>(&self, range: B) -> Option<&'a str> {
24        self.0.range(range)
25    }
26
27    /// The range of the remainder as a [`FilePathSegments`].
28    pub fn range<B: RangeBounds<isize>>(&self, range: B) -> Option<FilePathSegments<'a>> {
29        self.range_str(range).map(|x| unsafe {FilePathSegments::new_unchecked(x)})
30    }
31
32    /// The remaining [`FilePathSegments`].
33    pub fn remainder(&self) -> Option<FilePathSegments<'a>> {
34        Some(unsafe {FilePathSegments::new_unchecked(self.0.remainder()?)})
35    }
36}
37
38impl<'a> IntoIterator for &'a FilePath<'_> {
39    type IntoIter = FilePathSegmentsIter<'a>;
40    type Item     = FilePathSegment     <'a>;
41
42    fn into_iter(self) -> Self::IntoIter {
43        FilePathSegmentsIter(SplitSlashes(Some(unsafe {self.as_str().get_unchecked(1..)})))
44    }
45}
46
47impl<'a> IntoIterator for &'a FilePathSegments<'_> {
48    type IntoIter = FilePathSegmentsIter<'a>;
49    type Item     = FilePathSegment     <'a>;
50
51    fn into_iter(self) -> Self::IntoIter {
52        FilePathSegmentsIter(SplitSlashes(Some(self.as_str())))
53    }
54}
55
56impl<'a> Iterator for FilePathSegmentsIter<'a> {
57    type Item = FilePathSegment<'a>;
58
59    fn next(&mut self) -> Option<Self::Item> {
60        self.0.next().map(|x| unsafe {FilePathSegment::new_unchecked(x)})
61    }
62
63    fn nth(&mut self, n: usize) -> Option<Self::Item> {
64        self.0.nth(n).map(|x| unsafe {FilePathSegment::new_unchecked(x)})
65    }
66
67    fn count(self) -> usize {
68        self.0.count()
69    }
70}
71
72impl<'a> DoubleEndedIterator for FilePathSegmentsIter<'a> {
73    fn next_back(&mut self) -> Option<Self::Item> {
74        self.0.next_back().map(|x| unsafe {FilePathSegment::new_unchecked(x)})
75    }
76
77    fn nth_back(&mut self, n: usize) -> Option<Self::Item> {
78        self.0.nth_back(n).map(|x| unsafe {FilePathSegment::new_unchecked(x)})
79    }
80}