fwdlist/ops/
access.rs

1use crate::List;
2
3/// Some accessors to front/back elements.
4impl<T> List<T> {
5    /// Returns a reference to the first element in the list.
6    pub fn front(&self) -> Option<&T> {
7        self.head.as_ref().map(|node| &node.value)
8    }
9
10    /// Returns a mutable reference to the first element in the list.
11    pub fn front_mut(&mut self) -> Option<&mut T> {
12        self.head.as_mut().map(|node| &mut node.value)
13    }
14
15    /// Returns a reference to the last element in the list.
16    pub fn back(&self) -> Option<&T> {
17        let mut head_link = &self.head;
18        while let Some(ref node) = *head_link {
19            if node.next.is_none() {
20                return Some(&node.value);
21            }
22            head_link = &node.next;
23        }
24        None
25    }
26
27    /// Returns a mutable reference to the last element in the list.
28    pub fn back_mut(&mut self) -> Option<&mut T> {
29        self.penultimate_link()
30            .and_then(|link| link.as_mut().map(|node| &mut node.value))
31    }
32}