Trait Filter

Source
pub trait Filter {
    // Required methods
    fn make_filter() -> Self;
    fn allows(&self, path: &Path) -> 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, DirStructureItem, DirChildren, Filter};

pub struct TextFileFilter;

impl Filter for TextFileFilter {
    fn make_filter() -> Self {
       Self
    }

    fn allows(&self, 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 {
       #[dir_structure(path = self)]
       text_files: DirChildren<String, TextFileFilter>,
    }


    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§

Source

fn make_filter() -> Self

Creates an instance of this filter.

Source

fn allows(&self, path: &Path) -> bool

Checks if the path is allowed by this filter.

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.

Implementors§