organic/src/parser/list.rs

109 lines
2.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 07:07:12 +00:00
impl<T> Node<T> {
pub fn get_data(&self) -> &T {
&self.data
}
}
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-11 03:04:39 +00:00
pub fn ptr_eq(&self, other: &List<T>) -> bool {
match (self.head.as_ref(), other.head.as_ref()) {
(None, None) => true,
(None, Some(_)) | (Some(_), None) => false,
(Some(me), Some(them)) => Rc::ptr_eq(me, them),
}
}
2022-12-11 07:07:12 +00:00
pub fn iter(&self) -> impl Iterator<Item = &Rc<Node<T>>> {
NodeIter {
position: &self.head,
}
}
2022-12-04 01:38:56 +00:00
}
pub struct NodeIter<'a, T> {
position: &'a Option<Rc<Node<T>>>,
}
impl<'a, T> Iterator for NodeIter<'a, T> {
type Item = &'a Rc<Node<T>>;
fn next(&mut self) -> Option<Self::Item> {
let (return_value, next_position) = match &self.position {
None => return None,
Some(rc_node) => {
let next_position = &rc_node.parent;
let return_value = rc_node;
(return_value, next_position)
}
};
self.position = next_position;
Some(return_value)
}
}