organic/src/parser/list.rs

68 lines
1.5 KiB
Rust
Raw Normal View History

2022-12-11 02:27:33 +00:00
use std::fmt::Debug;
2022-12-04 01:38:56 +00:00
use std::rc::Rc;
#[derive(Debug)]
2022-12-04 01:38:56 +00:00
pub struct List<T> {
head: Option<Rc<Node<T>>>,
}
impl<T> Clone for List<T> {
fn clone(&self) -> Self {
List {
head: self.head.clone(),
}
}
}
2022-12-04 02:35:30 +00:00
#[derive(Debug, Clone)]
2022-12-04 01:38:56 +00:00
pub struct Node<T> {
data: T,
parent: Option<Rc<Node<T>>>,
}
2022-12-11 02:27:33 +00:00
// TODO: This Debug is only needed because of the try_unwrap+expect
impl<T: Debug> List<T> {
2022-12-04 01:38:56 +00:00
pub fn new() -> Self {
List { head: None }
}
pub fn push_front(&self, data: T) -> List<T> {
List {
head: Some(Rc::new(Node {
data: data,
parent: self.head.clone(),
})),
}
}
pub fn pop_front(&mut self) -> (Option<T>, List<T>) {
match self.head.take() {
2022-12-11 02:27:33 +00:00
None => (None, List::new()),
Some(popped_node) => {
let extracted_node =
Rc::try_unwrap(popped_node).expect("TODO I should handle this better");
(
Some(extracted_node.data),
List {
head: extracted_node.parent,
},
)
}
}
}
pub fn without_front(&self) -> List<T> {
List {
head: self.head.as_ref().map(|node| node.parent.clone()).flatten(),
}
}
pub fn get_data(&self) -> Option<&T> {
2022-12-04 02:50:06 +00:00
self.head.as_ref().map(|rc_node| &rc_node.data)
2022-12-04 01:38:56 +00:00
}
pub fn is_empty(&self) -> bool {
self.head.is_none()
}
2022-12-04 01:38:56 +00:00
}