Canopy is a small tree-based data structure implemented in Rust. It provides a way to model hierarchical relationships with two types of nodes: Node::Parent and Node::Leaf. The structure is defined as follows:
Node::Parentnodes hold references to their children and optionally to their parents, along with their value.Node::Leafnodes store just a value and do not have any children, making them terminal points in the tree structure. However, leaf nodes may also be able to be upgraded toNode::Parentsallowing them to have children.- std library feature where
PrevNodeRef, isWeak<RefCell<T>>whileno_stdusesrclite::Rc<RefCell<T>>.
- std library feature where
Canopy uses Rust’s pattern within to enable shared mutability and ownership, which makes it well-suited for managing dynamic, tree-like data.
Quick Tour
graph TD;
root-->child;
root-->child2;
child2-->grand_child1;
child2-->grand_child2;
To quickly get acquainted with the interface, let's create a simple graph structure like the one above. We'll also demonstrate some basic operations available in canopy.
Insert
To build our structure, we start by instantiating the parent node using Node::parent(). This function returns a reference-counted Node::Parent.
To add children, we pass a reference to the parent node and the value we want to insert. This rule applies recursively to all descendants.
use ;
Pop
The pop operation removes a child node from its parent. If all children are removed, the parent node is downgraded back to a Node::Leaf.
Iterate
We can iterate over the nodes using Node::iter(). This allows us to traverse the tree structure.
use ;
Features
- Tree-based structure with mutable and shared ownership via
Rc<RefCell<T>>, andWeak<RefCell<T>>. - Ability to model both parent-child relationships.
- Safety-focused code development, on trying to adhering to the "Power of 10" rules for safety-critical systems.
- Iter though using a BFS data-type
NodeIter<T> - Supports
#[no_std]
Installation
To use Canopy in your project, add it to your Cargo.toml:
[]
# Git version
# libcanopy = { git = "https://github.com/LVivona/canopy", branch = "main" }
# Cargo.io version
= { = "*" }
Closing Remarks
This project is also a personal experiment to apply best practices in developing safety-critical code. By adhering to the "Power of 10" rules for writing safe and reliable systems, the goal is to create robust, memory-safe code while exploring the depths of Rust’s safety features.