Simplify find_files::FindFilesIter::next with the help of a helper macro

This commit is contained in:
Skye 2024-11-14 17:52:01 -05:00
parent 71256b7ff4
commit 16589ec6f3

View file

@ -39,15 +39,24 @@ fn find_subs(root: &Path, match_str: &OsStr) -> io::Result<Option<PathBuf>> {
Ok(None)
}
macro_rules! nested_try {
($ex:expr) => {
match $ex {
Ok(val) => val,
Err(e) => return Some(Err(e)),
}
}
}
fn find_files(
root: &Path,
extension: &OsStr,
) -> io::Result<impl Iterator<Item = io::Result<PathBuf>>> {
struct FindFonts {
struct FindFilesIter {
read_dirs: Vec<ReadDir>,
extension: OsString,
}
impl Iterator for FindFonts {
impl Iterator for FindFilesIter {
type Item = io::Result<PathBuf>;
fn next(&mut self) -> Option<Self::Item> {
@ -56,22 +65,12 @@ fn find_files(
self.read_dirs.pop();
continue;
};
let entry = match next {
Ok(entry) => entry,
Err(e) => return Some(Err(e)),
};
let file_type = match entry.file_type() {
Err(e) => return Some(Err(e)),
Ok(file_type) => file_type,
};
let entry = nested_try!(next);
let file_type = nested_try!(entry.file_type());
if file_type.is_dir() {
match entry.path().read_dir() {
Err(e) => return Some(Err(e)),
Ok(read_dir) => {
let read_dir = nested_try!(entry.path().read_dir());
self.read_dirs.push(read_dir);
continue;
}
}
} else {
let path = entry.path();
if path.extension().is_some_and(|ex| ex == self.extension) {
@ -83,7 +82,7 @@ fn find_files(
}
}
}
Ok(FindFonts {
Ok(FindFilesIter {
read_dirs: vec![root.read_dir()?],
extension: extension.to_owned(),
})