splay/
map.rs

1use std::borrow::Borrow;
2use std::cell::UnsafeCell;
3use std::cmp::Ordering::{Less, Equal, Greater};
4use std::default::Default;
5use std::iter::{FromIterator, IntoIterator};
6use std::mem;
7use std::ops::{Index, IndexMut};
8
9use super::node::Node;
10
11/// The implementation of this splay tree is largely based on the c code at:
12///     ftp://ftp.cs.cmu.edu/usr/ftp/usr/sleator/splaying/top-down-splay.c
13/// This version of splaying is a top-down splay operation.
14pub struct SplayMap<K: Ord, V> {
15    root: UnsafeCell<Option<Box<Node<K, V>>>>,
16    size: usize,
17}
18
19pub struct IntoIter<K, V> {
20    cur: Option<Box<Node<K, V>>>,
21    remaining: usize,
22}
23
24/// Performs a top-down splay operation on a tree rooted at `node`. This will
25/// modify the pointer to contain the new root of the tree once the splay
26/// operation is done. When finished, if `key` is in the tree, it will be at the
27/// root. Otherwise the closest key to the specified key will be at the root.
28fn splay<K, V, Q: ?Sized>(key: &Q, node: &mut Box<Node<K, V>>)
29    where K: Ord + Borrow<Q>, Q: Ord
30{
31    let mut newleft = None;
32    let mut newright = None;
33
34    // Eplicitly grab a new scope so the loans on newleft/newright are
35    // terminated before we move out of them.
36    {
37        // Yes, these are backwards, that's intentional.
38        let mut l = &mut newright;
39        let mut r = &mut newleft;
40
41        loop {
42            match key.cmp(node.key.borrow()) {
43                // Found it, yay!
44                Equal => { break }
45
46                Less => {
47                    let mut left = match node.pop_left() {
48                        Some(left) => left, None => break
49                    };
50                    // rotate this node right if necessary
51                    if key.cmp(left.key.borrow()) == Less {
52                        // A bit odd, but avoids drop glue
53                        mem::swap(&mut node.left, &mut left.right);
54                        mem::swap(&mut left, node);
55                        let none = mem::replace(&mut node.right, Some(left));
56                        match mem::replace(&mut node.left, none) {
57                            Some(l) => { left = l; }
58                            None    => { break }
59                        }
60                    }
61
62                    *r = Some(mem::replace(node, left));
63                    let tmp = r;
64                    r = &mut tmp.as_mut().unwrap().left;
65                }
66
67                // If you look closely, you may have seen some similar code
68                // before
69                Greater => {
70                    match node.pop_right() {
71                        None => { break }
72                        // rotate left if necessary
73                        Some(mut right) => {
74                            if key.cmp(right.key.borrow()) == Greater {
75                                mem::swap(&mut node.right, &mut right.left);
76                                mem::swap(&mut right, node);
77                                let none = mem::replace(&mut node.left,
78                                                         Some(right));
79                                match mem::replace(&mut node.right, none) {
80                                    Some(r) => { right = r; }
81                                    None    => { break }
82                                }
83                            }
84                            *l = Some(mem::replace(node, right));
85                            let tmp = l;
86                            l = &mut tmp.as_mut().unwrap().right;
87                        }
88                    }
89                }
90            }
91        }
92
93        mem::swap(l, &mut node.left);
94        mem::swap(r, &mut node.right);
95    }
96
97    node.left = newright;
98    node.right = newleft;
99}
100
101impl<K: Ord, V> SplayMap<K, V> {
102    pub fn new() -> SplayMap<K, V> {
103        SplayMap { root: UnsafeCell::new(None), size: 0 }
104    }
105
106    /// Moves all values out of this map, transferring ownership to the given
107    /// iterator.
108    pub fn into_iter(mut self) -> IntoIter<K, V> {
109        IntoIter { cur: self.root_mut().take(), remaining: self.size }
110    }
111
112    pub fn len(&self) -> usize { self.size }
113    pub fn is_empty(&self) -> bool { self.len() == 0 }
114
115    /// Clears the tree in O(1) extra space (including the stack). This is
116    /// necessary to prevent stack exhaustion with extremely large trees.
117    pub fn clear(&mut self) {
118        let iter = IntoIter {
119            cur: self.root_mut().take(),
120            remaining: self.size,
121        };
122        for _ in iter {
123            // ignore, drop the values (and the node)
124        }
125        self.size = 0;
126    }
127
128    /// Return true if the map contains a value for the specified key
129    pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
130        where K: Borrow<Q>, Q: Ord,
131    {
132        self.get(key).is_some()
133    }
134
135    /// Return a reference to the value corresponding to the key
136    pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
137        where K: Borrow<Q>, Q: Ord,
138    {
139        // Splay trees are self-modifying, so they can't exactly operate with
140        // the immutable self given by the Map interface for this method. It can
141        // be guaranteed, however, that the callers of this method are not
142        // modifying the tree, they may just be rotating it. Each node is a
143        // pointer on the heap, so we know that none of the pointers inside
144        // these nodes (the value returned from this function) will be moving.
145        //
146        // With this in mind, we can unsafely use a mutable version of this tree
147        // to invoke the splay operation and return a pointer to the inside of
148        // one of the nodes (the pointer won't be deallocated or moved).
149        //
150        // However I'm not entirely sure whether this works with iteration or
151        // not. Arbitrary lookups can occur during iteration, and during
152        // iteration there's some form of "stack" remembering the nodes that
153        // need to get visited. I don't believe that it's safe to allow lookups
154        // while the tree is being iterated. Right now there are no iterators
155        // exposed on this splay tree implementation, and more thought would be
156        // required if there were.
157        unsafe {
158            match *self.root.get() {
159                Some(ref mut root) => {
160                    splay(key, root);
161                    if key == root.key.borrow() {
162                        return Some(&root.value);
163                    }
164                    None
165                }
166                None => None,
167            }
168        }
169    }
170
171    /// Return a mutable reference to the value corresponding to the key
172    pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
173        where K: Borrow<Q>, Q: Ord,
174    {
175        match *self.root_mut() {
176            None => { return None; }
177            Some(ref mut root) => {
178                splay(key, root);
179                if key == root.key.borrow() {
180                    return Some(&mut root.value);
181                }
182                return None;
183            }
184        }
185    }
186
187    /// Insert a key-value pair from the map. If the key already had a value
188    /// present in the map, that value is returned. Otherwise None is returned.
189    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
190        match self.root_mut() {
191            &mut Some(ref mut root) => {
192                splay(&key, root);
193
194                match key.cmp(&root.key) {
195                    Equal => {
196                        let old = mem::replace(&mut root.value, value);
197                        return Some(old);
198                    }
199                    /* TODO: would unsafety help perf here? */
200                    Less => {
201                        let left = root.pop_left();
202                        let new = Node::new(key, value, left, None);
203                        let prev = mem::replace(root, new);
204                        root.right = Some(prev);
205                    }
206                    Greater => {
207                        let right = root.pop_right();
208                        let new = Node::new(key, value, None, right);
209                        let prev = mem::replace(root, new);
210                        root.left = Some(prev);
211                    }
212                }
213            }
214            slot => {
215                *slot = Some(Node::new(key, value, None, None));
216            }
217        }
218        self.size += 1;
219        return None;
220    }
221
222    /// Removes a key from the map, returning the value at the key if the key
223    /// was previously in the map.
224    pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
225        where K: Borrow<Q>, Q: Ord
226    {
227        match *self.root_mut() {
228            None => { return None; }
229            Some(ref mut root) => {
230                splay(key, root);
231                if key != root.key.borrow() { return None }
232            }
233        }
234
235        // TODO: Extra storage of None isn't necessary
236        let (value, left, right) = match *self.root_mut().take().unwrap() {
237            Node {left, right, value, ..} => (value, left, right)
238        };
239
240        *self.root_mut() = match left {
241            None => right,
242            Some(mut node) => {
243                splay(key, &mut node);
244                node.right = right;
245                Some(node)
246            }
247        };
248
249        self.size -= 1;
250        return Some(value);
251    }
252}
253
254impl<K: Ord, V> SplayMap<K, V> {
255    // These two functions provide safe access to the root node, and they should
256    // be valid to call in virtually all contexts.
257    fn root_mut(&mut self) -> &mut Option<Box<Node<K, V>>> {
258        unsafe { &mut *self.root.get() }
259    }
260    fn root_ref(&self) -> &Option<Box<Node<K, V>>> {
261        unsafe { &*self.root.get() }
262    }
263}
264
265impl<'a, K: Ord, V, Q: ?Sized> Index<&'a Q> for SplayMap<K, V>
266    where K: Borrow<Q>, Q: Ord
267{
268    type Output = V;
269    fn index(&self, index: &'a Q) -> &V {
270        self.get(index).expect("key not present in SplayMap")
271    }
272}
273
274impl<'a, K: Ord, V, Q: ?Sized> IndexMut<&'a Q> for SplayMap<K, V>
275    where K: Borrow<Q>, Q: Ord
276{
277    fn index_mut(&mut self, index: &'a Q) -> &mut V {
278        self.get_mut(index).expect("key not present in SplayMap")
279    }
280}
281
282impl<K: Ord, V> Default for SplayMap<K, V> {
283    fn default() -> SplayMap<K, V> { SplayMap::new() }
284}
285
286impl<K: Ord, V> FromIterator<(K, V)> for SplayMap<K, V> {
287    fn from_iter<I: IntoIterator<Item=(K, V)>>(iterator: I) -> SplayMap<K, V> {
288        let mut map = SplayMap::new();
289        map.extend(iterator);
290        map
291    }
292}
293
294impl<K: Ord, V> Extend<(K, V)> for SplayMap<K, V> {
295    fn extend<I: IntoIterator<Item=(K, V)>>(&mut self, i: I) {
296        for (k, v) in i {
297            self.insert(k, v);
298        }
299    }
300}
301
302impl<K, V> Iterator for IntoIter<K, V> {
303    type Item = (K, V);
304    fn next(&mut self) -> Option<(K, V)> {
305        let mut cur = match self.cur.take() {
306            Some(cur) => cur,
307            None => return None,
308        };
309        loop {
310            match cur.pop_left() {
311                Some(node) => {
312                    let mut node = node;
313                    cur.left = node.pop_right();
314                    node.right = Some(cur);
315                    cur = node;
316                }
317
318                None => {
319                    self.cur = cur.pop_right();
320                    // left and right fields are both None
321                    let node = *cur;
322                    let Node { key, value, .. } = node;
323                    self.remaining -= 1;
324                    return Some((key, value));
325                }
326            }
327        }
328    }
329
330    fn size_hint(&self) -> (usize, Option<usize>) {
331        (self.remaining, Some(self.remaining))
332    }
333}
334
335impl<K, V> DoubleEndedIterator for IntoIter<K, V> {
336    // Pretty much the same as the above code, but with left replaced with right
337    // and vice-versa.
338    fn next_back(&mut self) -> Option<(K, V)> {
339        let mut cur = match self.cur.take() {
340            Some(cur) => cur,
341            None => return None,
342        };
343        loop {
344            match cur.pop_right() {
345                Some(node) => {
346                    let mut node = node;
347                    cur.right = node.pop_left();
348                    node.left = Some(cur);
349                    cur = node;
350                }
351
352                None => {
353                    self.cur = cur.pop_left();
354                    // left and right fields are both None
355                    let node = *cur;
356                    let Node { key, value, .. } = node;
357                    self.remaining -= 1;
358                    return Some((key, value));
359                }
360            }
361        }
362    }
363}
364
365impl<K, V> ExactSizeIterator for IntoIter<K, V> {}
366
367impl<K: Clone + Ord, V: Clone> Clone for SplayMap<K, V> {
368    fn clone(&self) -> SplayMap<K, V> {
369        SplayMap {
370            root: UnsafeCell::new(self.root_ref().clone()),
371            size: self.size,
372        }
373    }
374}
375
376impl<K: Ord, V> Drop for SplayMap<K, V> {
377    fn drop(&mut self) {
378        // Be sure to not recurse too deep on destruction
379        self.clear();
380    }
381}