5 releases (3 breaking)

0.4.0 May 26, 2024
0.3.0 Sep 5, 2022
0.2.1 Jul 19, 2022
0.1.2 Jul 18, 2022
0.1.1 Oct 16, 2021

#404 in Development tools

Download history 1475/week @ 2024-08-10 1613/week @ 2024-08-17 926/week @ 2024-08-24 1552/week @ 2024-08-31 1130/week @ 2024-09-07 1502/week @ 2024-09-14 1639/week @ 2024-09-21 971/week @ 2024-09-28 2129/week @ 2024-10-05 2659/week @ 2024-10-12 3580/week @ 2024-10-19 3518/week @ 2024-10-26 3383/week @ 2024-11-02 3605/week @ 2024-11-09 3340/week @ 2024-11-16 3056/week @ 2024-11-23

13,936 downloads per month
Used in 3 crates (2 directly)

MIT license

30KB
415 lines

This crate derives visitor pattern for arbitrary data structures. This pattern is particularly useful when dealing with complex nested data structures, abstract trees and hierarchies of all kinds.

The main building blocks of this crate are two derivable traits:

  • Visitor implementations walk through a data structures and accumulates some information;
  • Drive implementations are data structures that know how to drive a visitor through themselves.

Please refer to these traits' documentation for more details.

Example

use derive_visitor::{Visitor, Drive};

#[derive(Drive)]
struct Directory {
    #[drive(skip)]
    name: String,
    items: Vec<DirectoryItem>,
}

#[derive(Drive)]
enum DirectoryItem {
    File(File),
    Directory(Directory),
}

#[derive(Drive)]
struct File {
    #[drive(skip)]
    name: String,
}

#[derive(Visitor, Default)]
#[visitor(File(enter), Directory(enter))]
struct Counter {
    files: u32,
    directories: u32
}

impl Counter {
    fn enter_file(&mut self, _file: &File) {
        self.files += 1;
    }
    fn enter_directory(&mut self, _directory: &Directory) {
        self.directories += 1;
    }
}

let mut counter = Counter::default();

let example_directory = Directory {
    name: "root".into(),
    items: vec![
        DirectoryItem::Directory(
            Directory {
                name: "home".into(),
                items: vec![
                    DirectoryItem::File(File { name: "README.md".into() }),
                    DirectoryItem::File(File { name: "Star Wars.mov".into() })
                ]
            }
        ),
        DirectoryItem::Directory(
            Directory { name: "downloads".into(), items: vec![] }
        )
    ],
};

example_directory.drive(&mut counter);

assert_eq!(counter.files, 2);
assert_eq!(counter.directories, 3);

Dependencies

~2MB
~46K SLoC