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
use std::{
fs::{self, DirEntry, ReadDir},
io,
path::Path,
};
#[derive(Debug)]
pub enum ErrorKind {
IOError(io::Error),
}
pub type Result<T, E = ErrorKind> = std::result::Result<T, E>;
pub struct WalkDir {
levels: Vec<ReadDir>,
}
impl WalkDir {
pub fn new<P: AsRef<Path>>(path: P) -> Result<WalkDir> {
let mut levels = Vec::new();
levels.push(fs::read_dir(path).map_err(|e| ErrorKind::IOError(e))?);
Ok(WalkDir { levels })
}
}
impl Iterator for WalkDir {
type Item = Result<DirEntry>;
fn next(&mut self) -> Option<Self::Item> {
match self.levels.last_mut() {
Some(current_dir) => match current_dir.next() {
Some(Ok(entry)) => match entry.file_type() {
Ok(file_type) => {
if file_type.is_dir() {
self.levels.push(match fs::read_dir(&entry.path()) {
Ok(v) => v,
Err(e) => return Some(Err(ErrorKind::IOError(e))),
});
}
return Some(Ok(entry));
}
Err(e) => return Some(Err(ErrorKind::IOError(e))),
},
Some(Err(e)) => return Some(Err(ErrorKind::IOError(e))),
None => {
self.levels.pop();
return self.next();
}
},
None => None,
}
}
}