2022-12-10 21:27:33 -05:00
|
|
|
use std::fmt::Debug;
|
2022-12-04 00:02:15 -05:00
|
|
|
|
2022-12-03 21:35:30 -05:00
|
|
|
#[derive(Debug, Clone)]
|
2023-09-02 18:19:52 -04:00
|
|
|
pub struct List<'parent, T> {
|
2022-12-03 20:38:56 -05:00
|
|
|
data: T,
|
2023-09-02 18:19:52 -04:00
|
|
|
parent: Link<'parent, T>,
|
2022-12-11 02:07:12 -05:00
|
|
|
}
|
|
|
|
|
2023-09-02 18:19:52 -04:00
|
|
|
type Link<'parent, T> = Option<&'parent List<'parent, T>>;
|
2022-12-03 20:38:56 -05:00
|
|
|
|
2023-09-02 18:19:52 -04:00
|
|
|
impl<'parent, T> List<'parent, T> {
|
|
|
|
pub fn new(first_item: T) -> Self {
|
|
|
|
Self {
|
|
|
|
data: first_item,
|
|
|
|
parent: None,
|
2022-12-10 21:27:33 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-02 18:19:52 -04:00
|
|
|
pub fn get_data(&self) -> &T {
|
|
|
|
&self.data
|
2022-12-10 22:04:39 -05:00
|
|
|
}
|
2022-12-11 02:07:12 -05:00
|
|
|
|
2023-09-02 18:19:52 -04:00
|
|
|
pub fn get_parent(&'parent self) -> Link<'parent, T> {
|
|
|
|
self.parent
|
2022-12-11 02:07:12 -05:00
|
|
|
}
|
2022-12-15 23:52:52 -05:00
|
|
|
|
2023-09-02 18:19:52 -04:00
|
|
|
pub fn iter(&self) -> Iter<'_, T> {
|
|
|
|
Iter { next: Some(self) }
|
2022-12-16 00:47:33 -05:00
|
|
|
}
|
2022-12-03 20:38:56 -05:00
|
|
|
}
|
2022-12-11 01:04:51 -05:00
|
|
|
|
2023-09-02 18:19:52 -04:00
|
|
|
pub trait ListType<'parent, T> {
|
|
|
|
fn push(&'parent self, item: T) -> List<'parent, T>;
|
2022-12-11 01:04:51 -05:00
|
|
|
}
|
|
|
|
|
2023-09-02 18:19:52 -04:00
|
|
|
impl<'parent, T> ListType<'parent, T> for List<'parent, T> {
|
|
|
|
fn push(&'parent self, item: T) -> Self {
|
|
|
|
Self {
|
|
|
|
data: item,
|
|
|
|
parent: Some(self),
|
|
|
|
}
|
2022-12-11 01:04:51 -05:00
|
|
|
}
|
|
|
|
}
|
2022-12-15 23:52:52 -05:00
|
|
|
|
2023-09-02 18:19:52 -04:00
|
|
|
impl<'parent, T> ListType<'parent, T> for Link<'parent, T> {
|
|
|
|
fn push(&'parent self, item: T) -> List<'parent, T> {
|
|
|
|
List {
|
|
|
|
data: item,
|
|
|
|
parent: *self,
|
|
|
|
}
|
2022-12-15 23:52:52 -05:00
|
|
|
}
|
|
|
|
}
|
2022-12-16 00:47:33 -05:00
|
|
|
|
2023-09-02 18:19:52 -04:00
|
|
|
pub struct Iter<'a, T> {
|
|
|
|
next: Link<'a, T>,
|
2022-12-16 00:47:33 -05:00
|
|
|
}
|
|
|
|
|
2023-09-02 18:19:52 -04:00
|
|
|
impl<'a, T> Iterator for Iter<'a, T> {
|
|
|
|
type Item = &'a T;
|
2022-12-16 00:47:33 -05:00
|
|
|
|
|
|
|
fn next(&mut self) -> Option<Self::Item> {
|
2023-09-02 18:19:52 -04:00
|
|
|
let ret = self.next.map(|link| link.get_data());
|
|
|
|
self.next = self.next.map(|link| link.get_parent()).flatten();
|
|
|
|
ret
|
2022-12-16 00:47:33 -05:00
|
|
|
}
|
|
|
|
}
|