Implement Thread::start and join

This commit is contained in:
Quentin Legot
2023-03-01 16:55:17 +01:00
committed by François Autin
parent c140830faa
commit 83df053dc6
6 changed files with 264 additions and 163 deletions

View File

@ -1,178 +1,217 @@
use std::{cell::RefCell, rc::Rc};
/// Definition of an element of the list
///
/// Contain one stored item and the previous/next element of the list
struct ListNode<T> {
item: T,
next: Link<T>,
prev: Link<T>,
}
impl<T> ListNode<T> {
fn new(item: T) -> Self {
Self {
item,
next: None,
prev: None,
}
}
}
type Link<T> = Option<Rc<RefCell<ListNode<T>>>>;
/// Defintion of the generic linked list
#[derive(Default)]
pub struct DoublyLinkedList<T> {
pub struct List<T: PartialEq> {
head: Link<T>,
tail: Link<T>,
size: usize,
}
impl<T> DoublyLinkedList<T> {
type Link<T> = Option<Box<Node<T>>>;
struct Node<T> {
elem: T,
next: Link<T>,
}
impl<T: PartialEq> List<T> {
pub fn new() -> Self {
Self {
head: None,
tail: None,
size: 0,
}
List { head: None }
}
pub fn is_empty(&self) -> bool {
self.len() == 0
/// Push an item at the end of the list
pub fn push(&mut self, elem: T) {
let new_node = Box::new(Node {
elem: elem,
next: self.head.take(),
});
self.head = Some(new_node);
}
pub fn len(&self) -> usize {
self.size
}
/// Add the item at the end of the list
pub fn push_back(&mut self, item: T) {
let node = Rc::new(RefCell::new(ListNode::new(item)));
if let Some(prev_tail) = self.tail.take() {
prev_tail.borrow_mut().next = Some(Rc::clone(&node));
node.borrow_mut().prev = Some(prev_tail);
self.tail = Some(node);
self.size += 1;
} else {
self.head = Some(Rc::clone(&node));
self.tail = Some(node);
self.size = 1;
}
}
/// Add the item at the start of the list
pub fn push_front(&mut self, item: T) {
let node = Rc::new(RefCell::new(ListNode::new(item)));
if let Some(prev_head) = self.head.take() {
prev_head.borrow_mut().prev = Some(Rc::clone(&node));
node.borrow_mut().next = Some(prev_head);
self.head = Some(node);
self.size += 1;
} else {
self.head = Some(Rc::clone(&node));
self.tail = Some(node);
self.size = 1;
}
}
/// Retrieve and remove the item at the end of the list
pub fn pop_back(&mut self) -> Option<T> {
self.tail.take().map(|prev_tail| {
self.size -= 1;
match prev_tail.borrow_mut().prev.take() {
Some(node) => {
node.borrow_mut().next = None;
self.tail = Some(node);
}
None => {
self.head.take();
}
}
Rc::try_unwrap(prev_tail).ok().unwrap().into_inner().item
/// Retrieve and remove the item at the end of the list.
///
/// Return None if list is empty
pub fn pop(&mut self) -> Option<T> {
self.head.take().map(|node| {
self.head = node.next;
node.elem
})
}
/// Retrieve and remove the item at the start of the list
pub fn pop_front(&mut self) -> Option<T> {
self.head.take().map(|prev_head| {
self.size -= 1;
match prev_head.borrow_mut().next.take() {
Some(node) => {
node.borrow_mut().prev = None;
self.head = Some(node);
}
None => {
self.tail.take();
}
}
Rc::try_unwrap(prev_head).ok().unwrap().into_inner().item
/// Retrieve without removing the item at the end of the list
///
/// Return None if list is empty
pub fn peek(&self) -> Option<&T> {
self.head.as_ref().map(|node| {
&node.elem
})
}
/// Retrieve without removing the item at the end of the list as mutable
///
/// Return None if lsit is empty
pub fn peek_mut(&mut self) -> Option<&mut T> {
self.head.as_mut().map(|node| {
&mut node.elem
})
}
/// Search for an element in the list
///
/// Return **bool** true if the list contains the element, false otherwise
///
/// Worst case complexity of this function is O(n)
pub fn contains(&self, elem: &T) -> bool {
let mut iter = self.iter();
let element = iter.next();
while element.is_some() {
if element.unwrap() == elem {
return true;
}
}
false
}
pub fn into_iter(self) -> IntoIter<T> {
IntoIter(self)
}
pub fn iter(&self) -> Iter<'_, T> {
Iter { next: self.head.as_deref() }
}
pub fn iter_mut(&mut self) -> IterMut<'_, T> {
IterMut { next: self.head.as_deref_mut() }
}
}
impl<T> Drop for DoublyLinkedList<T> {
/// list destructor, safely desallocate smart pointer Rc
impl<T: PartialEq> Drop for List<T> {
fn drop(&mut self) {
while let Some(node) = self.head.take() {
let _ = node.borrow_mut().prev.take();
self.head = node.borrow_mut().next.take();
let mut cur_link = self.head.take();
while let Some(mut boxed_node) = cur_link {
cur_link = boxed_node.next.take();
}
self.tail.take();
}
}
impl<T> IntoIterator for DoublyLinkedList<T> {
type Item = <ListIterator<T> as Iterator>::Item;
pub struct IntoIter<T: PartialEq>(List<T>);
type IntoIter = ListIterator<T>;
fn into_iter(self) -> Self::IntoIter {
Self::IntoIter::new(self)
}
}
pub struct ListIterator<T> {
list: DoublyLinkedList<T>,
}
impl<T> ListIterator<T> {
fn new(list: DoublyLinkedList<T>) -> Self {
Self { list }
}
}
impl<T> Iterator for ListIterator<T> {
impl<T: PartialEq> Iterator for IntoIter<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
// access fields of a tuple struct numerically
self.0.pop()
}
}
pub struct Iter<'a, T> {
next: Option<&'a Node<T>>,
}
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
})
}
}
pub struct IterMut<'a, T> {
next: Option<&'a mut Node<T>>,
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<Self::Item> {
self.list.pop_front()
self.next.take().map(|node| {
self.next = node.next.as_deref_mut();
&mut node.elem
})
}
}
impl<T> DoubleEndedIterator for ListIterator<T> {
fn next_back(&mut self) -> Option<Self::Item> {
self.list.pop_back()
}
}
pub type List<T> = DoublyLinkedList<T>;
pub type ListInt = List<i32>;
#[cfg(test)]
mod test {
use super::DoublyLinkedList;
use super::List;
#[test]
fn test_list_push() {
let mut list = DoublyLinkedList::new();
list.push_back(5);
list.push_front(45);
assert_eq!(list.pop_front().unwrap(), 45);
assert_eq!(list.pop_front().unwrap(), 5);
fn basics() {
let mut list = List::new();
// Check empty list behaves right
assert_eq!(list.pop(), None);
// Populate list
list.push(1);
list.push(2);
list.push(3);
// Check normal removal
assert_eq!(list.pop(), Some(3));
assert_eq!(list.pop(), Some(2));
// Push some more just to make sure nothing's corrupted
list.push(4);
list.push(5);
// Check normal removal
assert_eq!(list.pop(), Some(5));
assert_eq!(list.pop(), Some(4));
// Check exhaustion
assert_eq!(list.pop(), Some(1));
assert_eq!(list.pop(), None);
}
#[test]
fn peek() {
let mut list = List::new();
assert_eq!(list.peek(), None);
assert_eq!(list.peek_mut(), None);
list.push(1); list.push(2); list.push(3);
assert_eq!(list.peek(), Some(&3));
assert_eq!(list.peek_mut(), Some(&mut 3));
list.peek_mut().map(|value| {
*value = 42
});
assert_eq!(list.peek(), Some(&42));
assert_eq!(list.pop(), Some(42));
}
#[test]
fn into_iter() {
let mut list = List::new();
list.push(1); list.push(2); list.push(3);
let mut iter = list.into_iter();
assert_eq!(iter.next(), Some(3));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), None);
}
#[test]
fn iter() {
let mut list = List::new();
list.push(1); list.push(2); list.push(3);
let mut iter = list.iter();
assert_eq!(iter.next(), Some(&3));
assert_eq!(iter.next(), Some(&2));
assert_eq!(iter.next(), Some(&1));
}
#[test]
fn iter_mut() {
let mut list = List::new();
list.push(1); list.push(2); list.push(3);
let mut iter = list.iter_mut();
assert_eq!(iter.next(), Some(&mut 3));
assert_eq!(iter.next(), Some(&mut 2));
assert_eq!(iter.next(), Some(&mut 1));
}
}