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-11 13:13:28 -04:00
pub ( crate ) 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-23 17:33:46 -04:00
// TODO: Should I be defining a lifetime for T in the generics here? Ref: https://quinedot.github.io/rust-learning/dyn-elision-advanced.html#iteraction-with-type-aliases
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 > {
2023-09-11 13:13:28 -04:00
pub ( crate ) fn new ( first_item : T ) -> Self {
2023-09-02 18:19:52 -04:00
Self {
data : first_item ,
parent : None ,
2022-12-10 21:27:33 -05:00
}
}
2023-09-11 13:13:28 -04:00
pub ( crate ) fn get_data ( & self ) -> & T {
2023-09-02 18:19:52 -04:00
& self . data
2022-12-10 22:04:39 -05:00
}
2022-12-11 02:07:12 -05:00
2023-09-11 13:13:28 -04:00
pub ( crate ) fn get_parent ( & ' parent self ) -> Link < ' parent , T > {
2023-09-02 18:19:52 -04:00
self . parent
2022-12-11 02:07:12 -05:00
}
2022-12-15 23:52:52 -05:00
2023-09-11 13:13:28 -04:00
pub ( crate ) fn iter ( & self ) -> Iter < '_ , T > {
2023-09-02 18:19:52 -04:00
Iter { next : Some ( self ) }
2022-12-16 00:47:33 -05:00
}
2023-09-02 20:46:17 -04:00
2023-09-11 13:13:28 -04:00
pub ( crate ) fn iter_list ( & self ) -> IterList < '_ , T > {
2023-09-02 20:52:02 -04:00
IterList { next : Some ( self ) }
2023-09-02 20:46:17 -04:00
}
2022-12-11 01:04:51 -05:00
2023-09-11 13:13:28 -04:00
pub ( crate ) fn push ( & ' parent self , item : T ) -> Self {
2023-09-02 18:19:52 -04:00
Self {
data : item ,
parent : Some ( self ) ,
}
2022-12-11 01:04:51 -05:00
}
}
2022-12-15 23:52:52 -05:00
2023-09-11 13:13:28 -04:00
pub ( crate ) struct Iter < ' a , T > {
2023-09-02 18:19:52 -04:00
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
}
}
2023-09-02 20:46:17 -04:00
2023-09-11 13:13:28 -04:00
pub ( crate ) struct IterList < ' a , T > {
2023-09-02 20:46:17 -04:00
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
}
}