The unique-pointer
crate provides an experimental data structure
UniquePointer
that makes extensive use of [unsafe
] rust to
provide a shared pointer across other data structures.
This crate is designed to be used as a building block of data-structures and aims at being particularly useful in allowing computer science students to implement data structures such as linked-lists and binary trees in rust while not spending much time tinkering with rust lifetimes.
Permits using UniquePointer<T>
where T
does not implement std::fmt::Debug
cargo add unique-pointer --allow-no-debug
#[derive(Clone, Debug, Hash)]
pub struct LinkedList<T: Debug> {
pub item: T,
pub next: UniquePointer<LinkedList<T>>,
}
impl<T: Debug> LinkedList<T> {
pub fn new(item: T) -> LinkedList<T> {
LinkedList {
item,
next: UniquePointer::null(),
}
}
pub fn append(&mut self, value: T) -> LinkedList<T> {
let next = LinkedList::new(value);
self.next.write_ref(&next);
next
}
pub fn next(&self) -> Option<&LinkedList<T>> {
self.next.as_ref()
}
pub fn len(&self) -> usize {
let mut length = 1;
if let Some(next) = self.next() {
length += 1;
length += next.len();
}
length
}
}
#[test]
fn test_linked_list() {
let mut a = LinkedList::new("a");
let mut b = a.append("b");
let c = b.append("c");
assert_eq!(a.len(), 3);
}