From d75b466f6d18834678fc9021b29accca44588e47 Mon Sep 17 00:00:00 2001 From: Julio Biason Date: Thu, 11 Apr 2024 09:17:50 -0300 Subject: [PATCH] Trying something silly with iterators --- yielddirs/Cargo.lock | 7 ++++++ yielddirs/Cargo.toml | 8 +++++++ yielddirs/README.md | 4 ++++ yielddirs/src/main.rs | 51 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 70 insertions(+) create mode 100644 yielddirs/Cargo.lock create mode 100644 yielddirs/Cargo.toml create mode 100644 yielddirs/README.md create mode 100644 yielddirs/src/main.rs diff --git a/yielddirs/Cargo.lock b/yielddirs/Cargo.lock new file mode 100644 index 0000000..724a20b --- /dev/null +++ b/yielddirs/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "yielddirs" +version = "0.1.0" diff --git a/yielddirs/Cargo.toml b/yielddirs/Cargo.toml new file mode 100644 index 0000000..94d358b --- /dev/null +++ b/yielddirs/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "yielddirs" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/yielddirs/README.md b/yielddirs/README.md new file mode 100644 index 0000000..d83a4f7 --- /dev/null +++ b/yielddirs/README.md @@ -0,0 +1,4 @@ +# YieldDirs + +Trying to make an iterator over the filesystem, which spews out some specific +directories. diff --git a/yielddirs/src/main.rs b/yielddirs/src/main.rs new file mode 100644 index 0000000..c4c5580 --- /dev/null +++ b/yielddirs/src/main.rs @@ -0,0 +1,51 @@ +use std::fs::ReadDir; +use std::path::Path; +use std::path::PathBuf; + +struct Walker { + path: PathBuf +} + +impl Walker { + pub fn new(base: &Path) -> Self { + println!("base={base:?}"); + println!("is_dir={}", base.is_dir()); + Self { path: base.to_path_buf()} + } + + pub fn children(&self) -> WalkerIterator { + WalkerIterator::new(&self.path) + } +} + +struct WalkerIterator { + walking: ReadDir +} + +impl WalkerIterator { + fn new(path: &Path) -> Self { + Self { + walking: path.read_dir().unwrap() + } + } +} + +impl Iterator for WalkerIterator { + type Item = String; + + fn next(&mut self) -> Option { + let current = self.walking.next()?; + Some(current.unwrap().file_name().to_string_lossy().to_string()) + } +} + +fn main() { + let mut args = std::env::args(); + let _ = args.next(); + let base_path = args.next().unwrap(); + + let walker = Walker::new(&Path::new(&base_path).canonicalize().unwrap()); + for child in walker.children() { + println!("{child}"); + } +}