linked_tail_list/
lib.rs

1//! This module implements a specialized linked list.
2//!
3//! The implemented list (from now on called a tail list) is neither a singly
4//! nor doubly linked: aside from the optional link to the next node, each node
5//! also has reference to the link which owns the node.
6//!
7//! For each tail list there is one item which currently 'owns' a node and it's
8//! tail (all the following nodes). 'Owns' in this context does not mean actual
9//! ownership in rust terms, but rather 'mutably borrows' this node (and it's)
10//! tail. This item will be referred to as the *active* item.
11//!
12//! For each node which is not owned by the currently active item, there exists
13//! at most one *passive* item, which owns a single node, but neither it's
14//! predecessors nor successors.
15//!
16//! A `TailList`, `Cursor` and `TailValRef` are active items. A `ValRef` is a
17//! passive item.
18//!
19//! An active item may temporarily transfer ownership of it's owned node to
20//! another item by creating a mutable borrow to itself.
21
22use std::cell::UnsafeCell;
23use std::marker::PhantomData;
24use std::mem;
25use std::ops::{Deref, DerefMut};
26
27////////////////////////////////////////////////////////////////////////////////
28// STRUCTS
29////////////////////////////////////////////////////////////////////////////////
30
31/// A struct actually owning its contents.
32struct Own<T>(UnsafeCell<T>); // TODO?: NonZero
33
34/// A struct only referencing its contents.
35struct Ref<T>(*mut T); // TODO: NonZero
36
37/// An actual Link to another Node.
38struct Link<T>(Option<Box<NodeOwn<T>>>);
39
40/// A Link which actually owns it's contents.
41type LinkOwn<T> = Own<Link<T>>;
42
43/// A reference to a Link.
44type LinkRef<T> = Ref<Link<T>>;
45
46/// An actual Node. Iff `val` is `None`, this is a dummy Node.
47struct Node<T> {
48    next: LinkOwn<T>,
49    owning_link: LinkRef<T>,
50    val: Option<T>,
51}
52
53/// A Node which actually owns it's contents.
54type NodeOwn<T> = Own<Node<T>>;
55
56/// A reference to a Node.
57type NodeRef<T> = Ref<Node<T>>;
58
59/// A specialized linked list (see the module documentation).
60pub struct TailList<T> {
61    head: LinkOwn<T>,
62}
63
64// Lifetimes:
65// (Only the listed lifetimes may be used and only for their intended meaning)
66//
67// 'node: The lifetime of any single node, usually the lifetime of the list
68// 'tail: The lifetime of the tail (only used for TailValRef)
69// 'slf:  Used in function calls to explicitly denote the self lifetime
70
71/// A `Cursor` is an iterator over a node and it's tail. It is an active item,
72/// which owns the next node it would return.
73///
74/// Due to the design of rust's `Iterator` trait, `Cursor` cannot implement
75/// `Iterator`.
76pub struct Cursor<'node, T: 'node> {
77    dummy: NodeRef<T>,
78    phantom: PhantomData<&'node mut Node<T>>,
79}
80
81/// A `ValRef` is a passive item, which provides mutable access to a single
82/// node.
83pub struct ValRef<'node, T: 'node> {
84    node: NodeRef<T>,
85    phantom: PhantomData<&'node Node<T>>,
86}
87
88/// A `TailValRef` is an active item, which provides mutable access to a single
89/// node and its successors.
90pub struct TailValRef<'node, 'tail, T: 'node + 'tail> {
91    val_ref: ValRef<'node, T>,
92    phantom: PhantomData<Cursor<'tail, T>>,
93}
94
95////////////////////////////////////////////////////////////////////////////////
96// IMPLS
97////////////////////////////////////////////////////////////////////////////////
98
99impl<T> Own<T> {
100    /// Returns a new `Own` struct encapsulating the given value.
101    fn new(val: T) -> Own<T> { Own(UnsafeCell::new(val)) }
102}
103
104impl<T> Link<T> {
105    /// Returns a new `Link` linking to nothing.
106    fn new() -> Link<T> { Link(None) }
107
108    /// Returns as new `Link` linking to the given node.
109    fn new_to_node(node: NodeOwn<T>) -> Link<T> {
110        Link(Some(Box::new(node)))
111    }
112
113    /// Returns an optional `NodeRef` to the linked to node, any.
114    fn opt_node_ref(&self) -> Option<NodeRef<T>> {
115        self.0.as_ref().map(|owned| owned.new_ref())
116    }
117}
118
119impl<T> Node<T> {
120    /// Returns a new node with the given `val` and `owning_link`.
121    fn new(val: Option<T>, owning_link: LinkRef<T>) -> Node<T> {
122        Node {
123            next: Own::new(Link::new()),
124            owning_link: owning_link,
125            val: val,
126        }
127    }
128}
129
130impl<T> TailList<T> {
131    /// Creates a new empty list.
132    pub fn new() -> TailList<T> {
133        TailList {
134            head: Own::new(Link::new()),
135        }
136    }
137
138    /// Pushed a new element to the front of the list.
139    pub fn push(&mut self, val: T) {
140        insert_at(&self.head, Some(val));
141    }
142
143    /// Returns a cursor over all elements in this list.
144    pub fn cursor<'node>(&'node mut self) -> Cursor<'node, T> {
145        Cursor::new(&self.head.new_ref())
146    }
147}
148
149impl<'node, T: 'node> Cursor<'node, T> {
150    /// Returns a new cursor with it's dummy node inserted after the given link.
151    fn new(at: &LinkRef<T>) -> Cursor<'node, T> {
152        Cursor {
153            dummy: insert_at(at, None),
154            phantom: PhantomData,
155        }
156    }
157
158    /// (Optionally) returns the next element of this cursor.
159    ///
160    /// This cursor is unusable as long as the `'tail` lifetime is still
161    /// referenced.
162    pub fn next<'tail>(&'tail mut self) -> Option<TailValRef<'node, 'tail, T>> {
163        // Get a reference to the next node, if there is any
164        let next_ref_opt: Option<NodeRef<T>> = self.dummy.borrow_inner().next
165            .borrow_inner().opt_node_ref();
166
167        let next_ref = match next_ref_opt {
168            Some(next_ref) => next_ref,
169            None => return None,
170        };
171
172        // Swap the places of the dummy and next nodes in the list
173        swap_places(&self.dummy, &next_ref);
174
175        // If the next node happens to be a dummy node, skip it by calling next
176        // again
177        if next_ref.borrow_inner().val.is_none() {
178            return self.next();
179        }
180
181        // Return the next node
182        Some(TailValRef {
183            val_ref: ValRef {
184                node: next_ref,
185                phantom: PhantomData,
186            },
187            phantom: PhantomData,
188        })
189    }
190}
191
192impl<'node, T: 'node> ValRef<'node, T> {
193    /// Returns a new ValRef referencing the given node.
194    fn new(node: NodeRef<T>) -> ValRef<'node, T> {
195        ValRef {
196            node: node,
197            phantom: PhantomData,
198        }
199    }
200
201    /// Inserts a new element before this element and returns a `ValRef` to the
202    /// newly inserted element.
203    pub fn insert_before(&mut self, val: T) -> ValRef<'node, T> {
204        ValRef::new(insert_at(&self.node.borrow_inner().owning_link, Some(val)))
205    }
206
207    /// Inserts a new element after this element and returns a `ValRef` to the
208    /// newly inserted element.
209    pub fn insert_after(&mut self, val: T) -> ValRef<'node, T> {
210        ValRef::new(insert_at(&self.node.borrow_inner().next, Some(val)))
211    }
212
213    /// Removes this element from the list and returns it's value.
214    pub fn remove(self) -> T {
215        let val = unlink(self.node);
216
217        if let Some(val) = val {
218            return val;
219        }
220
221        unreachable!("cannot remove dummy node")
222    }
223}
224
225impl<'node, 'tail, T: 'node + 'tail> TailValRef<'node, 'tail, T> {
226    /// Returns a reference to a `ValRef` to the first node owned by `self`, as
227    /// well as a `Cursor` owning the rest of the nodes owned by `self`.
228    ///
229    /// After both items have gone out of scope, this method may be called
230    /// again.
231    pub fn tail<'slf>(&'slf mut self) -> (&'slf ValRef<'node, T>,
232                                          Cursor<'slf, T>) {
233        let csr = Cursor::new(&self.val_ref.node.borrow_inner().next.new_ref());
234        (&self.val_ref, csr)
235    }
236
237    /// Returns a `ValRef` to the first node owned by `self, as well as a
238    /// `Cursor` owning the rest of the nodes owned by `self`.
239    ///
240    /// This method consumes `self`. The `Cursor` who returned this may be used
241    /// again after the returned cursor has gone out of scope.
242    pub fn into_tail(self) -> (ValRef<'node, T>, Cursor<'tail, T>) {
243        let csr = Cursor::new(&self.val_ref.node.borrow_inner().next.new_ref());
244        (self.val_ref, csr)
245    }
246
247    /// Turns `self` into a `ValRef` to the first node owned by `self`. The
248    /// `Cursor` who returned this may be used again after this method has been
249    /// called.
250    pub fn into_passive(self) -> ValRef<'node, T> {
251        self.val_ref
252    }
253
254    /// Inserts a new element before this element and returns a `ValRef` to the
255    /// newly inserted element.
256    pub fn insert_before(&mut self, val: T) -> ValRef<'node, T> {
257        self.val_ref.insert_before(val)
258    }
259
260    /// Inserts a new element after this element and returns a `ValRef` to the
261    /// newly inserted element.
262    pub fn insert_after(&mut self, val: T) -> ValRef<'node, T> {
263        self.val_ref.insert_after(val)
264    }
265
266    /// Removes this element from the list and returns it's value.
267    pub fn remove(self) -> T {
268        self.val_ref.remove()
269    }
270}
271
272////////////////////////////////////////////////////////////////////////////////
273// FUNCTIONS
274////////////////////////////////////////////////////////////////////////////////
275
276/// Inserts a new node into the list, directly at / after `link`.
277fn insert_at<T, L: OwnRef<Inner=Link<T>>>(link: &L, val: Option<T>) -> NodeRef<T> {
278    // Create a `NodeOwn` for the new value
279    let node = Own::new(Node::new(val, link.new_ref()));
280
281    // Move the tail of `link` to `node.next`
282    let link: &mut Link<T> = link.borrow_inner_mut();
283
284    {
285        let next: &mut Link<T> = node.borrow_inner().next.borrow_inner_mut();
286
287        mem::swap(link, next);
288    }
289
290    // Make `link` link to the new node
291    *link = Link::new_to_node(node);
292
293    // Get a reference to the newly created node
294    let node_ref = link.opt_node_ref()
295        .expect("the option was just initialized to some");
296
297    // Fix the `owning_link` of node originally linked to by `link` (which is
298    // now linked to by node.next)
299    fixup_owning_link(&node_ref.borrow_inner().next);
300
301    // Return a reference to the newly created node
302    node_ref
303}
304
305/// Swap the places of two nodes in the list
306fn swap_places<T>(a: &NodeRef<T>, b: &NodeRef<T>) {
307    // Swap the actual nodes (in the owning links)
308    let a_link = a.borrow_inner().owning_link.borrow_inner_mut();
309    let b_link = b.borrow_inner().owning_link.borrow_inner_mut();
310
311    mem::swap(a_link, b_link);
312
313    // Swap the next links
314    let a_next = a.borrow_inner().next.borrow_inner_mut();
315    let b_next = b.borrow_inner().next.borrow_inner_mut();
316
317    mem::swap(a_next, b_next);
318
319    // Fix up all owning links
320    fixup_owning_link(&a.borrow_inner().owning_link);
321    fixup_owning_link(&b.borrow_inner().owning_link);
322    fixup_owning_link(&a.borrow_inner().next);
323    fixup_owning_link(&b.borrow_inner().next);
324}
325
326/// Unlinks / removes the given node from the list and returns its optional
327/// value.
328fn unlink<T>(node_ref: NodeRef<T>) -> Option<T> {
329    // A mutable borrow of the next link of the node to remove
330    let next: &mut Link<T> = node_ref.borrow_inner().next
331        .borrow_inner_mut();
332
333    // A reference to the link owning the node to remove
334    let owning_link_ref: LinkRef<T> = node_ref.borrow_inner().owning_link
335        .clone();
336
337    // A mutable borrow of the link linking to the node to remove
338    let owning_link: &mut Link<T> = owning_link_ref.borrow_inner_mut();
339
340    // A temporary owning link
341    let tmp_link_own = Own::new(Link::new());
342
343    // Remove the node from the list
344    {
345        // A mutable borrow of the link owned by `tmp_link_own`
346        let tmp_link: &mut Link<T> = tmp_link_own.borrow_inner_mut();
347
348        // tmp -> None, owning -> This, next -> Next
349        mem::swap(tmp_link, owning_link);
350        // tmp -> This, owning -> None, next -> Next
351        mem::swap(owning_link, next);
352        // tmp -> This, owning -> Next, next -> None
353
354        fixup_owning_link(&owning_link_ref);
355    }
356
357    // Extract the value now owned by `tmp_link_own`
358    unsafe {
359        let val: NodeOwn<T> = *tmp_link_own.0.into_inner().0
360            .expect("the option was just set to some");
361
362        val.0.into_inner().val
363    }
364}
365
366/// Given a link, if this link links to a node, ensures that the node's
367/// `owning_link` points to the given link.
368fn fixup_owning_link<T, L: OwnRef<Inner=Link<T>>>(link: &L) {
369    let opt_node_ref = link.borrow_inner().opt_node_ref();
370
371    if let Some(node_ref) = opt_node_ref {
372        let node = node_ref.borrow_inner_mut();
373        node.owning_link = link.new_ref();
374    }
375}
376
377////////////////////////////////////////////////////////////////////////////////
378// TRAITS
379////////////////////////////////////////////////////////////////////////////////
380
381/// A trait abstracting over `Own` and `Ref`.
382trait OwnRef {
383    /// The type encapsulated by this `Own` or `Ref`.
384    type Inner;
385
386    /// Returns a mutable pointer to the inner value.
387    fn get_mut_ptr(&self) -> *mut Self::Inner;
388
389    /// Returns a new `Ref` to the inner value.
390    fn new_ref(&self) -> Ref<Self::Inner> {
391        Ref(self.get_mut_ptr())
392    }
393
394    /// Borrows the inner value.
395    fn borrow_inner(&self) -> &Self::Inner {
396        unsafe { & *self.get_mut_ptr() }
397    }
398
399    /// Borrows the inner value mutably.
400    fn borrow_inner_mut(&self) -> &mut Self::Inner {
401        unsafe { &mut *self.get_mut_ptr() }
402    }
403}
404
405////////////////////////////////////////////////////////////////////////////////
406// TRAIT IMPLS
407////////////////////////////////////////////////////////////////////////////////
408
409impl<T> OwnRef for Own<T> {
410    type Inner = T;
411
412    fn get_mut_ptr(&self) -> *mut T { self.0.get() }
413}
414
415impl<T> OwnRef for Ref<T> {
416    type Inner = T;
417
418    fn get_mut_ptr(&self) -> *mut T { self.0 }
419}
420
421impl<T> Clone for Ref<T> {
422    fn clone(&self) -> Ref<T> {
423        Ref(self.0)
424    }
425}
426
427impl <'node, T: 'node> Drop for Cursor<'node, T> {
428    fn drop(&mut self) {
429        unlink(self.dummy.clone());
430    }
431}
432
433impl<'node, T: 'node> Deref for ValRef<'node, T> {
434    type Target = T;
435
436    fn deref(&self) -> &T {
437        if let Some(ref val) = self.node.borrow_inner().val {
438            return val;
439        }
440
441        unreachable!("cannot deref dummy node");
442    }
443}
444
445impl<'node, T: 'node> DerefMut for ValRef<'node, T> {
446    fn deref_mut(&mut self) -> &mut T {
447        if let Some(ref mut val) = self.node.borrow_inner_mut().val {
448            return val;
449        }
450
451        unreachable!("cannot deref dummy node");
452    }
453}
454
455impl<'node, 'tail, T: 'node + 'tail> Deref for TailValRef<'node, 'tail, T> {
456    type Target = T;
457
458    fn deref(&self) -> &T {
459        self.val_ref.deref()
460    }
461}
462
463impl<'node, 'tail, T: 'node + 'tail> DerefMut for TailValRef<'node, 'tail, T> {
464    fn deref_mut(&mut self) -> &mut T {
465        self.val_ref.deref_mut()
466    }
467}
468
469#[cfg(test)]
470mod tests {
471    include!( "./lib_tests.rs");
472}