Crate traversable

Crate traversable 

Source
Expand description

§Traversable

A visitor pattern implementation for traversing data structures.

This crate provides Traversable and TraversableMut traits for types that can be traversed, as well as Visitor and VisitorMut traits for types that perform the traversal.

It is designed to be flexible and efficient, allowing for deep traversal of complex data structures.

§Quick Start

Add traversable to your Cargo.toml with the derive feature:

[dependencies]
traversable = { version = "0.2", features = ["derive", "std"] }

Define your data structures and derive Traversable:

use std::any::Any;
use std::ops::ControlFlow;

use traversable::Traversable;
use traversable::Visitor;

#[derive(Traversable)]
struct Directory {
    name: String,
    files: Vec<File>,
    #[traverse(skip)]
    cache_id: u64,
}

#[derive(Traversable)]
struct File {
    name: String,
    size: u64,
}

struct FileCounter {
    count: usize,
    total_size: u64,
}

impl Visitor for FileCounter {
    type Break = ();

    fn enter(&mut self, node: &dyn Any) -> ControlFlow<Self::Break> {
        if let Some(file) = node.downcast_ref::<File>() {
            self.count += 1;
            self.total_size += file.size;
        }
        ControlFlow::Continue(())
    }
}

let root = Directory {
    name: "root".to_string(),
    files: vec![
        File {
            name: "a.txt".to_string(),
            size: 100,
        },
        File {
            name: "b.rs".to_string(),
            size: 200,
        },
    ],
    cache_id: 12345,
};

let mut counter = FileCounter {
    count: 0,
    total_size: 0,
};
root.traverse(&mut counter);

assert_eq!(counter.count, 2);
assert_eq!(counter.total_size, 300);

§Attributes

The derive macro supports the following attributes on fields and variants:

  • #[traverse(skip)]: Skips traversing into the annotated field or variant.
  • #[traverse(with = "function_name")]: Uses a custom function to traverse the field.

§Features

  • derive: Enables procedural macros #[derive(Traversable)] and #[derive(TraversableMut)].
  • std: Enables support for standard library types (e.g., Vec, HashMap, Box).
  • traverse-trivial: Enables traversal for primitive types (u8, i32, bool, etc.). By default, these are ignored.
  • traverse-std: Enables traversal for “primary” std types like String. By default, these are ignored. Note that container types like Vec are always traversed if the std feature is enabled.

Modules§

combinator
Combinators for Visitors.
function
Visitors from functions or closures.

Traits§

Traversable
A trait for types that can be traversed by a visitor.
TraversableMut
A trait for types that can be traversed mutably by a visitor.
Visitor
A visitor that can be used to traverse a data structure.
VisitorMut
A visitor that can be used to traverse a mutable data structure.