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