Browse Source

Working with iter

master
Julio Biason 8 months ago
parent
commit
ecf71d5dae
  1. 7
      diritertest/Cargo.lock
  2. 8
      diritertest/Cargo.toml
  3. 3
      diritertest/README.md
  4. 48
      diritertest/src/diriter.rs
  5. 21
      diritertest/src/main.rs

7
diritertest/Cargo.lock generated

@ -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"

8
diritertest/Cargo.toml

@ -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]

3
diritertest/README.md

@ -0,0 +1,3 @@
# DirIterTest
An iterator over directories (and subdirectories).

48
diritertest/src/diriter.rs

@ -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()
}
}

21
diritertest/src/main.rs

@ -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…
Cancel
Save