Struct Tree

Source
pub struct Tree<T> { /* private fields */ }
Expand description

A tree structure containing multiple nodes of generic type T.

Each node in the tree is indexed by its position in the internal vector. The tree supports operations for adding, accessing, and traversing nodes.

§Example

use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node("root");
let child = tree.add_child(root, "child");

Implementations§

Source§

impl<T> Tree<T>

Source

pub fn new() -> Self

Creates a new, empty tree.

§Returns

A Tree instance with no nodes.

§Example
use easy_tree::Tree;

let tree: Tree<i32> = Tree::new();
Examples found in repository?
examples/basic.rs (line 4)
3fn main() {
4    let mut tree = Tree::new();
5    let root = tree.add_node("root");
6    let child = tree.add_child(root, "child");
7    let grandchild = tree.add_child(child, "grandchild");
8
9    assert_eq!(tree.get(root), Some(&"root"));
10    assert_eq!(tree.get(grandchild), Some(&"grandchild"));
11}
More examples
Hide additional examples
examples/traversal.rs (line 4)
3fn main() {
4    let mut tree = Tree::new();
5    let root = tree.add_node("root");
6    let child1 = tree.add_child(root, "child1");
7    let _grandchild1 = tree.add_child(child1, "grandchild1");
8    let _child2 = tree.add_child(root, "child2");
9
10    let mut log = vec![];
11    tree.traverse(
12        |idx, data, log| log.push(format!("Visiting node {}: {}", idx, data)),
13        |idx, data, log| log.push(format!("Finished node {}: {}", idx, data)),
14        &mut log,
15    );
16
17    println!("{:?}", log);
18}
Source

pub fn add_node(&mut self, data: T) -> usize

Adds a new node to the tree.

This method is typically used to add a root node or a disconnected node.

§Parameters
  • data: The data to associate with the new node.
§Returns

The index of the newly added node.

§Example
use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node("root");
Examples found in repository?
examples/basic.rs (line 5)
3fn main() {
4    let mut tree = Tree::new();
5    let root = tree.add_node("root");
6    let child = tree.add_child(root, "child");
7    let grandchild = tree.add_child(child, "grandchild");
8
9    assert_eq!(tree.get(root), Some(&"root"));
10    assert_eq!(tree.get(grandchild), Some(&"grandchild"));
11}
More examples
Hide additional examples
examples/traversal.rs (line 5)
3fn main() {
4    let mut tree = Tree::new();
5    let root = tree.add_node("root");
6    let child1 = tree.add_child(root, "child1");
7    let _grandchild1 = tree.add_child(child1, "grandchild1");
8    let _child2 = tree.add_child(root, "child2");
9
10    let mut log = vec![];
11    tree.traverse(
12        |idx, data, log| log.push(format!("Visiting node {}: {}", idx, data)),
13        |idx, data, log| log.push(format!("Finished node {}: {}", idx, data)),
14        &mut log,
15    );
16
17    println!("{:?}", log);
18}
Source

pub fn add_child(&mut self, parent: usize, data: T) -> usize

Adds a child node to an existing node in the tree.

§Parameters
  • parent: The index of the parent node.
  • data: The data to associate with the new child node.
§Returns

The index of the newly added child node.

§Example
use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node("root");
let child = tree.add_child(root, "child");
Examples found in repository?
examples/basic.rs (line 6)
3fn main() {
4    let mut tree = Tree::new();
5    let root = tree.add_node("root");
6    let child = tree.add_child(root, "child");
7    let grandchild = tree.add_child(child, "grandchild");
8
9    assert_eq!(tree.get(root), Some(&"root"));
10    assert_eq!(tree.get(grandchild), Some(&"grandchild"));
11}
More examples
Hide additional examples
examples/traversal.rs (line 6)
3fn main() {
4    let mut tree = Tree::new();
5    let root = tree.add_node("root");
6    let child1 = tree.add_child(root, "child1");
7    let _grandchild1 = tree.add_child(child1, "grandchild1");
8    let _child2 = tree.add_child(root, "child2");
9
10    let mut log = vec![];
11    tree.traverse(
12        |idx, data, log| log.push(format!("Visiting node {}: {}", idx, data)),
13        |idx, data, log| log.push(format!("Finished node {}: {}", idx, data)),
14        &mut log,
15    );
16
17    println!("{:?}", log);
18}
Source

pub fn add_child_to_root(&mut self, data: T) -> usize

Adds a child node to the tree root.

§Parameters
  • data: The data to associate with the new child node.
§Returns

The index of the newly added child node.

§Example
use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node("root");
let child = tree.add_child_to_root("child");
Source

pub fn get(&self, index: usize) -> Option<&T>

Retrieves a reference to the data stored in a node.

§Parameters
  • index: The index of the node to access.
§Returns

Some(&T) if the node exists, or None if the index is out of bounds.

§Example
use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node(42);
assert_eq!(tree.get(root), Some(&42));
Examples found in repository?
examples/basic.rs (line 9)
3fn main() {
4    let mut tree = Tree::new();
5    let root = tree.add_node("root");
6    let child = tree.add_child(root, "child");
7    let grandchild = tree.add_child(child, "grandchild");
8
9    assert_eq!(tree.get(root), Some(&"root"));
10    assert_eq!(tree.get(grandchild), Some(&"grandchild"));
11}
Source

pub fn get_unchecked(&self, index: usize) -> &T

Retrieves a reference to the data stored in a node without bounds checking.

This method is faster than Tree::get because it does not perform any bounds checking. However, it is unsafe to use if the provided index is out of bounds or invalid.

§Parameters
  • index: The index of the node to access.
§Returns

A reference to the data stored in the node.

§Safety

Ensure that:

  • The index is within the valid range of node indices in the tree (0 to Tree::len() - 1).
  • The node at the given index exists and has not been removed (if applicable).
§Example
use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node(42);

// Safe use: The index is valid.
assert_eq!(tree.get_unchecked(root), &42);

// Unsafe use: Accessing an invalid index would cause undefined behavior.
// let invalid = tree.get_unchecked(999); // Avoid this!
Source

pub fn get_mut(&mut self, index: usize) -> Option<&mut T>

Retrieves a mutable reference to the data stored in a node.

§Parameters
  • index: The index of the node to access.
§Returns

Some(&mut T) if the node exists, or None if the index is out of bounds.

§Example
use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node(42);
*tree.get_mut(root).unwrap() = 43;
assert_eq!(tree.get(root), Some(&43));
Source

pub fn get_unchecked_mut(&mut self, index: usize) -> &mut T

Retrieves a mutable reference to the data stored in a node without bounds checking.

This method is faster than Tree::get_mut because it does not perform any bounds checking. However, it is unsafe to use if the provided index is out of bounds or invalid.

§Parameters
  • index: The index of the node to access.
§Returns

A mutable reference to the data stored in the node.

§Safety

Ensure that:

  • The index is within the valid range of node indices in the tree (0 to Tree::len() - 1).
  • The node at the given index exists and has not been removed (if applicable).
  • No other references to the same node are active during this call, to avoid data races or aliasing violations.
§Example
use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node(42);

// Safe use: The index is valid.
*tree.get_unchecked_mut(root) = 99;
assert_eq!(tree.get_unchecked(root), &99);

// Unsafe use: Accessing an invalid index would cause undefined behavior.
// let invalid = tree.get_unchecked_mut(999); // Avoid this!
Source

pub fn parent_index_unchecked(&self, index: usize) -> Option<usize>

Returns the parent index of a node, if it has a parent.

§Parameters
  • index: The index of the node.
§Returns

Some(parent_index) if the node has a parent, or None otherwise.

§Panics

This method panics if the index is out of bounds.

§Example
use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node(42);
let child = tree.add_child(root, 99);
assert_eq!(tree.parent_index_unchecked(child), Some(root));
Source

pub fn children(&self, index: usize) -> &[usize]

Returns a slice of the indices of the children of a node.

§Parameters
  • index: The index of the node.
§Returns

A slice containing the indices of the node’s children.

§Panics

This method panics if the index is out of bounds.

§Example
use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node("root");
let child = tree.add_child(root, "child");
assert_eq!(tree.children(root), &[child]);
Source

pub fn traverse<'a, S>( &'a self, before_processing_children: impl FnMut(usize, &'a T, &mut S), after_processing_the_subtree: impl FnMut(usize, &'a T, &mut S), s: &mut S, )

Traverses the tree in a depth-first manner.

The traversal applies two callbacks:

  • before_processing_children: Called before processing the children of a node.
  • after_processing_the_subtree: Called after processing all children of a node.
§Parameters
  • before_processing_children: A function to apply before visiting children.
  • after_processing_the_subtree: A function to apply after visiting children.
  • state: Mutable state to share across callbacks.
§Example
use easy_tree::Tree;

let mut tree = Tree::new();
let root = tree.add_node("root");
let child = tree.add_child(root, "child");

let mut log = vec![];
tree.traverse(
    |idx, data, log| log.push(format!("Entering node {}: {}", idx, data)),
    |idx, data, log| log.push(format!("Leaving node {}: {}", idx, data)),
    &mut log,
);
Examples found in repository?
examples/traversal.rs (lines 11-15)
3fn main() {
4    let mut tree = Tree::new();
5    let root = tree.add_node("root");
6    let child1 = tree.add_child(root, "child1");
7    let _grandchild1 = tree.add_child(child1, "grandchild1");
8    let _child2 = tree.add_child(root, "child2");
9
10    let mut log = vec![];
11    tree.traverse(
12        |idx, data, log| log.push(format!("Visiting node {}: {}", idx, data)),
13        |idx, data, log| log.push(format!("Finished node {}: {}", idx, data)),
14        &mut log,
15    );
16
17    println!("{:?}", log);
18}
Source

pub fn iter(&self) -> impl Iterator<Item = (usize, &T)>

Returns an iterator over the indices and data of the nodes in the tree.

Source

pub fn iter_mut(&mut self) -> impl Iterator<Item = (usize, &mut T)>

Returns a mutable iterator over the indices and data of the nodes in the tree.

Source

pub fn is_empty(&self) -> bool

Returns true if the tree contains no nodes.

Source

pub fn len(&self) -> usize

Returns the number of nodes in the tree.

Source

pub fn clear(&mut self)

Removes all nodes from the tree.

Source§

impl<T: Send + Sync> Tree<T>

Source

pub fn par_iter(&self) -> impl ParallelIterator<Item = (usize, &T)>

Returns a parallel iterator over the indices and data of the nodes in the tree.

Source

pub fn par_iter_mut(&mut self) -> impl ParallelIterator<Item = (usize, &mut T)>

Returns a mutable parallel iterator over the indices and data of the nodes in the tree.

Trait Implementations§

Source§

impl<T: Clone> Clone for Tree<T>

Source§

fn clone(&self) -> Tree<T>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T> Default for Tree<T>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Tree<T>

§

impl<T> RefUnwindSafe for Tree<T>
where T: RefUnwindSafe,

§

impl<T> Send for Tree<T>
where T: Send,

§

impl<T> Sync for Tree<T>
where T: Sync,

§

impl<T> Unpin for Tree<T>
where T: Unpin,

§

impl<T> UnwindSafe for Tree<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.