organic/src/context/list.rs

70 lines
1.4 KiB
Rust
Raw Normal View History

2022-12-11 02:27:33 +00:00
use std::fmt::Debug;
2022-12-04 02:35:30 +00:00
#[derive(Debug, Clone)]
pub struct List<'parent, T> {
2022-12-04 01:38:56 +00:00
data: T,
parent: Link<'parent, T>,
2022-12-11 07:07:12 +00:00
}
type Link<'parent, T> = Option<&'parent List<'parent, T>>;
2022-12-04 01:38:56 +00:00
impl<'parent, T> List<'parent, T> {
pub fn new(first_item: T) -> Self {
Self {
data: first_item,
parent: None,
2022-12-11 02:27:33 +00:00
}
}
pub fn get_data(&self) -> &T {
&self.data
2022-12-11 03:04:39 +00:00
}
2022-12-11 07:07:12 +00:00
pub fn get_parent(&'parent self) -> Link<'parent, T> {
self.parent
2022-12-11 07:07:12 +00:00
}
2022-12-16 04:52:52 +00:00
pub fn iter(&self) -> Iter<'_, T> {
Iter { next: Some(self) }
}
2023-09-03 00:46:17 +00:00
pub fn iter_list(&self) -> IterList<'_, T> {
2023-09-03 00:52:02 +00:00
IterList { next: Some(self) }
2023-09-03 00:46:17 +00:00
}
pub fn push(&'parent self, item: T) -> Self {
Self {
data: item,
parent: Some(self),
}
}
}
2022-12-16 04:52:52 +00:00
pub struct Iter<'a, T> {
next: Link<'a, T>,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let ret = self.next.map(|link| link.get_data());
self.next = self.next.map(|link| link.get_parent()).flatten();
ret
}
}
2023-09-03 00:46:17 +00:00
pub struct IterList<'a, T> {
next: Link<'a, T>,
}
impl<'a, T> Iterator for IterList<'a, T> {
type Item = &'a List<'a, T>;
fn next(&mut self) -> Option<Self::Item> {
let ret = self.next;
self.next = self.next.map(|this| this.get_parent()).flatten();
ret
}
}