1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#[cfg(feature = "no_std")]
use std::prelude::*;

use std::cell::RefCell;

pub struct ImmutVecItem<T> {
    prev: Option<usize>,
    data: T
}
pub struct ImmutVec<'a, T> {
    inner: &'a RefCell<Vec<ImmutVecItem<T>>>,
    id: Option<usize>
}
impl<'a, T> Copy for ImmutVec<'a, T> {}
impl<'a, T> Clone for ImmutVec<'a, T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner,
            id: self.id
        }
    }
}
impl<'a, T> ImmutVec<'a, T> {
    pub fn new(inner: &'a RefCell<Vec<ImmutVecItem<T>>>) -> Self {
        Self {
            inner,
            id: None
        }
    }
    #[must_use = "push does nothing to the original vector"]
    pub fn push(self, item: T) -> Self {
        let mut inner = self.inner.borrow_mut();
        let id = inner.len();
        inner.push(ImmutVecItem {
            prev: self.id,
            data: item
        });
        Self {
            id: Some(id),
            ..self
        }
    }
}
impl<'a, T: Clone> ImmutVec<'a, T> {
    #[must_use = "pop does nothing to the original vector"]
    pub fn pop(self) -> (Self, Option<T>) {
        let inner = self.inner.borrow();
        let id = match self.id {
            None => return (self, None),
            Some(id) => id
        };
        let item = &inner[id];
        (Self {
            id: item.prev,
            ..self
        }, Some(item.data.clone()))
    }
    pub fn iter_rev(self) -> ImmutVecIter<'a, T> {
        ImmutVecIter(self)
    }
}

pub struct ImmutVecIter<'a, T: Clone>(ImmutVec<'a, T>);
impl<'a, T: Clone> Iterator for ImmutVecIter<'a, T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        let (new, item) = self.0.pop();
        self.0 = new;
        item
    }
}