pub trait Filter<P: PathType + ?Sized> {
// Required method
fn allows(path: &P) -> bool;
}Expand description
A filter for the children of a DirChildren structure.
This is used to filter out children that we don’t want to read into the structure. For example, if we have a directory with a lot of files, we can use this to only read the files we want, for example, that have just a certain extension.
§Examples
For example, for a Filter that only allows .txt files:
use std::path::Path;
use std::path::PathBuf;
use dir_structure::{DirStructure, traits::sync::{DirStructure, DirStructureItem}, dir_children::{DirChildren, Filter}};
use dir_structure::prelude::*;
pub struct TextFileFilter;
impl Filter<Path> for TextFileFilter {
fn allows(path: &Path) -> bool {
path.extension()
.and_then(|s| s.to_str())
.map_or(false, |s| s == "txt")
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let path = PathBuf::from("dir");
#[derive(DirStructure)]
struct Dir<Vfs: VfsCore<Path = Path>> {
#[dir_structure(path = self)]
text_files: DirChildren<String, TextFileFilter, Vfs::Path>,
}
std::fs::write(path.join("file1.txt"), "file1")?;
std::fs::write(path.join("file2.txt"), "file2")?;
std::fs::write(path.join("file3.bin"), "aaa")?;
let dir = Dir::read(&path)?;
assert_eq!(dir.text_files.len(), 2);
assert_eq!(dir.text_files.get_value_by_name("file1.txt"), Some(&String::from("file1")));
assert_eq!(dir.text_files.get_value_by_name("file2.txt"), Some(&String::from("file2")));
assert_eq!(dir.text_files.get_value_by_name("file3.bin"), None);
Ok(())
}Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.