use std::{iter::FromIterator, sync::Arc};
#[derive(Debug)]
pub struct List<T> {
head: Link<T>,
}
type Link<T> = Option<Arc<Node<T>>>;
#[derive(Debug, Default)]
struct Node<T> {
elem: T,
next: Link<T>,
}
impl<T> List<T> {
pub fn new() -> Self {
Self { head: None }
}
#[must_use]
pub fn append(&self, elem: T) -> Self {
List {
head: Some(Arc::new(Node { elem, next: self.head.clone() })),
}
}
pub fn head(&self) -> Option<&T> {
self.head.as_ref().map(|n| &n.elem)
}
pub fn tail(&self) -> List<T> {
List {
head: self.head.as_ref().and_then(|n| n.next.clone()),
}
}
}
impl<T> Clone for List<T> {
fn clone(&self) -> Self {
Self { head: self.head.as_ref().cloned() }
}
}
pub struct Iter<'a, T> {
next: Option<&'a Node<T>>,
}
impl<T> List<T> {
pub fn iter(&self) -> Iter<'_, T> {
Iter { next: self.head.as_deref() }
}
}
impl<T> Default for List<T> {
fn default() -> Self {
List::new()
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
self.next.map(|node| {
self.next = node.next.as_deref();
&node.elem
})
}
}
impl<T> FromIterator<T> for List<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let mut list = Self::new();
for elem in iter {
list = list.append(elem);
}
list
}
}
impl<'a, T> IntoIterator for &'a List<T> {
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[cfg(test)]
mod test {
use super::List;
#[test]
fn basics() {
let list = List::new();
assert_eq!(list.head(), None);
let list = list.append(1).append(2).append(3);
assert_eq!(list.head(), Some(&3));
let list = list.tail();
assert_eq!(list.head(), Some(&2));
let list = list.tail();
assert_eq!(list.head(), Some(&1));
let list = list.tail();
assert_eq!(list.head(), None);
let list = list.tail();
assert_eq!(list.head(), None);
}
}