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
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

use std::cmp::Ordering;
use std::hash::{Hasher, Hash};
use std::iter::FromIterator;
use std::fmt::Display;
use sequence::list;
use List;

// TODO Use impl trait for return value when available
pub type Iter<'a, T> = list::Iter<'a, T>;

/// Creates a [`Stack`](stack/struct.Stack.html) containing the given arguments:
///
/// ```
/// # use rpds::*;
/// #
/// let s = Stack::new()
///     .push(1)
///     .push(2)
///     .push(3);
///
/// assert_eq!(stack![1, 2, 3], s);
/// ```
#[macro_export]
macro_rules! stack {
    ($($e:expr),*) => {
        {
            #[allow(unused_mut)]
            let mut s = $crate::Stack::new();
            $(
                s = s.push($e);
            )*
            s
        }
    };
}

/// A persistent stack with structural sharing.  This data structure supports fast `push()`,
/// `pop()`, and `peek()`.
///
/// # Complexity
///
/// Let *n* be the number of elements in the stack.
///
/// ## Temporal complexity
///
/// | Operation         | Best case | Average | Worst case  |
/// |:----------------- | ---------:| -------:| -----------:|
/// | `new()`           |      Θ(1) |    Θ(1) |        Θ(1) |
/// | `push()`          |      Θ(1) |    Θ(1) |        Θ(1) |
/// | `pop()`           |      Θ(1) |    Θ(1) |        Θ(1) |
/// | `peek()`          |      Θ(1) |    Θ(1) |        Θ(1) |
/// | `size()`          |      Θ(1) |    Θ(1) |        Θ(1) |
/// | `clone()`         |      Θ(1) |    Θ(1) |        Θ(1) |
/// | iterator creation |      Θ(1) |    Θ(1) |        Θ(1) |
/// | iterator step     |      Θ(1) |    Θ(1) |        Θ(1) |
/// | iterator full     |      Θ(n) |    Θ(n) |        Θ(n) |
///
/// # Implementation details
///
/// This is a thin wrapper around a [`List`](../sequence/list/struct.List.html).
#[derive(Debug)]
pub struct Stack<T> {
    list: List<T>
}

impl<T> Stack<T> {
    pub fn new() -> Stack<T> {
        Stack {
            list: List::new()
        }
    }

    pub fn peek(&self) -> Option<&T> {
        self.list.first()
    }

    pub fn pop(&self) -> Option<Stack<T>> {
        self.list.drop_first().map(|l| Stack { list: l } )
    }

    pub fn push(&self, v: T) -> Stack<T> {
        Stack {
            list: self.list.push_front(v)
        }
    }

    #[inline]
    pub fn size(&self) -> usize {
        self.list.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.size() == 0
    }

    pub fn iter(&self) -> Iter<T> {
        self.list.iter()
    }
}

impl<T> Default for Stack<T> {
    fn default() -> Stack<T> {
        Stack::new()
    }
}

impl<T: PartialEq> PartialEq for Stack<T> {
    fn eq(&self, other: &Stack<T>) -> bool {
        self.list.eq(&other.list)
    }
}

impl<T: Eq> Eq for Stack<T> {}

impl<T: PartialOrd<T>> PartialOrd<Stack<T>> for Stack<T> {
    fn partial_cmp(&self, other: &Stack<T>) -> Option<Ordering> {
        self.list.partial_cmp(&other.list)
    }
}

impl<T: Ord> Ord for Stack<T> {
    fn cmp(&self, other: &Stack<T>) -> Ordering {
        self.list.cmp(&other.list)
    }
}

impl<T: Hash> Hash for Stack<T> {
    fn hash<H: Hasher>(&self, state: &mut H) -> () {
        self.list.hash(state)
    }
}

impl<T> Clone for Stack<T> {
    fn clone(&self) -> Stack<T> {
        Stack {
            list: List::clone(&self.list)
        }
    }
}

impl<T: Display> Display for Stack<T> {
    fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        let mut first = true;

        fmt.write_str("Stack(")?;

        for v in self.iter() {
            if !first {
                fmt.write_str(", ")?;
            }
            v.fmt(fmt)?;
            first = false;
        }

        fmt.write_str(")")
    }
}

impl<'a, T> IntoIterator for &'a Stack<T> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Iter<'a, T> {
        self.list.iter()
    }
}

impl<T> FromIterator<T> for Stack<T> {
    fn from_iter<I: IntoIterator<Item = T>>(into_iter: I) -> Stack<T> {
        Stack {
            list: List::from_iter(into_iter)
        }
    }
}

#[cfg(feature = "serde")]
pub mod serde {
    use super::*;
    use serde::ser::{Serialize, Serializer};
    use serde::de::{Deserialize, Deserializer};

    impl<T> Serialize for Stack<T>
        where T: Serialize {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.collect_seq(self)
        }
    }

    impl<'de, T> Deserialize<'de> for Stack<T>
        where T: Deserialize<'de> {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Stack<T>, D::Error> {
            let list: List<T> = Deserialize::deserialize(deserializer)?;
            Ok(Stack {
                list: list,
            })
        }
    }
}

#[cfg(test)]
mod test;