Julio Biason
1 year ago
5 changed files with 87 additions and 0 deletions
@ -0,0 +1,7 @@ |
|||||||
|
# This file is automatically @generated by Cargo. |
||||||
|
# It is not intended for manual editing. |
||||||
|
version = 3 |
||||||
|
|
||||||
|
[[package]] |
||||||
|
name = "diritertest" |
||||||
|
version = "0.1.0" |
@ -0,0 +1,8 @@ |
|||||||
|
[package] |
||||||
|
name = "diritertest" |
||||||
|
version = "0.1.0" |
||||||
|
edition = "2021" |
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html |
||||||
|
|
||||||
|
[dependencies] |
@ -0,0 +1,3 @@ |
|||||||
|
# DirIterTest |
||||||
|
|
||||||
|
An iterator over directories (and subdirectories). |
@ -0,0 +1,48 @@ |
|||||||
|
//! Iterator over directories
|
||||||
|
|
||||||
|
use std::collections::VecDeque; |
||||||
|
use std::fs::DirEntry; |
||||||
|
use std::fs::ReadDir; |
||||||
|
use std::path::Path; |
||||||
|
use std::path::PathBuf; |
||||||
|
|
||||||
|
pub struct DirIter { |
||||||
|
curr_dir: ReadDir, |
||||||
|
remaining_dirs: VecDeque<PathBuf>, |
||||||
|
} |
||||||
|
|
||||||
|
impl DirIter { |
||||||
|
pub fn new(start: &Path) -> std::io::Result<Self> { |
||||||
|
Ok(Self { |
||||||
|
curr_dir: start.read_dir()?, |
||||||
|
remaining_dirs: VecDeque::new(), |
||||||
|
}) |
||||||
|
} |
||||||
|
|
||||||
|
pub fn advance(&mut self) -> Option<PathBuf> { |
||||||
|
let next = self.curr_dir.next(); |
||||||
|
match next { |
||||||
|
Some(Ok(x)) => { |
||||||
|
if x.path().is_dir() { |
||||||
|
self.remaining_dirs.push_back(x.path()); |
||||||
|
self.advance() |
||||||
|
} else { |
||||||
|
Some(x.path()) |
||||||
|
} |
||||||
|
} |
||||||
|
Some(Err(_)) | None => { |
||||||
|
let next_dir = self.remaining_dirs.pop_front()?; |
||||||
|
self.curr_dir = std::fs::read_dir(next_dir).ok()?; |
||||||
|
self.advance() |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
impl Iterator for DirIter { |
||||||
|
type Item = PathBuf; |
||||||
|
|
||||||
|
fn next(&mut self) -> Option<Self::Item> { |
||||||
|
self.advance() |
||||||
|
} |
||||||
|
} |
@ -0,0 +1,21 @@ |
|||||||
|
use std::path::Path; |
||||||
|
|
||||||
|
use crate::diriter::DirIter; |
||||||
|
|
||||||
|
mod diriter; |
||||||
|
|
||||||
|
fn main() { |
||||||
|
let mut all_iter = DirIter::new(&Path::new(".")).unwrap(); |
||||||
|
while let Some(path) = all_iter.next() { |
||||||
|
println!(">> {:?}", path); |
||||||
|
} |
||||||
|
|
||||||
|
println!("-----------------------"); |
||||||
|
|
||||||
|
let all_iter = DirIter::new(&Path::new(".")).unwrap(); |
||||||
|
for path in all_iter { |
||||||
|
println!(">>> {:?}", path); |
||||||
|
} |
||||||
|
|
||||||
|
println!("Hello, world!"); |
||||||
|
} |
Loading…
Reference in new issue