dir_iterator/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#![allow(dead_code)]

#[cfg(test)]
mod test;

use std::*;

#[cfg(feature = "wildcard")]
pub fn wildcard(wildcard: &'static str) -> impl FnMut(&fs::DirEntry) -> bool {
    let wildcard = wc::Wildcard::new(wildcard.as_bytes()).unwrap();
    move |entry| wildcard.is_match(entry.file_name().as_encoded_bytes())
}

pub struct DirIterator {
    // stack representing the current directory dive
    stack: Vec<fs::ReadDir>,
}

impl DirIterator {
    pub fn new(path: impl AsRef<path::Path>) -> Result<Self, io::Error> {
        Ok(Self {
            stack: vec![fs::read_dir(path)?],
        })
    }
}

impl Iterator for DirIterator {
    type Item = Result<fs::DirEntry, io::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(it) = self.stack.last_mut() {
                match it.next() {
                    Some(Ok(entry)) => match entry.file_type() {
                        Ok(file_type) => {
                            if file_type.is_file() {
                                return Some(Ok(entry));
                            } else {
                                self.stack.push(fs::read_dir(entry.path()).expect(""))
                            }
                        }
                        Err(err) => return Some(Err(err)),
                    },
                    Some(Err(err)) => panic!("{err}"),
                    None => {
                        self.stack.pop()?;
                    }
                }
            } else {
                return None;
            }
        }
    }
}