Skip to content

Commit ba87048

Browse files
committed
Implemented our own Path::ancestors iterator
1 parent 8df55dd commit ba87048

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

src/path/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ mod pathbuf;
99

1010
// Structs re-export
1111
#[doc(inline)]
12-
pub use std::path::{Ancestors, Components, Display, Iter, PrefixComponent, StripPrefixError};
12+
pub use std::path::{Components, Display, Iter, PrefixComponent, StripPrefixError};
1313

1414
// Enums re-export
1515
#[doc(inline)]
@@ -23,5 +23,5 @@ pub use std::path::MAIN_SEPARATOR;
2323
#[doc(inline)]
2424
pub use std::path::is_separator;
2525

26-
pub use path::Path;
26+
pub use path::{Ancestors, Path};
2727
pub use pathbuf::PathBuf;

src/path/path.rs

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use std::ffi::OsStr;
2+
use std::iter::FusedIterator;
23

3-
use crate::path::{Ancestors, Components, Display, Iter, PathBuf, StripPrefixError};
4+
use crate::path::{Components, Display, Iter, PathBuf, StripPrefixError};
45
use crate::{fs, io};
56

67
/// This struct is an async version of [`std::path::Path`].
@@ -35,7 +36,7 @@ impl Path {
3536
/// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html
3637
/// [`parent`]: struct.Path.html#method.parent
3738
pub fn ancestors(&self) -> Ancestors<'_> {
38-
self.inner.ancestors()
39+
Ancestors { next: Some(&self) }
3940
}
4041

4142
/// Yields the underlying [`OsStr`] slice.
@@ -752,6 +753,42 @@ impl Path {
752753
}
753754
}
754755

756+
/// An iterator over [`Path`] and its ancestors.
757+
///
758+
/// This `struct` is created by the [`ancestors`] method on [`Path`].
759+
/// See its documentation for more.
760+
///
761+
/// # Examples
762+
///
763+
/// ```
764+
/// use async_std::path::Path;
765+
///
766+
/// let path = Path::new("/foo/bar");
767+
///
768+
/// for ancestor in path.ancestors() {
769+
/// println!("{}", ancestor.display());
770+
/// }
771+
/// ```
772+
///
773+
/// [`ancestors`]: struct.Path.html#method.ancestors
774+
/// [`Path`]: struct.Path.html
775+
#[derive(Copy, Clone, Debug)]
776+
pub struct Ancestors<'a> {
777+
next: Option<&'a Path>,
778+
}
779+
780+
impl<'a> Iterator for Ancestors<'a> {
781+
type Item = &'a Path;
782+
783+
fn next(&mut self) -> Option<Self::Item> {
784+
let next = self.next;
785+
self.next = next.and_then(Path::parent);
786+
next
787+
}
788+
}
789+
790+
impl FusedIterator for Ancestors<'_> {}
791+
755792
impl<'a> From<&'a std::path::Path> for &'a Path {
756793
fn from(path: &'a std::path::Path) -> &'a Path {
757794
&Path::new(path.as_os_str())

0 commit comments

Comments
 (0)