From bb25cfd128b117406abbe172eb680802983a30b8 Mon Sep 17 00:00:00 2001 From: Nilstrieb Date: Sat, 7 Aug 2021 20:31:49 +0200 Subject: [PATCH] changes --- src/linked_list.rs | 54 +++++++++++++++++++++++++--------------------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/src/linked_list.rs b/src/linked_list.rs index b4404db..fbad6de 100644 --- a/src/linked_list.rs +++ b/src/linked_list.rs @@ -49,24 +49,25 @@ impl LinkedList { } } - pub fn insert_end(&mut self, element: T) {} + pub fn _insert_end(&mut self, _element: T) {} - /// Random access over the list - pub fn get(&self, index: usize) -> Option<&T> { - fn get_inner(node: Option<&NonNull>>, index: usize) -> Option<&Node> { - match node { - // SAFETY: All pointers should always be valid - Some(ptr) => match index { - 0 => unsafe { Some(ptr.as_ref()) }, - n => get_inner(unsafe { ptr.as_ref() }.next.as_ref(), n - 1), - }, - None => None, + pub fn get(&self, mut index: usize) -> Option<&T> { + let mut node = &self.start; + let mut result = None; + while let Some(content) = node { + // SAFETY: All pointers should always be valid + let content = unsafe { content.as_ref() }; + if index == 0 { + result = Some(&content.value); + break; } + index -= 1; + node = &content.next; } - get_inner(self.start.as_ref(), index).map(|n| &n.value) + result } - pub fn get_node(&self, index: usize) {} + pub fn _get_node(&self, _index: usize) {} /// Returns an iterator over the items pub fn iter(&self) -> Iter { @@ -83,6 +84,12 @@ where } } +impl Default for LinkedList { + fn default() -> Self { + Self::new() + } +} + impl Drop for LinkedList { fn drop(&mut self) { let mut item = self.start; @@ -96,6 +103,7 @@ impl Drop for LinkedList { } } +/// A Node in a `LinkedList` #[derive(Debug)] pub struct Node { value: T, @@ -105,7 +113,7 @@ pub struct Node { } fn allocate_nonnull(element: T) -> NonNull { - let mut boxed = Box::new(element); + let boxed = Box::new(element); // SAFETY: box is always non-null unsafe { NonNull::new_unchecked(Box::leak(boxed)) } } @@ -117,11 +125,10 @@ pub struct Iter<'a, T> { impl<'a, T> Iter<'a, T> { fn new(list: &'a LinkedList) -> Self { Self { - item: match list.start { + item: list.start.as_ref().map(|nn| { // SAFETY: All pointers should always be valid, the list lives as long as its items - Some(ref nn) => unsafe { Some(nn.as_ref()) }, - None => None, - }, + unsafe { nn.as_ref() } + }), } } } @@ -133,13 +140,10 @@ impl<'a, T: Debug> Iterator for Iter<'a, T> { let current = self.item; match current { Some(node) => { - self.item = match &node.next { - Some(ref nn) => { - // SAFETY: All pointers should always be valid - unsafe { Some(nn.as_ref()) } - } - None => None, - }; + self.item = node.next.as_ref().map(|nn| { + // SAFETY: All pointers should always be valid + unsafe { nn.as_ref() } + }); Some(&node.value) } None => None,