1use std::ffi::OsStr;
2use std::fmt;
3use std::iter::FusedIterator;
4
5use crate::path::{Component, Components, Path};
6
7/// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices.
8///
9/// This `struct` is created by the [`iter`] method on [`Path`].
10/// See its documentation for more.
11///
12/// [`Component`]: enum.Component.html
13/// [`iter`]: struct.Path.html#method.iter
14/// [`OsStr`]: ../../std/ffi/struct.OsStr.html
15/// [`Path`]: struct.Path.html
16#[derive(Clone)]
17pub struct Iter<'a> {
18 pub(crate) inner: Components<'a>,
19}
20
21impl<'a> Iter<'a> {
22 /// Extracts a slice corresponding to the portion of the path remaining for iteration.
23 ///
24 /// # Examples
25 ///
26 /// ```
27 /// use async_std::path::Path;
28 ///
29 /// let mut iter = Path::new("/tmp/foo/bar.txt").iter();
30 /// iter.next();
31 /// iter.next();
32 ///
33 /// assert_eq!(Path::new("foo/bar.txt"), iter.as_path());
34 /// ```
35 pub fn as_path(&self) -> &'a Path {
36 self.inner.as_path()
37 }
38}
39
40impl<'a> Iterator for Iter<'a> {
41 type Item = &'a OsStr;
42
43 fn next(&mut self) -> Option<&'a OsStr> {
44 self.inner.next().map(Component::as_os_str)
45 }
46}
47
48impl fmt::Debug for Iter<'_> {
49 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 struct DebugHelper<'a>(&'a Path);
51
52 impl fmt::Debug for DebugHelper<'_> {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 f.debug_list().entries(self.0.iter()).finish()
55 }
56 }
57
58 f&mut DebugTuple<'_, '_>.debug_tuple(name:"Iter")
59 .field(&DebugHelper(self.as_path()))
60 .finish()
61 }
62}
63
64impl AsRef<Path> for Iter<'_> {
65 fn as_ref(&self) -> &Path {
66 self.as_path()
67 }
68}
69
70impl AsRef<OsStr> for Iter<'_> {
71 fn as_ref(&self) -> &OsStr {
72 self.as_path().as_os_str()
73 }
74}
75
76impl<'a> DoubleEndedIterator for Iter<'a> {
77 fn next_back(&mut self) -> Option<&'a OsStr> {
78 self.inner.next_back().map(Component::as_os_str)
79 }
80}
81
82impl FusedIterator for Iter<'_> {}
83