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