├── .github └── workflows │ └── ci.yml ├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE ├── README.md ├── benches └── bench.rs ├── examples └── set_random_insert.rs ├── src ├── heap.rs ├── iter.rs ├── lib.rs ├── map.rs ├── set.rs ├── tree_core.rs └── vec_like.rs └── tests └── lib.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push] 4 | 5 | jobs: 6 | check: 7 | name: Check 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | toolchain: [stable, beta, nightly] 12 | steps: 13 | - name: Checkout sources 14 | uses: actions/checkout@v2 15 | 16 | - name: Install ${{ matrix.toolchain }} toolchain 17 | uses: actions-rs/toolchain@v1 18 | with: 19 | profile: minimal 20 | toolchain: ${{ matrix.toolchain }} 21 | override: true 22 | 23 | - name: Run cargo check 24 | uses: actions-rs/cargo@v1 25 | with: 26 | command: check 27 | args: --workspace 28 | 29 | lints: 30 | name: Lints 31 | runs-on: ubuntu-latest 32 | strategy: 33 | matrix: 34 | toolchain: [stable, beta, nightly] 35 | steps: 36 | - name: Checkout sources 37 | uses: actions/checkout@v2 38 | 39 | - name: Install ${{ matrix.toolchain }} toolchain 40 | uses: actions-rs/toolchain@v1 41 | with: 42 | profile: minimal 43 | toolchain: ${{ matrix.toolchain }} 44 | override: true 45 | components: rustfmt, clippy 46 | 47 | - name: Run cargo fmt 48 | uses: actions-rs/cargo@v1 49 | with: 50 | command: fmt 51 | args: --all -- --check 52 | 53 | - name: Run cargo clippy 54 | uses: actions-rs/cargo@v1 55 | with: 56 | command: clippy 57 | args: --workspace -- -D warnings 58 | 59 | test: 60 | name: Test Suite 61 | runs-on: ubuntu-latest 62 | strategy: 63 | matrix: 64 | toolchain: [stable, beta, nightly] 65 | steps: 66 | - name: Checkout sources 67 | uses: actions/checkout@v2 68 | 69 | - name: Install ${{ matrix.toolchain }} toolchain 70 | uses: actions-rs/toolchain@v1 71 | with: 72 | profile: minimal 73 | toolchain: ${{ matrix.toolchain }} 74 | override: true 75 | 76 | - name: Run cargo test 77 | uses: actions-rs/cargo@v1 78 | with: 79 | command: test 80 | args: --all 81 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: required 3 | rust: 4 | - stable 5 | - beta 6 | - nightly 7 | matrix: 8 | allow_failures: 9 | - rust: nightly 10 | 11 | env: 12 | global: 13 | - RUSTFLAGS="-C link-dead-code" 14 | 15 | addons: 16 | apt: 17 | packages: 18 | - libcurl4-openssl-dev 19 | - libelf-dev 20 | - libdw-dev 21 | - cmake 22 | - gcc 23 | - binutils-dev 24 | - libiberty-dev 25 | 26 | after_success: | 27 | wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && 28 | tar xzf master.tar.gz && 29 | cd kcov-master && 30 | mkdir build && 31 | cd build && 32 | cmake .. && 33 | make && 34 | make install DESTDIR=../../kcov-build && 35 | cd ../.. && 36 | rm -rf kcov-master && 37 | for file in target/debug/{splay_tree,lib}-*[^\.d]; do mkdir -p "target/cov/$(basename $file)"; ./kcov-build/usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; done && 38 | bash <(curl -s https://codecov.io/bash) && 39 | echo "Uploaded code coverage" 40 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "splay_tree" 3 | version = "0.3.1" 4 | authors = ["Takeru Ohta "] 5 | description = "Splay Tree based Data Structures (map, set, heap)" 6 | homepage = "https://github.com/sile/splay_tree" 7 | repository = "https://github.com/sile/splay_tree" 8 | readme = "README.md" 9 | categories = ["data-structures", "no-std"] 10 | license = "MIT" 11 | edition = "2021" 12 | 13 | [badges] 14 | travis-ci = {repository = "sile/splay_tree"} 15 | codecov = {repository = "sile/splay_tree"} 16 | 17 | [dependencies] 18 | serde = { version = "1", optional = true, default-features = false, features = ["alloc", "derive"] } 19 | 20 | [dev-dependencies] 21 | rand = "0.8" 22 | serde_json = { version = "1" } 23 | 24 | [features] 25 | std = [] 26 | default = [ "std" ] 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License 2 | 3 | Copyright (c) 2016 Takeru Ohta 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | splay_tree 2 | ========== 3 | 4 | [![](https://img.shields.io/crates/v/splay_tree.svg)](https://crates.io/crates/splay_tree) 5 | [![Documentation](https://docs.rs/splay_tree/badge.svg)](https://docs.rs/splay_tree) 6 | [![Build Status](https://travis-ci.org/sile/splay_tree.svg?branch=master)](https://travis-ci.org/sile/splay_tree) 7 | [![Code Coverage](https://codecov.io/gh/sile/splay_tree/branch/master/graph/badge.svg)](https://codecov.io/gh/sile/splay_tree/branch/master) 8 | [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) 9 | 10 | `splay_tree` provides data structures such as map, set and heap which are based on an in-place top-down splay tree. 11 | 12 | > A splay tree is a self-adjusting binary search tree with 13 | > the additional property that recently accessed elements are quick to access again. 14 | > It performs basic operations such as insertion, look-up and removal in O(log n) amortized time. - [Splay tree (Wikipedia)](https://en.wikipedia.org/wiki/Splay_tree) 15 | 16 | Documentation 17 | ------------- 18 | 19 | See [RustDoc Documentation](https://docs.rs/splay_tree/). 20 | 21 | The documentation includes some examples. 22 | 23 | 24 | Installation 25 | ------------ 26 | 27 | Add following lines to your `Cargo.toml`: 28 | 29 | ```toml 30 | [dependencies] 31 | splay_tree = "0.2" 32 | ``` 33 | 34 | 35 | Reference 36 | --------- 37 | 38 | - https://en.wikipedia.org/wiki/Splay_tree 39 | - http://digital.cs.usu.edu/~allan/DS/Notes/Ch22.pdf 40 | 41 | 42 | License 43 | ------- 44 | 45 | This library is released under the MIT License. 46 | 47 | See the [LICENSE](LICENSE) file for full license information. 48 | -------------------------------------------------------------------------------- /benches/bench.rs: -------------------------------------------------------------------------------- 1 | #![feature(test)] 2 | 3 | use splay_tree::SplayMap; 4 | 5 | const SMALL: u32 = 10; 6 | const MEDIUM: u32 = 100; 7 | const BIG: u32 = 1000; 8 | const HUGE: u32 = 10_000_000; 9 | 10 | fn insert_splay(b: &mut test::Bencher, num: u32) { 11 | let mut map = SplayMap::new(); 12 | for i in 0..num { 13 | map.insert(i, i); 14 | } 15 | let mut j = num + 1; 16 | b.iter(|| { 17 | j += 1; 18 | map.insert(j, j); 19 | }) 20 | } 21 | 22 | fn get_middle_splay(b: &mut test::Bencher, num: u32) { 23 | let mut map = SplayMap::new(); 24 | for i in 0..num { 25 | map.insert(i, i); 26 | } 27 | let middle = num / 2; 28 | b.iter(|| { 29 | test::black_box(map.get(&middle)); 30 | }) 31 | } 32 | 33 | fn get_none_splay(b: &mut test::Bencher, num: u32) { 34 | let mut map = SplayMap::new(); 35 | for i in 0..num { 36 | map.insert(i, i); 37 | } 38 | let none = num + 1; 39 | b.iter(|| { 40 | test::black_box(map.get(&none)); 41 | }) 42 | } 43 | 44 | #[bench] 45 | fn bench_insert_splay_small(b: &mut test::Bencher) { 46 | insert_splay(b, SMALL); 47 | } 48 | #[bench] 49 | fn bench_insert_splay_medium(b: &mut test::Bencher) { 50 | insert_splay(b, MEDIUM); 51 | } 52 | #[bench] 53 | fn bench_insert_splay_big(b: &mut test::Bencher) { 54 | insert_splay(b, BIG); 55 | } 56 | #[bench] 57 | fn bench_insert_splay_huge(b: &mut test::Bencher) { 58 | insert_splay(b, HUGE); 59 | } 60 | 61 | #[bench] 62 | fn bench_get_none_splay_small(b: &mut test::Bencher) { 63 | get_none_splay(b, SMALL); 64 | } 65 | #[bench] 66 | fn bench_get_none_splay_medium(b: &mut test::Bencher) { 67 | get_none_splay(b, MEDIUM); 68 | } 69 | #[bench] 70 | fn bench_get_none_splay_big(b: &mut test::Bencher) { 71 | get_none_splay(b, BIG); 72 | } 73 | #[bench] 74 | fn bench_get_none_splay_huge(b: &mut test::Bencher) { 75 | get_none_splay(b, HUGE); 76 | } 77 | -------------------------------------------------------------------------------- /examples/set_random_insert.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut set = splay_tree::SplaySet::new(); 3 | for _ in 0..1_000_000 { 4 | set.insert(rand::random::()); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /src/heap.rs: -------------------------------------------------------------------------------- 1 | //! A priority queue implemented with a splay tree. 2 | use crate::iter; 3 | use crate::tree_core; 4 | use std::cmp; 5 | 6 | /// `SplayHeap` iterator. 7 | pub struct Iter<'a, T: 'a> { 8 | iter: iter::Iter<'a, Item, ()>, 9 | } 10 | impl<'a, T: 'a> Iter<'a, T> { 11 | fn new(tree: &'a tree_core::Tree, ()>) -> Self { 12 | Iter { iter: tree.iter() } 13 | } 14 | } 15 | impl<'a, T: 'a> Iterator for Iter<'a, T> { 16 | type Item = &'a T; 17 | fn next(&mut self) -> Option { 18 | self.iter.next().map(|(i, _)| &i.0) 19 | } 20 | } 21 | 22 | /// An iterator that moves out of a `SplayHeap`. 23 | pub struct IntoIter(iter::IntoIter, ()>); 24 | impl Iterator for IntoIter { 25 | type Item = T; 26 | fn next(&mut self) -> Option { 27 | self.0.next().map(|(k, _)| k.0) 28 | } 29 | } 30 | 31 | #[derive(Debug, Clone, PartialEq, Eq)] 32 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] 33 | struct Item(T, u64); 34 | 35 | impl PartialOrd for Item 36 | where 37 | T: PartialOrd, 38 | { 39 | fn partial_cmp(&self, other: &Self) -> Option { 40 | self.0.partial_cmp(&other.0).map(|order| match order { 41 | cmp::Ordering::Equal => self.1.cmp(&other.1), 42 | cmp::Ordering::Less => cmp::Ordering::Greater, 43 | cmp::Ordering::Greater => cmp::Ordering::Less, 44 | }) 45 | } 46 | } 47 | 48 | impl Ord for Item 49 | where 50 | T: Ord, 51 | { 52 | fn cmp(&self, other: &Self) -> cmp::Ordering { 53 | match self.0.cmp(&other.0) { 54 | cmp::Ordering::Equal => self.1.cmp(&other.1), 55 | cmp::Ordering::Less => cmp::Ordering::Greater, 56 | cmp::Ordering::Greater => cmp::Ordering::Less, 57 | } 58 | } 59 | } 60 | 61 | /// A priority queue implemented with a splay tree. 62 | /// 63 | /// This will be a max-heap. 64 | /// 65 | /// A splay tree based heap is a self-adjusting data structure. 66 | /// It performs pushing and popping in `O(log n)` amortized time. 67 | /// 68 | /// It is a logic error for a key to be modified in such a way that 69 | /// the key's ordering relative to any other key, 70 | /// as determined by the `Ord` trait, changes while it is in the map. 71 | /// This is normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code. 72 | /// 73 | /// # Examples 74 | /// ``` 75 | /// use splay_tree::SplayHeap; 76 | /// 77 | /// let mut heap = SplayHeap::new(); 78 | /// 79 | /// heap.push(0); 80 | /// heap.push(10); 81 | /// heap.push(7); 82 | /// 83 | /// assert_eq!(heap.peek(), Some(&10)); 84 | /// assert_eq!(heap.pop(), Some(10)); 85 | /// assert_eq!(heap.pop(), Some(7)); 86 | /// assert_eq!(heap.pop(), Some(0)); 87 | /// assert_eq!(heap.pop(), None); 88 | /// ``` 89 | #[derive(Debug, Clone)] 90 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] 91 | pub struct SplayHeap { 92 | tree: tree_core::Tree, ()>, 93 | seq: u64, 94 | } 95 | impl SplayHeap 96 | where 97 | T: Ord, 98 | { 99 | /// Creates an empty `SplayHeap` as a max-heap. 100 | /// 101 | /// # Examples 102 | /// ``` 103 | /// use splay_tree::SplayHeap; 104 | /// let mut heap = SplayHeap::new(); 105 | /// 106 | /// heap.push(10); 107 | /// assert_eq!(heap.pop(), Some(10)); 108 | /// ``` 109 | pub fn new() -> Self { 110 | SplayHeap { 111 | tree: tree_core::Tree::new(), 112 | seq: 0, 113 | } 114 | } 115 | 116 | /// Returns the greatest item in the heap, or `None` if it is empty. 117 | /// 118 | /// # NOTICE 119 | /// Because `SplayHeap` is a self-adjusting amortized data structure, 120 | /// this function requires the `mut` qualifier. 121 | /// 122 | /// # Examples 123 | /// ``` 124 | /// use splay_tree::SplayHeap; 125 | /// let mut heap = SplayHeap::new(); 126 | /// assert_eq!(heap.peek(), None); 127 | /// 128 | /// heap.push(1); 129 | /// heap.push(5); 130 | /// heap.push(2); 131 | /// assert_eq!(heap.peek(), Some(&5)); 132 | /// ``` 133 | pub fn peek(&mut self) -> Option<&T> { 134 | self.tree.get_lftmost().map(|(i, _)| &i.0) 135 | } 136 | 137 | /// Immutable version of [`SplayHeap::peek()`]. 138 | /// 139 | /// Note that this method could be less efficient than the mutable version. 140 | /// 141 | /// # Examples 142 | /// ``` 143 | /// use splay_tree::SplayHeap; 144 | /// let mut heap = SplayHeap::new(); 145 | /// assert_eq!(heap.peek_immut(), None); 146 | /// 147 | /// heap.push(1); 148 | /// heap.push(5); 149 | /// heap.push(2); 150 | /// assert_eq!(heap.peek_immut(), Some(&5)); 151 | /// ``` 152 | pub fn peek_immut(&self) -> Option<&T> { 153 | self.tree.get_lftmost_immut().map(|(i, _)| &i.0) 154 | } 155 | 156 | /// Removes the greatest item from the heap and returns it, or `None` if it is empty. 157 | /// 158 | /// # Examples 159 | /// ``` 160 | /// use splay_tree::SplayHeap; 161 | /// let mut heap: SplayHeap<_> = vec![1, 3].into_iter().collect(); 162 | /// 163 | /// assert_eq!(heap.pop(), Some(3)); 164 | /// assert_eq!(heap.pop(), Some(1)); 165 | /// assert_eq!(heap.pop(), None); 166 | /// ``` 167 | pub fn pop(&mut self) -> Option { 168 | self.tree.take_lftmost().map(|(i, _)| i.0) 169 | } 170 | 171 | /// Pushes an item onto the heap. 172 | /// 173 | /// # Examples 174 | /// ``` 175 | /// use splay_tree::SplayHeap; 176 | /// let mut heap = SplayHeap::new(); 177 | /// heap.push(3); 178 | /// heap.push(5); 179 | /// heap.push(1); 180 | /// 181 | /// assert_eq!(heap.len(), 3); 182 | /// assert_eq!(heap.peek(), Some(&5)); 183 | /// ``` 184 | pub fn push(&mut self, item: T) { 185 | let seq = self.seq; 186 | self.seq = seq.wrapping_add(1); 187 | self.tree.insert(Item(item, seq), ()); 188 | } 189 | 190 | /// Drops all items from the heap. 191 | /// 192 | /// # Examples 193 | /// ``` 194 | /// use splay_tree::SplayHeap; 195 | /// let mut heap: SplayHeap<_> = vec![1, 3].into_iter().collect(); 196 | /// 197 | /// assert!(!heap.is_empty()); 198 | /// heap.clear(); 199 | /// assert!(heap.is_empty()); 200 | /// ``` 201 | pub fn clear(&mut self) { 202 | self.tree = tree_core::Tree::new(); 203 | } 204 | } 205 | impl SplayHeap { 206 | /// Returns an iterator visiting all items in sorted (descending) order. 207 | /// 208 | /// # Examples 209 | /// ``` 210 | /// use splay_tree::SplayHeap; 211 | /// let heap: SplayHeap<_> = vec![1, 4, 2, 3].into_iter().collect(); 212 | /// 213 | /// // Print all values in `heap` in sorted order 214 | /// for x in heap.iter() { 215 | /// println!("{}", x); 216 | /// } 217 | /// ``` 218 | pub fn iter(&self) -> Iter { 219 | Iter::new(&self.tree) 220 | } 221 | 222 | /// Returns the length of the heap. 223 | /// 224 | /// # Examples 225 | /// ``` 226 | /// use splay_tree::SplayHeap; 227 | /// let heap: SplayHeap<_> = vec![1, 3].into_iter().collect(); 228 | /// 229 | /// assert_eq!(heap.len(), 2); 230 | /// ``` 231 | pub fn len(&self) -> usize { 232 | self.tree.len() 233 | } 234 | 235 | /// Checkes if the heap is empty. 236 | /// 237 | /// # Examples 238 | /// ``` 239 | /// use splay_tree::SplayHeap; 240 | /// let mut heap = SplayHeap::new(); 241 | /// 242 | /// assert!(heap.is_empty()); 243 | /// 244 | /// heap.push(1); 245 | /// assert!(!heap.is_empty()); 246 | /// 247 | /// heap.pop(); 248 | /// assert!(heap.is_empty()); 249 | /// ``` 250 | pub fn is_empty(&self) -> bool { 251 | self.len() == 0 252 | } 253 | } 254 | impl Default for SplayHeap 255 | where 256 | T: Ord, 257 | { 258 | fn default() -> Self { 259 | SplayHeap::new() 260 | } 261 | } 262 | impl std::iter::FromIterator for SplayHeap 263 | where 264 | T: Ord, 265 | { 266 | fn from_iter(iter: I) -> Self 267 | where 268 | I: IntoIterator, 269 | { 270 | let mut heap = SplayHeap::new(); 271 | for x in iter { 272 | heap.push(x); 273 | } 274 | heap 275 | } 276 | } 277 | impl IntoIterator for SplayHeap { 278 | type Item = T; 279 | type IntoIter = IntoIter; 280 | fn into_iter(self) -> Self::IntoIter { 281 | IntoIter(self.tree.into_iter()) 282 | } 283 | } 284 | impl<'a, T> IntoIterator for &'a SplayHeap { 285 | type Item = &'a T; 286 | type IntoIter = Iter<'a, T>; 287 | fn into_iter(self) -> Self::IntoIter { 288 | self.iter() 289 | } 290 | } 291 | impl Extend for SplayHeap 292 | where 293 | T: Ord, 294 | { 295 | fn extend(&mut self, iter: I) 296 | where 297 | I: IntoIterator, 298 | { 299 | for x in iter { 300 | self.push(x); 301 | } 302 | } 303 | } 304 | impl<'a, T> Extend<&'a T> for SplayHeap 305 | where 306 | T: Copy + 'a + Ord, 307 | { 308 | fn extend(&mut self, iter: I) 309 | where 310 | I: IntoIterator, 311 | { 312 | for x in iter { 313 | self.push(*x); 314 | } 315 | } 316 | } 317 | -------------------------------------------------------------------------------- /src/iter.rs: -------------------------------------------------------------------------------- 1 | //! Iterators for splay tree 2 | use crate::tree_core::Node; 3 | use crate::tree_core::NodeIndex; 4 | use std::mem; 5 | use std::vec::Vec; 6 | 7 | pub type MaybeNodeIndex = Option; 8 | 9 | pub trait Nodes { 10 | type Entry; 11 | fn get_node(&mut self, index: NodeIndex) -> (Self::Entry, MaybeNodeIndex, MaybeNodeIndex); 12 | } 13 | 14 | enum Visit { 15 | Elem(E), 16 | Node(NodeIndex), 17 | } 18 | 19 | pub struct InOrderIter 20 | where 21 | N: Nodes, 22 | { 23 | nodes: N, 24 | stack: Vec>, 25 | } 26 | impl InOrderIter 27 | where 28 | N: Nodes, 29 | { 30 | pub fn new(root: MaybeNodeIndex, nodes: N) -> Self { 31 | InOrderIter { 32 | nodes, 33 | stack: root.map(Visit::Node).into_iter().collect(), 34 | } 35 | } 36 | } 37 | impl Iterator for InOrderIter 38 | where 39 | N: Nodes, 40 | { 41 | type Item = N::Entry; 42 | fn next(&mut self) -> Option { 43 | while let Some(v) = self.stack.pop() { 44 | match v { 45 | Visit::Node(n) => { 46 | let (e, lft, rgt) = self.nodes.get_node(n); 47 | if let Some(rgt) = rgt { 48 | self.stack.push(Visit::Node(rgt)) 49 | } 50 | self.stack.push(Visit::Elem(e)); 51 | if let Some(lft) = lft { 52 | self.stack.push(Visit::Node(lft)) 53 | } 54 | } 55 | Visit::Elem(e) => { 56 | return Some(e); 57 | } 58 | } 59 | } 60 | None 61 | } 62 | } 63 | 64 | pub type Iter<'a, K, V> = InOrderIter<&'a [Node]>; 65 | impl<'a, K: 'a, V: 'a> Nodes for &'a [Node] { 66 | type Entry = (&'a K, &'a V); 67 | fn get_node(&mut self, index: NodeIndex) -> (Self::Entry, MaybeNodeIndex, MaybeNodeIndex) { 68 | let n = unsafe { self.get_unchecked(index as usize) }; 69 | (n.into(), n.lft(), n.rgt()) 70 | } 71 | } 72 | 73 | pub type IterMut<'a, K, V> = InOrderIter<&'a mut [Node]>; 74 | impl<'a, K: 'a, V: 'a> Nodes for &'a mut [Node] { 75 | type Entry = (&'a K, &'a mut V); 76 | fn get_node(&mut self, index: NodeIndex) -> (Self::Entry, MaybeNodeIndex, MaybeNodeIndex) { 77 | let n = unsafe { self.get_unchecked_mut(index as usize) }; 78 | let (lft, rgt) = (n.lft(), n.rgt()); 79 | let n = unsafe { &mut *(n as *mut _) as &mut Node<_, _> }; 80 | (n.into(), lft, rgt) 81 | } 82 | } 83 | 84 | pub type IntoIter = InOrderIter>; 85 | pub struct OwnedNodes(pub(crate) Vec>>); 86 | impl Nodes for OwnedNodes { 87 | type Entry = (K, V); 88 | fn get_node(&mut self, index: NodeIndex) -> (Self::Entry, MaybeNodeIndex, MaybeNodeIndex) { 89 | let n = mem::take(self.0.get_mut(index as usize).expect("bug")).expect("bug"); 90 | let (lft, rgt) = (n.lft(), n.rgt()); 91 | (n.into(), lft, rgt) 92 | } 93 | } 94 | impl Drop for OwnedNodes { 95 | fn drop(&mut self) { 96 | let is_sentinel = |n: &Node<_, _>| n.lft().is_some() && n.lft() == n.rgt(); 97 | for e in self.0.drain(..).flatten() { 98 | if is_sentinel(&e) { 99 | mem::forget(e); 100 | } 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Splay tree based data structures 2 | #![cfg_attr(not(feature = "std"), no_std)] 3 | #![cfg_attr(not(feature = "std"), feature(alloc))] 4 | #![warn(missing_docs)] 5 | 6 | #[cfg(feature = "serde")] 7 | #[macro_use] 8 | extern crate serde; 9 | 10 | #[cfg(not(feature = "std"))] 11 | #[macro_use] 12 | pub extern crate alloc; 13 | 14 | #[cfg(not(feature = "std"))] 15 | mod std { 16 | pub use alloc::*; 17 | pub use core::{borrow, cmp, fmt, hash, iter, mem, ops, slice, u32}; 18 | } 19 | 20 | pub mod heap; 21 | mod iter; 22 | pub mod map; 23 | pub mod set; 24 | mod tree_core; 25 | mod vec_like; 26 | 27 | #[doc(inline)] 28 | pub use map::SplayMap; 29 | 30 | #[doc(inline)] 31 | pub use set::SplaySet; 32 | 33 | #[doc(inline)] 34 | pub use heap::SplayHeap; 35 | -------------------------------------------------------------------------------- /src/map.rs: -------------------------------------------------------------------------------- 1 | //! A map based on a splay tree. 2 | use crate::iter; 3 | use crate::tree_core; 4 | use std::borrow::Borrow; 5 | use std::mem; 6 | 7 | /// A map based on a splay tree. 8 | /// 9 | /// A splay tree based map is a self-adjusting data structure. 10 | /// It performs insertion, removal and look-up in `O(log n)` amortized time. 11 | /// 12 | /// It is a logic error for a key to be modified in such a way that 13 | /// the key's ordering relative to any other key, 14 | /// as determined by the `Ord` trait, changes while it is in the map. 15 | /// This is normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code. 16 | /// 17 | /// # Examples 18 | /// ``` 19 | /// use splay_tree::SplayMap; 20 | /// 21 | /// let mut map = SplayMap::new(); 22 | /// 23 | /// map.insert("foo", 1); 24 | /// map.insert("bar", 2); 25 | /// map.insert("baz", 3); 26 | /// 27 | /// assert_eq!(map.get("foo"), Some(&1)); 28 | /// assert_eq!(map.remove("foo"), Some(1)); 29 | /// assert_eq!(map.get("foo"), None); 30 | /// 31 | /// for (k, v) in &map { 32 | /// println!("{}: {}", k, v); 33 | /// } 34 | /// ``` 35 | /// 36 | /// `SplayMap` implements an [Entry API](#method.entry) which allows for 37 | /// more complex methods of getting, setting, updating and removing keys and their values: 38 | /// ``` 39 | /// use splay_tree::SplayMap; 40 | /// 41 | /// # fn main() { 42 | /// let mut count = SplayMap::new(); 43 | /// for _ in 0..1000 { 44 | /// let k = rand::random::(); 45 | /// *count.entry(k).or_insert(0) += 1; 46 | /// } 47 | /// for k in 0..=255 { 48 | /// println!("{}: {}", k, count.get(&k).unwrap_or(&0)); 49 | /// } 50 | /// # } 51 | /// ``` 52 | #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] 53 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] 54 | pub struct SplayMap { 55 | tree: tree_core::Tree, 56 | } 57 | impl SplayMap 58 | where 59 | K: Ord, 60 | { 61 | /// Makes a new empty `SplayMap`. 62 | /// 63 | /// # Examples 64 | /// ``` 65 | /// use splay_tree::SplayMap; 66 | /// 67 | /// let mut map = SplayMap::new(); 68 | /// map.insert("foo", 1); 69 | /// assert_eq!(map.len(), 1); 70 | /// ``` 71 | pub fn new() -> Self { 72 | SplayMap { 73 | tree: tree_core::Tree::new(), 74 | } 75 | } 76 | 77 | /// Clears the map, removing all values. 78 | /// 79 | /// # Examples 80 | /// ``` 81 | /// use splay_tree::SplayMap; 82 | /// 83 | /// let mut map = SplayMap::new(); 84 | /// map.insert("foo", 1); 85 | /// map.clear(); 86 | /// assert!(map.is_empty()); 87 | /// ``` 88 | pub fn clear(&mut self) { 89 | self.tree = tree_core::Tree::new(); 90 | } 91 | 92 | /// Returns true if the map contains a value for the specified key. 93 | /// 94 | /// The key may be any borrowed form of the map's key type, 95 | /// but the ordering on the borrowed form _must_ match the ordering on the key type. 96 | /// 97 | /// # Notice 98 | /// 99 | /// Because `SplayMap` is a self-adjusting amortized data structure, 100 | /// this function requires the `mut` qualifier for `self`. 101 | /// 102 | /// # Examples 103 | /// ``` 104 | /// use splay_tree::SplayMap; 105 | /// 106 | /// let mut map = SplayMap::new(); 107 | /// map.insert("foo", 1); 108 | /// assert!(map.contains_key("foo")); 109 | /// assert!(!map.contains_key("bar")); 110 | /// ``` 111 | pub fn contains_key(&mut self, key: &Q) -> bool 112 | where 113 | K: Borrow, 114 | Q: Ord, 115 | { 116 | self.tree.contains_key(key) 117 | } 118 | 119 | /// Immutable version of [`SplayMap::contains_key()`]. 120 | /// 121 | /// Note that this method could be less efficient than the mutable version. 122 | /// 123 | /// # Examples 124 | /// ``` 125 | /// use splay_tree::SplayMap; 126 | /// 127 | /// let mut map = SplayMap::new(); 128 | /// map.insert("foo", 1); 129 | /// assert!(map.contains_key_immut("foo")); 130 | /// assert!(!map.contains_key_immut("bar")); 131 | /// ``` 132 | pub fn contains_key_immut(&self, key: &Q) -> bool 133 | where 134 | K: Borrow, 135 | Q: Ord, 136 | { 137 | self.tree.contains_key_immut(key) 138 | } 139 | 140 | /// Returns a reference to the value corresponding to the key. 141 | /// 142 | /// The key may be any borrowed form of the map's key type, 143 | /// but the ordering on the borrowed form _must_ match the ordering on the key type. 144 | /// 145 | /// # Notice 146 | /// 147 | /// Because `SplayMap` is a self-adjusting amortized data structure, 148 | /// this function requires the `mut` qualifier for `self`. 149 | /// 150 | /// # Examples 151 | /// ``` 152 | /// use splay_tree::SplayMap; 153 | /// 154 | /// let mut map = SplayMap::new(); 155 | /// map.insert("foo", 1); 156 | /// assert_eq!(map.get("foo"), Some(&1)); 157 | /// assert_eq!(map.get("bar"), None); 158 | /// ``` 159 | pub fn get(&mut self, key: &Q) -> Option<&V> 160 | where 161 | K: Borrow, 162 | Q: Ord, 163 | { 164 | self.get_mut(key).map(|v| &*v) 165 | } 166 | 167 | /// Immutable version of [`SplayMap::get()`]. 168 | /// 169 | /// Note that this method could be less efficient than the mutable version. 170 | /// 171 | /// # Examples 172 | /// ``` 173 | /// use splay_tree::SplayMap; 174 | /// 175 | /// let mut map = SplayMap::new(); 176 | /// map.insert("foo", 1); 177 | /// assert_eq!(map.get_immut("foo"), Some(&1)); 178 | /// assert_eq!(map.get_immut("bar"), None); 179 | /// ``` 180 | pub fn get_immut(&self, key: &Q) -> Option<&V> 181 | where 182 | K: Borrow, 183 | Q: Ord, 184 | { 185 | self.tree.get_immut(key).map(|(_, v)| v) 186 | } 187 | 188 | /// Returns a mutable reference to the value corresponding to the key. 189 | /// 190 | /// The key may be any borrowed form of the map's key type, 191 | /// but the ordering on the borrowed form _must_ match the ordering on the key type. 192 | /// 193 | /// # Examples 194 | /// ``` 195 | /// use splay_tree::SplayMap; 196 | /// 197 | /// let mut map = SplayMap::new(); 198 | /// map.insert("foo", 1); 199 | /// map.get_mut("foo").map(|v| *v = 2); 200 | /// assert_eq!(map.get("foo"), Some(&2)); 201 | /// ``` 202 | pub fn get_mut(&mut self, key: &Q) -> Option<&mut V> 203 | where 204 | K: Borrow, 205 | Q: Ord, 206 | { 207 | self.tree.get(key) 208 | } 209 | 210 | /// Finds a minimum key which satisfies "greater than or equal to `key`" condition in the map. 211 | /// 212 | /// # Examples 213 | /// ``` 214 | /// use splay_tree::SplayMap; 215 | /// 216 | /// let mut map = SplayMap::new(); 217 | /// map.insert(1, ()); 218 | /// map.insert(3, ()); 219 | /// 220 | /// assert_eq!(map.find_lower_bound_key(&0), Some(&1)); 221 | /// assert_eq!(map.find_lower_bound_key(&1), Some(&1)); 222 | /// assert_eq!(map.find_lower_bound_key(&4), None); 223 | /// ``` 224 | pub fn find_lower_bound_key(&mut self, key: &Q) -> Option<&K> 225 | where 226 | K: Borrow, 227 | Q: Ord, 228 | { 229 | self.tree.find_lower_bound(key) 230 | } 231 | 232 | /// Immutable version of [`SplayMap::find_lower_bound_key()`]. 233 | /// 234 | /// Note that this method could be less efficient than the mutable version. 235 | /// 236 | /// # Examples 237 | /// ``` 238 | /// use splay_tree::SplayMap; 239 | /// 240 | /// let mut map = SplayMap::new(); 241 | /// map.insert(1, ()); 242 | /// map.insert(3, ()); 243 | /// 244 | /// assert_eq!(map.find_lower_bound_key_immut(&0), Some(&1)); 245 | /// assert_eq!(map.find_lower_bound_key_immut(&1), Some(&1)); 246 | /// assert_eq!(map.find_lower_bound_key_immut(&4), None); 247 | /// ``` 248 | pub fn find_lower_bound_key_immut(&self, key: &Q) -> Option<&K> 249 | where 250 | K: Borrow, 251 | Q: Ord, 252 | { 253 | self.tree.find_lower_bound_immut(key) 254 | } 255 | 256 | /// Finds a minimum key which satisfies "greater than `key`" condition in the map. 257 | /// 258 | /// # Examples 259 | /// ``` 260 | /// use splay_tree::SplayMap; 261 | /// 262 | /// let mut map = SplayMap::new(); 263 | /// map.insert(1, ()); 264 | /// map.insert(3, ()); 265 | /// 266 | /// assert_eq!(map.find_upper_bound_key(&0), Some(&1)); 267 | /// assert_eq!(map.find_upper_bound_key(&1), Some(&3)); 268 | /// assert_eq!(map.find_upper_bound_key(&4), None); 269 | /// ``` 270 | pub fn find_upper_bound_key(&mut self, key: &Q) -> Option<&K> 271 | where 272 | K: Borrow, 273 | Q: Ord, 274 | { 275 | self.tree.find_upper_bound(key) 276 | } 277 | 278 | /// Immutable version of [`SplayMap::find_upper_bound_key()`]. 279 | /// 280 | /// Note that this method could be less efficient than the mutable version. 281 | /// 282 | /// # Examples 283 | /// ``` 284 | /// use splay_tree::SplayMap; 285 | /// 286 | /// let mut map = SplayMap::new(); 287 | /// map.insert(1, ()); 288 | /// map.insert(3, ()); 289 | /// 290 | /// assert_eq!(map.find_upper_bound_key_immut(&0), Some(&1)); 291 | /// assert_eq!(map.find_upper_bound_key_immut(&1), Some(&3)); 292 | /// assert_eq!(map.find_upper_bound_key_immut(&4), None); 293 | /// ``` 294 | pub fn find_upper_bound_key_immut(&self, key: &Q) -> Option<&K> 295 | where 296 | K: Borrow, 297 | Q: Ord, 298 | { 299 | self.tree.find_upper_bound_immut(key) 300 | } 301 | 302 | /// Gets the entry which have the minimum key in the map. 303 | /// 304 | /// # Examples 305 | /// ``` 306 | /// use splay_tree::SplayMap; 307 | /// 308 | /// let mut map = SplayMap::new(); 309 | /// map.insert(1, ()); 310 | /// map.insert(3, ()); 311 | /// 312 | /// assert_eq!(map.smallest(), Some((&1, &()))); 313 | /// ``` 314 | pub fn smallest(&mut self) -> Option<(&K, &V)> { 315 | self.tree.get_lftmost() 316 | } 317 | 318 | /// Immutable version of [`SplayMap::smallest()`]. 319 | /// 320 | /// Note that this method could be less efficient than the mutable version. 321 | /// 322 | /// # Examples 323 | /// ``` 324 | /// use splay_tree::SplayMap; 325 | /// 326 | /// let mut map = SplayMap::new(); 327 | /// map.insert(1, ()); 328 | /// map.insert(3, ()); 329 | /// 330 | /// assert_eq!(map.smallest_immut(), Some((&1, &()))); 331 | /// ``` 332 | pub fn smallest_immut(&self) -> Option<(&K, &V)> { 333 | self.tree.get_lftmost_immut() 334 | } 335 | 336 | /// Takes the entry which have the minimum key in the map. 337 | /// 338 | /// # Examples 339 | /// ``` 340 | /// use splay_tree::SplayMap; 341 | /// 342 | /// let mut map = SplayMap::new(); 343 | /// map.insert(1, ()); 344 | /// map.insert(3, ()); 345 | /// 346 | /// assert_eq!(map.take_smallest(), Some((1, ()))); 347 | /// assert_eq!(map.take_smallest(), Some((3, ()))); 348 | /// assert_eq!(map.take_smallest(), None); 349 | /// ``` 350 | pub fn take_smallest(&mut self) -> Option<(K, V)> { 351 | self.tree.take_lftmost() 352 | } 353 | 354 | /// Gets the entry which have the maximum key in the map. 355 | /// 356 | /// # Examples 357 | /// ``` 358 | /// use splay_tree::SplayMap; 359 | /// 360 | /// let mut map = SplayMap::new(); 361 | /// map.insert(1, ()); 362 | /// map.insert(3, ()); 363 | /// 364 | /// assert_eq!(map.largest(), Some((&3, &()))); 365 | /// ``` 366 | pub fn largest(&mut self) -> Option<(&K, &V)> { 367 | self.tree.get_rgtmost() 368 | } 369 | 370 | /// Immutable version of [`SplayMap::largest()`]. 371 | /// 372 | /// Note that this method could be less efficient than the mutable version. 373 | /// 374 | /// # Examples 375 | /// ``` 376 | /// use splay_tree::SplayMap; 377 | /// 378 | /// let mut map = SplayMap::new(); 379 | /// map.insert(1, ()); 380 | /// map.insert(3, ()); 381 | /// 382 | /// assert_eq!(map.largest_immut(), Some((&3, &()))); 383 | /// ``` 384 | pub fn largest_immut(&self) -> Option<(&K, &V)> { 385 | self.tree.get_rgtmost_immut() 386 | } 387 | 388 | /// Takes the entry which have the maximum key in the map. 389 | /// 390 | /// # Examples 391 | /// ``` 392 | /// use splay_tree::SplayMap; 393 | /// 394 | /// let mut map = SplayMap::new(); 395 | /// map.insert(1, ()); 396 | /// map.insert(3, ()); 397 | /// 398 | /// assert_eq!(map.take_largest(), Some((3, ()))); 399 | /// assert_eq!(map.take_largest(), Some((1, ()))); 400 | /// assert_eq!(map.take_largest(), None); 401 | /// ``` 402 | pub fn take_largest(&mut self) -> Option<(K, V)> { 403 | self.tree.take_rgtmost() 404 | } 405 | 406 | /// Inserts a key-value pair into the map. 407 | /// 408 | /// If the map did not have this key present, `None` is returned. 409 | /// 410 | /// If the map did have this key present, the value is updated, 411 | /// and the old value is returned. 412 | /// The key is not updated, though; 413 | /// this matters for types that can be `==` without being identical. 414 | /// 415 | /// # Examples 416 | /// ``` 417 | /// use splay_tree::SplayMap; 418 | /// 419 | /// let mut map = SplayMap::new(); 420 | /// assert_eq!(map.insert("foo", 1), None); 421 | /// assert_eq!(map.get("foo"), Some(&1)); 422 | /// assert_eq!(map.insert("foo", 2), Some(1)); 423 | /// assert_eq!(map.get("foo"), Some(&2)); 424 | /// ``` 425 | pub fn insert(&mut self, key: K, value: V) -> Option { 426 | self.tree.insert(key, value) 427 | } 428 | 429 | /// Removes a key from the map, 430 | /// returning the value at the key if the key was previously in the map. 431 | /// 432 | /// The key may be any borrowed form of the map's key type, 433 | /// but the ordering on the borrowed form _must_ match the ordering on the key type. 434 | /// 435 | /// # Examples 436 | /// ``` 437 | /// use splay_tree::SplayMap; 438 | /// 439 | /// let mut map = SplayMap::new(); 440 | /// map.insert("foo", 1); 441 | /// assert_eq!(map.remove("foo"), Some(1)); 442 | /// assert_eq!(map.remove("foo"), None); 443 | /// ``` 444 | pub fn remove(&mut self, key: &Q) -> Option 445 | where 446 | K: Borrow, 447 | Q: Ord, 448 | { 449 | self.tree.remove(key) 450 | } 451 | 452 | /// Gets the given key's corresponding entry in the map for in-place manipulation. 453 | /// 454 | /// # Examples 455 | /// ``` 456 | /// use splay_tree::SplayMap; 457 | /// 458 | /// let mut count = SplayMap::new(); 459 | /// 460 | /// // count the number of occurrences of letters in the vec 461 | /// for x in vec!["a", "b", "a", "c", "a", "b"] { 462 | /// *count.entry(x).or_insert(0) += 1; 463 | /// } 464 | /// 465 | /// assert_eq!(count.get("a"), Some(&3)); 466 | /// ``` 467 | pub fn entry(&mut self, key: K) -> Entry { 468 | if self.contains_key(&key) { 469 | Entry::Occupied(OccupiedEntry { 470 | tree: &mut self.tree, 471 | }) 472 | } else { 473 | Entry::Vacant(VacantEntry { 474 | key, 475 | tree: &mut self.tree, 476 | }) 477 | } 478 | } 479 | } 480 | impl SplayMap { 481 | /// Returns the number of elements in the map. 482 | /// 483 | /// # Examples 484 | /// ``` 485 | /// use splay_tree::SplayMap; 486 | /// 487 | /// let mut map = SplayMap::new(); 488 | /// map.insert("foo", 1); 489 | /// map.insert("bar", 2); 490 | /// assert_eq!(map.len(), 2); 491 | /// ``` 492 | pub fn len(&self) -> usize { 493 | self.tree.len() 494 | } 495 | 496 | /// Returns true if the map contains no elements. 497 | /// 498 | /// # Examples 499 | /// ``` 500 | /// use splay_tree::SplayMap; 501 | /// 502 | /// let mut map = SplayMap::new(); 503 | /// assert!(map.is_empty()); 504 | /// 505 | /// map.insert("foo", 1); 506 | /// assert!(!map.is_empty()); 507 | /// 508 | /// map.clear(); 509 | /// assert!(map.is_empty()); 510 | /// ``` 511 | pub fn is_empty(&self) -> bool { 512 | self.len() == 0 513 | } 514 | 515 | /// Gets an iterator over the entries of the map, sorted by key. 516 | /// 517 | /// # Examples 518 | /// ``` 519 | /// use splay_tree::SplayMap; 520 | /// 521 | /// let map: SplayMap<_, _> = 522 | /// vec![("foo", 1), ("bar", 2), ("baz", 3)].into_iter().collect(); 523 | /// assert_eq!(vec![(&"bar", &2), (&"baz", &3), (&"foo", &1)], 524 | /// map.iter().collect::>()); 525 | /// ``` 526 | pub fn iter(&self) -> Iter { 527 | Iter::new(&self.tree) 528 | } 529 | 530 | /// Gets a mutable iterator over the entries of the map, soretd by key. 531 | /// 532 | /// # Examples 533 | /// ``` 534 | /// use splay_tree::SplayMap; 535 | /// 536 | /// let mut map: SplayMap<_, _> = 537 | /// vec![("foo", 1), ("bar", 2), ("baz", 3)].into_iter().collect(); 538 | /// for (_, v) in map.iter_mut() { 539 | /// *v += 10; 540 | /// } 541 | /// assert_eq!(map.get("bar"), Some(&12)); 542 | /// ``` 543 | pub fn iter_mut(&mut self) -> IterMut { 544 | IterMut::new(&mut self.tree) 545 | } 546 | 547 | /// Gets an iterator over the keys of the map, in sorted order. 548 | /// 549 | /// # Examples 550 | /// ``` 551 | /// use splay_tree::SplayMap; 552 | /// 553 | /// let map: SplayMap<_, _> = 554 | /// vec![("foo", 1), ("bar", 2), ("baz", 3)].into_iter().collect(); 555 | /// assert_eq!(vec!["bar", "baz", "foo"], 556 | /// map.keys().cloned().collect::>()); 557 | /// ``` 558 | pub fn keys(&self) -> Keys { 559 | Keys::new(&self.tree) 560 | } 561 | 562 | /// Gets an iterator over the values of the map, in order by key. 563 | /// 564 | /// # Examples 565 | /// ``` 566 | /// use splay_tree::SplayMap; 567 | /// 568 | /// let map: SplayMap<_, _> = 569 | /// vec![("foo", 1), ("bar", 2), ("baz", 3)].into_iter().collect(); 570 | /// assert_eq!(vec![2, 3, 1], 571 | /// map.values().cloned().collect::>()); 572 | /// ``` 573 | pub fn values(&self) -> Values { 574 | Values::new(&self.tree) 575 | } 576 | 577 | /// Gets a mutable iterator over the values of the map, in order by key. 578 | /// 579 | /// # Examples 580 | /// ``` 581 | /// use splay_tree::SplayMap; 582 | /// 583 | /// let mut map: SplayMap<_, _> = 584 | /// vec![("foo", 1), ("bar", 2), ("baz", 3)].into_iter().collect(); 585 | /// for v in map.values_mut() { 586 | /// *v += 10; 587 | /// } 588 | /// assert_eq!(vec![12, 13, 11], 589 | /// map.values().cloned().collect::>()); 590 | /// ``` 591 | pub fn values_mut(&mut self) -> ValuesMut { 592 | ValuesMut::new(&mut self.tree) 593 | } 594 | } 595 | impl Default for SplayMap 596 | where 597 | K: Ord, 598 | { 599 | fn default() -> Self { 600 | SplayMap::new() 601 | } 602 | } 603 | impl std::iter::FromIterator<(K, V)> for SplayMap 604 | where 605 | K: Ord, 606 | { 607 | fn from_iter(iter: I) -> Self 608 | where 609 | I: IntoIterator, 610 | { 611 | let mut map = SplayMap::new(); 612 | for (k, v) in iter { 613 | map.insert(k, v); 614 | } 615 | map 616 | } 617 | } 618 | impl<'a, K, V> IntoIterator for &'a SplayMap 619 | where 620 | K: 'a, 621 | V: 'a, 622 | { 623 | type Item = (&'a K, &'a V); 624 | type IntoIter = Iter<'a, K, V>; 625 | fn into_iter(self) -> Self::IntoIter { 626 | Iter::new(&self.tree) 627 | } 628 | } 629 | impl<'a, K, V> IntoIterator for &'a mut SplayMap 630 | where 631 | K: 'a, 632 | V: 'a, 633 | { 634 | type Item = (&'a K, &'a mut V); 635 | type IntoIter = IterMut<'a, K, V>; 636 | fn into_iter(self) -> Self::IntoIter { 637 | IterMut::new(&mut self.tree) 638 | } 639 | } 640 | impl IntoIterator for SplayMap { 641 | type Item = (K, V); 642 | type IntoIter = IntoIter; 643 | fn into_iter(self) -> Self::IntoIter { 644 | IntoIter::new(self.tree) 645 | } 646 | } 647 | impl Extend<(K, V)> for SplayMap 648 | where 649 | K: Ord, 650 | { 651 | fn extend(&mut self, iter: T) 652 | where 653 | T: IntoIterator, 654 | { 655 | for (k, v) in iter { 656 | self.insert(k, v); 657 | } 658 | } 659 | } 660 | impl<'a, K, V> Extend<(&'a K, &'a V)> for SplayMap 661 | where 662 | K: 'a + Copy + Ord, 663 | V: 'a + Copy, 664 | { 665 | fn extend(&mut self, iter: T) 666 | where 667 | T: IntoIterator, 668 | { 669 | for (k, v) in iter { 670 | self.insert(*k, *v); 671 | } 672 | } 673 | } 674 | 675 | /// An iterator over a SplayMap's entries. 676 | pub struct Iter<'a, K: 'a, V: 'a>(iter::Iter<'a, K, V>); 677 | impl<'a, K: 'a, V: 'a> Iter<'a, K, V> { 678 | fn new(tree: &'a tree_core::Tree) -> Self { 679 | Iter(tree.iter()) 680 | } 681 | } 682 | impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> { 683 | type Item = (&'a K, &'a V); 684 | fn next(&mut self) -> Option { 685 | self.0.next() 686 | } 687 | } 688 | 689 | /// A mutable iterator over a SplayMap's entries. 690 | pub struct IterMut<'a, K: 'a, V: 'a>(iter::IterMut<'a, K, V>); 691 | impl<'a, K: 'a, V: 'a> IterMut<'a, K, V> { 692 | fn new(tree: &'a mut tree_core::Tree) -> Self { 693 | IterMut(tree.iter_mut()) 694 | } 695 | } 696 | impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> { 697 | type Item = (&'a K, &'a mut V); 698 | fn next(&mut self) -> Option { 699 | self.0.next() 700 | } 701 | } 702 | 703 | /// An owning iterator over a SplayMap's entries. 704 | pub struct IntoIter(iter::IntoIter); 705 | impl IntoIter { 706 | fn new(tree: tree_core::Tree) -> Self { 707 | IntoIter(tree.into_iter()) 708 | } 709 | } 710 | impl Iterator for IntoIter { 711 | type Item = (K, V); 712 | fn next(&mut self) -> Option { 713 | self.0.next() 714 | } 715 | } 716 | 717 | /// An iterator over a SplayMap's keys. 718 | pub struct Keys<'a, K: 'a, V: 'a>(Iter<'a, K, V>); 719 | impl<'a, K: 'a, V: 'a> Keys<'a, K, V> { 720 | fn new(tree: &'a tree_core::Tree) -> Self { 721 | Keys(Iter::new(tree)) 722 | } 723 | } 724 | impl<'a, K: 'a, V: 'a> Iterator for Keys<'a, K, V> { 725 | type Item = &'a K; 726 | fn next(&mut self) -> Option { 727 | self.0.next().map(|(k, _)| k) 728 | } 729 | } 730 | 731 | /// An iterator over a SplayMap's values. 732 | pub struct Values<'a, K: 'a, V: 'a>(Iter<'a, K, V>); 733 | impl<'a, K: 'a, V: 'a> Values<'a, K, V> { 734 | fn new(tree: &'a tree_core::Tree) -> Self { 735 | Values(Iter::new(tree)) 736 | } 737 | } 738 | impl<'a, K: 'a, V: 'a> Iterator for Values<'a, K, V> { 739 | type Item = &'a V; 740 | fn next(&mut self) -> Option { 741 | self.0.next().map(|(_, v)| v) 742 | } 743 | } 744 | 745 | /// A mutable iterator over a SplayMap's values. 746 | pub struct ValuesMut<'a, K: 'a, V: 'a>(IterMut<'a, K, V>); 747 | impl<'a, K: 'a, V: 'a> ValuesMut<'a, K, V> { 748 | fn new(tree: &'a mut tree_core::Tree) -> Self { 749 | ValuesMut(IterMut::new(tree)) 750 | } 751 | } 752 | impl<'a, K: 'a, V: 'a> Iterator for ValuesMut<'a, K, V> { 753 | type Item = &'a mut V; 754 | fn next(&mut self) -> Option { 755 | self.0.next().map(|(_, v)| v) 756 | } 757 | } 758 | 759 | /// A view into a single entry in a map, which may either be vacant or occupied. 760 | pub enum Entry<'a, K: 'a, V: 'a> { 761 | /// An occupied entry 762 | Occupied(OccupiedEntry<'a, K, V>), 763 | /// A vacant entry 764 | Vacant(VacantEntry<'a, K, V>), 765 | } 766 | impl<'a, K: 'a, V: 'a> Entry<'a, K, V> 767 | where 768 | K: Ord, 769 | { 770 | /// Returns a reference to this entry's key. 771 | pub fn key(&self) -> &K { 772 | match *self { 773 | Entry::Occupied(ref e) => e.key(), 774 | Entry::Vacant(ref e) => e.key(), 775 | } 776 | } 777 | 778 | /// Ensures a value is in the entry by inserting the default if empty, 779 | /// and returns a mutable reference to the value in the entry. 780 | pub fn or_insert(self, default: V) -> &'a mut V { 781 | match self { 782 | Entry::Occupied(e) => e.into_mut(), 783 | Entry::Vacant(e) => e.insert(default), 784 | } 785 | } 786 | 787 | /// Ensures a value is in the entry by inserting the result of the default function if empty, 788 | /// and returns a mutable reference to the value in the entry. 789 | pub fn or_insert_with V>(self, default: F) -> &'a mut V { 790 | match self { 791 | Entry::Occupied(e) => e.into_mut(), 792 | Entry::Vacant(e) => e.insert(default()), 793 | } 794 | } 795 | } 796 | 797 | /// An occupied Entry. 798 | pub struct OccupiedEntry<'a, K: 'a, V: 'a> { 799 | tree: &'a mut tree_core::Tree, 800 | } 801 | impl<'a, K: 'a, V: 'a> OccupiedEntry<'a, K, V> 802 | where 803 | K: Ord, 804 | { 805 | /// Gets a reference to the key in the entry. 806 | pub fn key(&self) -> &K { 807 | &self.tree.root_ref().key 808 | } 809 | 810 | /// Gets a reference to the value in the entry. 811 | pub fn get(&self) -> &V { 812 | &self.tree.root_ref().val 813 | } 814 | 815 | /// Gets a mutable reference to the value in the entry. 816 | pub fn get_mut(&mut self) -> &mut V { 817 | &mut self.tree.root_mut().val 818 | } 819 | 820 | /// Converts the entry into a mutable reference to its value. 821 | pub fn into_mut(self) -> &'a mut V { 822 | &mut self.tree.root_mut().val 823 | } 824 | 825 | /// Sets the value of the entry with the OccupiedEntry's key, 826 | /// and returns the entry's old value. 827 | pub fn insert(&mut self, value: V) -> V { 828 | mem::replace(self.get_mut(), value) 829 | } 830 | 831 | /// Takes the value of the entry out of the map, and returns it. 832 | pub fn remove(self) -> V { 833 | self.tree.pop_root().unwrap().1 834 | } 835 | } 836 | 837 | /// A vacant Entry. 838 | pub struct VacantEntry<'a, K: 'a, V: 'a> { 839 | key: K, 840 | tree: &'a mut tree_core::Tree, 841 | } 842 | impl<'a, K: 'a, V: 'a> VacantEntry<'a, K, V> 843 | where 844 | K: Ord, 845 | { 846 | /// Gets a reference to the key that would be used 847 | /// when inserting a value through the VacantEntry. 848 | pub fn key(&self) -> &K { 849 | &self.key 850 | } 851 | 852 | /// Sets the value of the entry with the VacantEntry's key, 853 | /// and returns a mutable reference to it. 854 | pub fn insert(self, value: V) -> &'a mut V { 855 | self.tree.insert(self.key, value); 856 | &mut self.tree.root_mut().val 857 | } 858 | } 859 | -------------------------------------------------------------------------------- /src/set.rs: -------------------------------------------------------------------------------- 1 | //! A set based on splay tree. 2 | use crate::iter; 3 | use crate::tree_core; 4 | use crate::vec_like; 5 | use std::borrow::Borrow; 6 | use std::cmp; 7 | use std::iter::Peekable; 8 | use std::ops; 9 | 10 | /// A set based on splay tree. 11 | /// 12 | /// A splay tree based set is a self-adjusting data structure. 13 | /// It performs insertion, removal and look-up in `O(log n)` amortized time. 14 | /// 15 | /// It is a logic error for a key to be modified in such a way that 16 | /// the key's ordering relative to any other key, 17 | /// as determined by the `Ord` trait, changes while it is in the map. 18 | /// This is normally only possible through `Cell`, `RefCell`, global state, I/O, or unsafe code. 19 | /// 20 | /// # Examples 21 | /// ``` 22 | /// use splay_tree::SplaySet; 23 | /// 24 | /// let mut set = SplaySet::new(); 25 | /// 26 | /// set.insert("foo"); 27 | /// set.insert("bar"); 28 | /// set.insert("baz"); 29 | /// assert_eq!(set.len(), 3); 30 | /// 31 | /// assert!(set.contains("bar")); 32 | /// assert!(set.remove("bar")); 33 | /// assert!(!set.contains("bar")); 34 | /// 35 | /// assert_eq!(vec!["baz", "foo"], set.into_iter().collect::>()); 36 | /// ``` 37 | #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] 38 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] 39 | pub struct SplaySet { 40 | tree: tree_core::Tree, 41 | } 42 | impl SplaySet 43 | where 44 | T: Ord, 45 | { 46 | /// Makes a new SplaySet 47 | /// 48 | /// # Examples 49 | /// ``` 50 | /// use splay_tree::SplaySet; 51 | /// 52 | /// let set: SplaySet<()> = SplaySet::new(); 53 | /// assert!(set.is_empty()); 54 | /// ``` 55 | pub fn new() -> Self { 56 | SplaySet { 57 | tree: tree_core::Tree::new(), 58 | } 59 | } 60 | 61 | /// Clears the set, removing all values. 62 | /// 63 | /// # Examples 64 | /// ``` 65 | /// use splay_tree::SplaySet; 66 | /// 67 | /// let mut set = SplaySet::new(); 68 | /// set.insert("foo"); 69 | /// set.clear(); 70 | /// assert!(set.is_empty()); 71 | /// ``` 72 | pub fn clear(&mut self) { 73 | self.tree = tree_core::Tree::new(); 74 | } 75 | 76 | /// Returns true if the set contains a value. 77 | /// 78 | /// The value may be any borrowed form of the set's value type, 79 | /// but the ordering on the borrowed form _must_ match the ordering on the value type. 80 | /// 81 | /// Because `SplaySet` is a self-adjusting amortized data structure, 82 | /// this function requires the `mut` qualifier for `self`. 83 | /// 84 | /// # Examples 85 | /// ``` 86 | /// use splay_tree::SplaySet; 87 | /// 88 | /// let mut set = SplaySet::new(); 89 | /// set.insert("foo"); 90 | /// assert!(set.contains("foo")); 91 | /// assert!(!set.contains("bar")); 92 | /// ``` 93 | pub fn contains(&mut self, value: &Q) -> bool 94 | where 95 | T: Borrow, 96 | Q: Ord, 97 | { 98 | self.tree.contains_key(value) 99 | } 100 | 101 | /// Immutable version of [`SplaySet::contains()`]. 102 | /// 103 | /// Note that this method could be less efficient than the mutable version. 104 | /// 105 | /// # Examples 106 | /// ``` 107 | /// use splay_tree::SplaySet; 108 | /// 109 | /// let mut set = SplaySet::new(); 110 | /// set.insert("foo"); 111 | /// assert!(set.contains_immut("foo")); 112 | /// assert!(!set.contains_immut("bar")); 113 | /// ``` 114 | pub fn contains_immut(&self, value: &Q) -> bool 115 | where 116 | T: Borrow, 117 | Q: Ord, 118 | { 119 | self.tree.contains_key_immut(value) 120 | } 121 | 122 | /// Returns a reference to the value in the set, if any, that is equal to the given value. 123 | /// 124 | /// The value may be any borrowed form of the set's value type, 125 | /// but the ordering on the borrowed form _must_ match the ordering on the value type. 126 | /// 127 | /// Because `SplaySet` is a self-adjusting amortized data structure, 128 | /// this function requires the `mut` qualifier for `self`. 129 | /// 130 | /// # Examples 131 | /// ``` 132 | /// use splay_tree::SplaySet; 133 | /// 134 | /// let mut set = SplaySet::new(); 135 | /// set.insert("foo"); 136 | /// assert_eq!(set.get("foo"), Some(&"foo")); 137 | /// assert_eq!(set.get("bar"), None); 138 | /// ``` 139 | pub fn get(&mut self, value: &Q) -> Option<&T> 140 | where 141 | T: Borrow, 142 | Q: Ord, 143 | { 144 | if self.tree.get(value).is_some() { 145 | Some(&self.tree.root_ref().key) 146 | } else { 147 | None 148 | } 149 | } 150 | 151 | /// Immutable version of [`SplaySet::get()`]. 152 | /// 153 | /// Note that this method could be less efficient than the mutable version. 154 | /// 155 | /// # Examples 156 | /// ``` 157 | /// use splay_tree::SplaySet; 158 | /// 159 | /// let mut set = SplaySet::new(); 160 | /// set.insert("foo"); 161 | /// assert_eq!(set.get_immut("foo"), Some(&"foo")); 162 | /// assert_eq!(set.get_immut("bar"), None); 163 | /// ``` 164 | pub fn get_immut(&self, value: &Q) -> Option<&T> 165 | where 166 | T: Borrow, 167 | Q: Ord, 168 | { 169 | self.tree.get_immut(value).map(|x| x.0) 170 | } 171 | 172 | /// Finds a minimum element which 173 | /// satisfies "greater than or equal to `value`" condition in the set. 174 | /// 175 | /// The value may be any borrowed form of the set's value type, 176 | /// but the ordering on the borrowed form _must_ match the ordering on the value type. 177 | /// 178 | /// # Examples 179 | /// ``` 180 | /// use splay_tree::SplaySet; 181 | /// 182 | /// let mut set = SplaySet::new(); 183 | /// set.insert(1); 184 | /// set.insert(3); 185 | /// 186 | /// assert_eq!(set.find_lower_bound(&0), Some(&1)); 187 | /// assert_eq!(set.find_lower_bound(&1), Some(&1)); 188 | /// assert_eq!(set.find_lower_bound(&4), None); 189 | /// ``` 190 | pub fn find_lower_bound(&mut self, value: &Q) -> Option<&T> 191 | where 192 | T: Borrow, 193 | Q: Ord, 194 | { 195 | self.tree.find_lower_bound(value) 196 | } 197 | 198 | /// Immutable version of [`SplaySet::find_lower_bound()`]. 199 | /// 200 | /// Note that this method could be less efficient than the mutable version. 201 | /// 202 | /// # Examples 203 | /// ``` 204 | /// use splay_tree::SplaySet; 205 | /// 206 | /// let mut set = SplaySet::new(); 207 | /// set.insert(1); 208 | /// set.insert(3); 209 | /// 210 | /// assert_eq!(set.find_lower_bound_immut(&0), Some(&1)); 211 | /// assert_eq!(set.find_lower_bound_immut(&1), Some(&1)); 212 | /// assert_eq!(set.find_lower_bound_immut(&4), None); 213 | /// ``` 214 | pub fn find_lower_bound_immut(&self, value: &Q) -> Option<&T> 215 | where 216 | T: Borrow, 217 | Q: Ord, 218 | { 219 | self.tree.find_lower_bound_immut(value) 220 | } 221 | 222 | /// Finds a minimum element which satisfies "greater than `value`" condition in the set. 223 | /// 224 | /// The value may be any borrowed form of the set's value type, 225 | /// but the ordering on the borrowed form _must_ match the ordering on the value type. 226 | /// 227 | /// # Examples 228 | /// ``` 229 | /// use splay_tree::SplaySet; 230 | /// 231 | /// let mut set = SplaySet::new(); 232 | /// set.insert(1); 233 | /// set.insert(3); 234 | /// 235 | /// assert_eq!(set.find_upper_bound(&0), Some(&1)); 236 | /// assert_eq!(set.find_upper_bound(&1), Some(&3)); 237 | /// assert_eq!(set.find_upper_bound(&4), None); 238 | /// ``` 239 | pub fn find_upper_bound(&mut self, value: &Q) -> Option<&T> 240 | where 241 | T: Borrow, 242 | Q: Ord, 243 | { 244 | self.tree.find_upper_bound(value) 245 | } 246 | 247 | /// Immutable version of [`SplaySet::find_upper_bound()`]. 248 | /// 249 | /// Note that this method could be less efficient than the mutable version. 250 | /// 251 | /// # Examples 252 | /// ``` 253 | /// use splay_tree::SplaySet; 254 | /// 255 | /// let mut set = SplaySet::new(); 256 | /// set.insert(1); 257 | /// set.insert(3); 258 | /// 259 | /// assert_eq!(set.find_upper_bound_immut(&0), Some(&1)); 260 | /// assert_eq!(set.find_upper_bound_immut(&1), Some(&3)); 261 | /// assert_eq!(set.find_upper_bound_immut(&4), None); 262 | /// ``` 263 | pub fn find_upper_bound_immut(&self, value: &Q) -> Option<&T> 264 | where 265 | T: Borrow, 266 | Q: Ord, 267 | { 268 | self.tree.find_upper_bound_immut(value) 269 | } 270 | 271 | /// Gets the minimum value in the map. 272 | /// 273 | /// # Examples 274 | /// ``` 275 | /// use splay_tree::SplaySet; 276 | /// 277 | /// let mut set = SplaySet::new(); 278 | /// set.insert(1); 279 | /// set.insert(3); 280 | /// 281 | /// assert_eq!(set.smallest(), Some(&1)); 282 | /// ``` 283 | pub fn smallest(&mut self) -> Option<&T> { 284 | self.tree.get_lftmost().map(|(v, _)| v) 285 | } 286 | 287 | /// Immutable version of [`SplaySet::smallest()`]. 288 | /// 289 | /// Note that this method could be less efficient than the mutable version. 290 | /// 291 | /// # Examples 292 | /// ``` 293 | /// use splay_tree::SplaySet; 294 | /// 295 | /// let mut set = SplaySet::new(); 296 | /// set.insert(1); 297 | /// set.insert(3); 298 | /// 299 | /// assert_eq!(set.smallest_immut(), Some(&1)); 300 | /// ``` 301 | pub fn smallest_immut(&self) -> Option<&T> { 302 | self.tree.get_lftmost_immut().map(|(v, _)| v) 303 | } 304 | 305 | /// Takes the minimum value in the map. 306 | /// 307 | /// # Examples 308 | /// ``` 309 | /// use splay_tree::SplaySet; 310 | /// 311 | /// let mut set = SplaySet::new(); 312 | /// set.insert(1); 313 | /// set.insert(3); 314 | /// 315 | /// assert_eq!(set.take_smallest(), Some(1)); 316 | /// assert_eq!(set.take_smallest(), Some(3)); 317 | /// assert_eq!(set.take_smallest(), None); 318 | /// ``` 319 | pub fn take_smallest(&mut self) -> Option { 320 | self.tree.take_lftmost().map(|(v, _)| v) 321 | } 322 | 323 | /// Gets the maximum value in the map. 324 | /// 325 | /// # Examples 326 | /// ``` 327 | /// use splay_tree::SplaySet; 328 | /// 329 | /// let mut set = SplaySet::new(); 330 | /// set.insert(1); 331 | /// set.insert(3); 332 | /// 333 | /// assert_eq!(set.largest(), Some(&3)); 334 | /// ``` 335 | pub fn largest(&mut self) -> Option<&T> { 336 | self.tree.get_rgtmost().map(|(v, _)| v) 337 | } 338 | 339 | /// Immutable version of [`SplaySet::largest()`]. 340 | /// 341 | /// Note that this method could be less efficient than the mutable version. 342 | /// 343 | /// # Examples 344 | /// ``` 345 | /// use splay_tree::SplaySet; 346 | /// 347 | /// let mut set = SplaySet::new(); 348 | /// set.insert(1); 349 | /// set.insert(3); 350 | /// 351 | /// assert_eq!(set.largest_immut(), Some(&3)); 352 | /// ``` 353 | pub fn largest_immut(&self) -> Option<&T> { 354 | self.tree.get_rgtmost_immut().map(|(v, _)| v) 355 | } 356 | 357 | /// Takes the maximum value in the map. 358 | /// 359 | /// # Examples 360 | /// ``` 361 | /// use splay_tree::SplaySet; 362 | /// 363 | /// let mut set = SplaySet::new(); 364 | /// set.insert(1); 365 | /// set.insert(3); 366 | /// 367 | /// assert_eq!(set.take_largest(), Some(3)); 368 | /// assert_eq!(set.take_largest(), Some(1)); 369 | /// assert_eq!(set.take_largest(), None); 370 | /// ``` 371 | pub fn take_largest(&mut self) -> Option { 372 | self.tree.take_rgtmost().map(|(v, _)| v) 373 | } 374 | 375 | /// Adds a value to the set. 376 | /// 377 | /// If the set did not have this value present, `true` is returned. 378 | /// 379 | /// If the set did have this value present, `false` is returned, 380 | /// and the entry is not updated. 381 | /// 382 | /// # Examples 383 | /// ``` 384 | /// use splay_tree::SplaySet; 385 | /// 386 | /// let mut set = SplaySet::new(); 387 | /// assert!(set.insert("foo")); 388 | /// assert!(!set.insert("foo")); 389 | /// assert_eq!(set.len(), 1); 390 | /// ``` 391 | pub fn insert(&mut self, value: T) -> bool { 392 | self.tree.insert(value, ()).is_none() 393 | } 394 | 395 | /// Adds a value to the set, replacing the existing value, if any, 396 | /// that is equal to the given one. 397 | /// Returns the replaced value. 398 | /// 399 | /// # Examples 400 | /// ``` 401 | /// use splay_tree::SplaySet; 402 | /// 403 | /// let mut set = SplaySet::new(); 404 | /// assert_eq!(set.replace("foo"), None); 405 | /// assert_eq!(set.replace("foo"), Some("foo")); 406 | /// ``` 407 | pub fn replace(&mut self, value: T) -> Option { 408 | let old = self.take(&value); 409 | self.insert(value); 410 | old 411 | } 412 | 413 | /// Removes a value from the set. Returns `true` is the value was present in the set. 414 | /// 415 | /// The value may be any borrowed form of the set's value type, 416 | /// but the ordering on the borrowed form _must_ match the ordering on the value type. 417 | /// 418 | /// # Examples 419 | /// ``` 420 | /// use splay_tree::SplaySet; 421 | /// 422 | /// let mut set = SplaySet::new(); 423 | /// set.insert("foo"); 424 | /// assert_eq!(set.remove("foo"), true); 425 | /// assert_eq!(set.remove("foo"), false); 426 | /// ``` 427 | pub fn remove(&mut self, value: &Q) -> bool 428 | where 429 | T: Borrow, 430 | Q: Ord, 431 | { 432 | self.tree.remove(value).is_some() 433 | } 434 | 435 | /// Removes and returns the value in the set, if any, that is equal to the given one. 436 | /// 437 | /// The value may be any borrowed form of the set's value type, 438 | /// but the ordering on the borrowed form _must_ match the ordering on the value type. 439 | /// 440 | /// # Examples 441 | /// ``` 442 | /// use splay_tree::SplaySet; 443 | /// 444 | /// let mut set = SplaySet::new(); 445 | /// set.insert("foo"); 446 | /// assert_eq!(set.take("foo"), Some("foo")); 447 | /// assert_eq!(set.take("foo"), None); 448 | /// ``` 449 | pub fn take(&mut self, value: &Q) -> Option 450 | where 451 | T: Borrow, 452 | Q: Ord, 453 | { 454 | if self.contains(value) { 455 | self.tree.pop_root().map(|(e, _)| e) 456 | } else { 457 | None 458 | } 459 | } 460 | 461 | /// Visits the values representing the difference, in ascending order. 462 | /// 463 | /// # Examples 464 | /// ``` 465 | /// use splay_tree::SplaySet; 466 | /// 467 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 468 | /// let b: SplaySet<_> = vec![2, 3, 4].into_iter().collect(); 469 | /// 470 | /// assert_eq!(a.difference(&b).cloned().collect::>(), 471 | /// [1]); 472 | /// ``` 473 | pub fn difference<'a>(&'a self, other: &'a Self) -> Difference<'a, T> { 474 | Difference(self.iter().peekable(), other.iter().peekable()) 475 | } 476 | 477 | /// Visits the values representing the symmetric difference, in ascending order. 478 | /// 479 | /// # Examples 480 | /// ``` 481 | /// use splay_tree::SplaySet; 482 | /// 483 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 484 | /// let b: SplaySet<_> = vec![2, 3, 4].into_iter().collect(); 485 | /// 486 | /// assert_eq!(a.symmetric_difference(&b).cloned().collect::>(), 487 | /// [1, 4]); 488 | /// ``` 489 | pub fn symmetric_difference<'a>(&'a self, other: &'a Self) -> SymmetricDifference<'a, T> { 490 | SymmetricDifference(self.iter().peekable(), other.iter().peekable()) 491 | } 492 | 493 | /// Visits the values representing the intersection, in ascending order. 494 | /// 495 | /// # Examples 496 | /// ``` 497 | /// use splay_tree::SplaySet; 498 | /// 499 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 500 | /// let b: SplaySet<_> = vec![2, 3, 4].into_iter().collect(); 501 | /// 502 | /// assert_eq!(a.intersection(&b).cloned().collect::>(), 503 | /// [2, 3]); 504 | /// ``` 505 | pub fn intersection<'a>(&'a self, other: &'a Self) -> Intersection<'a, T> { 506 | Intersection(self.iter().peekable(), other.iter().peekable()) 507 | } 508 | 509 | /// Visits the values representing the union, in ascending order. 510 | /// 511 | /// # Examples 512 | /// ``` 513 | /// use splay_tree::SplaySet; 514 | /// 515 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 516 | /// let b: SplaySet<_> = vec![2, 3, 4].into_iter().collect(); 517 | /// 518 | /// assert_eq!(a.union(&b).cloned().collect::>(), 519 | /// [1, 2, 3, 4]); 520 | /// ``` 521 | pub fn union<'a>(&'a self, other: &'a Self) -> Union<'a, T> { 522 | Union(self.iter().peekable(), other.iter().peekable()) 523 | } 524 | 525 | /// Returns `true` if the set has no elements in common with `other`. 526 | /// This is equivalent to checking for an empty intersection. 527 | /// 528 | /// # Examples 529 | /// ``` 530 | /// use splay_tree::SplaySet; 531 | /// 532 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 533 | /// let b: SplaySet<_> = vec![2, 3, 4].into_iter().collect(); 534 | /// let c: SplaySet<_> = vec![4, 5, 6].into_iter().collect(); 535 | /// 536 | /// assert!(!a.is_disjoint(&b)); 537 | /// assert!(!b.is_disjoint(&c)); 538 | /// assert!(a.is_disjoint(&c)); 539 | /// assert!(c.is_disjoint(&a)); 540 | /// ``` 541 | pub fn is_disjoint(&self, other: &Self) -> bool { 542 | self.intersection(other).count() == 0 543 | } 544 | 545 | /// Returns `true` if the set is a subset of another. 546 | /// 547 | /// # Examples 548 | /// ``` 549 | /// use splay_tree::SplaySet; 550 | /// 551 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 552 | /// let b: SplaySet<_> = vec![2, 3, 4].into_iter().collect(); 553 | /// let c: SplaySet<_> = vec![1, 2, 3, 4].into_iter().collect(); 554 | /// 555 | /// assert!(!a.is_subset(&b)); 556 | /// assert!(!b.is_subset(&a)); 557 | /// assert!(!c.is_subset(&a)); 558 | /// assert!(a.is_subset(&c)); 559 | /// assert!(b.is_subset(&c)); 560 | /// assert!(c.is_subset(&c)); 561 | /// ``` 562 | pub fn is_subset(&self, other: &Self) -> bool { 563 | self.difference(other).count() == 0 564 | } 565 | 566 | /// Returns `true` if the set is a superset of another. 567 | /// 568 | /// # Examples 569 | /// ``` 570 | /// use splay_tree::SplaySet; 571 | /// 572 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 573 | /// let b: SplaySet<_> = vec![2, 3, 4].into_iter().collect(); 574 | /// let c: SplaySet<_> = vec![1, 2, 3, 4].into_iter().collect(); 575 | /// 576 | /// assert!(!a.is_superset(&b)); 577 | /// assert!(!b.is_superset(&a)); 578 | /// assert!(!a.is_superset(&c)); 579 | /// assert!(c.is_superset(&a)); 580 | /// assert!(c.is_superset(&b)); 581 | /// assert!(c.is_superset(&c)); 582 | /// ``` 583 | pub fn is_superset(&self, other: &Self) -> bool { 584 | other.is_subset(self) 585 | } 586 | 587 | /// Returns a vector like mutable view of the set. 588 | /// 589 | /// # Examples 590 | /// ``` 591 | /// use splay_tree::SplaySet; 592 | /// 593 | /// let mut set = SplaySet::new(); 594 | /// set.insert("foo"); 595 | /// set.insert("bar"); 596 | /// { 597 | /// let mut vec = set.as_vec_like_mut(); 598 | /// vec.push("baz"); 599 | /// 600 | /// assert_eq!(vec.get(0), Some(&"foo")); 601 | /// assert_eq!(vec.get(2), Some(&"baz")); 602 | /// 603 | /// assert_eq!(vec.find_index(&"bar"), Some(1)); 604 | /// 605 | /// assert_eq!(vec.iter().cloned().collect::>(), 606 | /// ["foo", "bar", "baz"]); 607 | /// } 608 | /// assert_eq!(set.iter().cloned().collect::>(), 609 | /// ["bar", "baz", "foo"]); 610 | /// ``` 611 | pub fn as_vec_like_mut(&mut self) -> VecLikeMut { 612 | VecLikeMut::new(&mut self.tree) 613 | } 614 | } 615 | impl SplaySet { 616 | /// Returns the number of elements in the set. 617 | /// 618 | /// # Examples 619 | /// ``` 620 | /// use splay_tree::SplaySet; 621 | /// 622 | /// let mut set = SplaySet::new(); 623 | /// set.insert("foo"); 624 | /// set.insert("bar"); 625 | /// assert_eq!(set.len(), 2); 626 | /// ``` 627 | pub fn len(&self) -> usize { 628 | self.tree.len() 629 | } 630 | 631 | /// Returns true if the set contains no elements. 632 | /// 633 | /// # Examples 634 | /// ``` 635 | /// use splay_tree::SplaySet; 636 | /// 637 | /// let mut set = SplaySet::new(); 638 | /// assert!(set.is_empty()); 639 | /// 640 | /// set.insert("foo"); 641 | /// assert!(!set.is_empty()); 642 | /// 643 | /// set.clear(); 644 | /// assert!(set.is_empty()); 645 | /// ``` 646 | pub fn is_empty(&self) -> bool { 647 | self.len() == 0 648 | } 649 | 650 | /// Gets an iterator over the SplaySet's contents, in sorted order. 651 | /// 652 | /// # Examples 653 | /// ``` 654 | /// use splay_tree::SplaySet; 655 | /// 656 | /// let mut set = SplaySet::new(); 657 | /// set.insert("foo"); 658 | /// set.insert("bar"); 659 | /// set.insert("baz"); 660 | /// 661 | /// assert_eq!(set.iter().collect::>(), [&"bar", &"baz", &"foo"]); 662 | /// ``` 663 | pub fn iter(&self) -> Iter { 664 | Iter::new(self) 665 | } 666 | 667 | /// Returns a vector like view of the set. 668 | /// 669 | /// # Examples 670 | /// ``` 671 | /// use splay_tree::SplaySet; 672 | /// 673 | /// let mut set = SplaySet::new(); 674 | /// set.insert("foo"); 675 | /// set.insert("bar"); 676 | /// { 677 | /// let mut vec = set.as_vec_like(); 678 | /// assert_eq!(vec.get(0), Some(&"foo")); 679 | /// assert_eq!(vec.get(1), Some(&"bar")); 680 | /// 681 | /// assert_eq!(vec.iter().cloned().collect::>(), 682 | /// ["foo", "bar"]); 683 | /// } 684 | /// assert_eq!(set.iter().cloned().collect::>(), 685 | /// ["bar", "foo"]); 686 | /// ``` 687 | pub fn as_vec_like(&self) -> VecLike { 688 | VecLike::new(&self.tree) 689 | } 690 | } 691 | impl Default for SplaySet 692 | where 693 | T: Ord, 694 | { 695 | fn default() -> Self { 696 | SplaySet::new() 697 | } 698 | } 699 | impl std::iter::FromIterator for SplaySet 700 | where 701 | T: Ord, 702 | { 703 | fn from_iter(iter: I) -> Self 704 | where 705 | I: IntoIterator, 706 | { 707 | let mut set = SplaySet::new(); 708 | for x in iter { 709 | set.insert(x); 710 | } 711 | set 712 | } 713 | } 714 | impl IntoIterator for SplaySet { 715 | type Item = T; 716 | type IntoIter = IntoIter; 717 | fn into_iter(self) -> Self::IntoIter { 718 | IntoIter(self.tree.into_iter()) 719 | } 720 | } 721 | impl<'a, T> IntoIterator for &'a SplaySet { 722 | type Item = &'a T; 723 | type IntoIter = Iter<'a, T>; 724 | fn into_iter(self) -> Self::IntoIter { 725 | Iter::new(self) 726 | } 727 | } 728 | impl Extend for SplaySet 729 | where 730 | T: Ord, 731 | { 732 | fn extend(&mut self, iter: I) 733 | where 734 | I: IntoIterator, 735 | { 736 | for x in iter { 737 | self.insert(x); 738 | } 739 | } 740 | } 741 | impl<'a, T> Extend<&'a T> for SplaySet 742 | where 743 | T: Copy + 'a + Ord, 744 | { 745 | fn extend(&mut self, iter: I) 746 | where 747 | I: IntoIterator, 748 | { 749 | for x in iter { 750 | self.insert(*x); 751 | } 752 | } 753 | } 754 | impl<'a, 'b, T> ops::Sub<&'b SplaySet> for &'a SplaySet 755 | where 756 | T: Ord + Clone, 757 | { 758 | type Output = SplaySet; 759 | 760 | /// Returns the difference of `self` and `rhs` as a new `SplaySet`. 761 | /// 762 | /// # Examples 763 | /// ``` 764 | /// use splay_tree::SplaySet; 765 | /// 766 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 767 | /// let b: SplaySet<_> = vec![3, 4, 5].into_iter().collect(); 768 | /// 769 | /// assert_eq!((&a - &b).into_iter().collect::>(), 770 | /// [1, 2]); 771 | /// ``` 772 | fn sub(self, rhs: &SplaySet) -> SplaySet { 773 | self.difference(rhs).cloned().collect() 774 | } 775 | } 776 | impl<'a, 'b, T> ops::BitXor<&'b SplaySet> for &'a SplaySet 777 | where 778 | T: Ord + Clone, 779 | { 780 | type Output = SplaySet; 781 | 782 | /// Returns the symmetric difference of `self` and `rhs` as a new `SplaySet`. 783 | /// 784 | /// # Examples 785 | /// ``` 786 | /// use splay_tree::SplaySet; 787 | /// 788 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 789 | /// let b: SplaySet<_> = vec![3, 4, 5].into_iter().collect(); 790 | /// 791 | /// assert_eq!((&a ^ &b).into_iter().collect::>(), 792 | /// [1, 2, 4, 5]); 793 | /// ``` 794 | fn bitxor(self, rhs: &SplaySet) -> SplaySet { 795 | self.symmetric_difference(rhs).cloned().collect() 796 | } 797 | } 798 | impl<'a, 'b, T> ops::BitAnd<&'b SplaySet> for &'a SplaySet 799 | where 800 | T: Ord + Clone, 801 | { 802 | type Output = SplaySet; 803 | 804 | /// Returns the intersection of `self` and `rhs` as a new `SplaySet`. 805 | /// 806 | /// # Examples 807 | /// ``` 808 | /// use splay_tree::SplaySet; 809 | /// 810 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 811 | /// let b: SplaySet<_> = vec![3, 4, 5].into_iter().collect(); 812 | /// 813 | /// assert_eq!((&a & &b).into_iter().collect::>(), 814 | /// [3]); 815 | /// ``` 816 | fn bitand(self, rhs: &SplaySet) -> SplaySet { 817 | self.intersection(rhs).cloned().collect() 818 | } 819 | } 820 | impl<'a, 'b, T> ops::BitOr<&'b SplaySet> for &'a SplaySet 821 | where 822 | T: Ord + Clone, 823 | { 824 | type Output = SplaySet; 825 | 826 | /// Returns the union of `self` and `rhs` as a new `SplaySet`. 827 | /// 828 | /// # Examples 829 | /// ``` 830 | /// use splay_tree::SplaySet; 831 | /// 832 | /// let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 833 | /// let b: SplaySet<_> = vec![3, 4, 5].into_iter().collect(); 834 | /// 835 | /// assert_eq!((&a | &b).into_iter().collect::>(), 836 | /// [1, 2, 3, 4, 5]); 837 | /// ``` 838 | fn bitor(self, rhs: &SplaySet) -> SplaySet { 839 | self.union(rhs).cloned().collect() 840 | } 841 | } 842 | 843 | /// An Iterator over a SplaySet items. 844 | pub struct Iter<'a, T: 'a>(iter::Iter<'a, T, ()>); 845 | impl<'a, T: 'a> Iter<'a, T> { 846 | fn new(set: &'a SplaySet) -> Self { 847 | Iter(set.tree.iter()) 848 | } 849 | } 850 | impl<'a, T: 'a> Iterator for Iter<'a, T> { 851 | type Item = &'a T; 852 | fn next(&mut self) -> Option { 853 | self.0.next().map(|(e, _)| e) 854 | } 855 | } 856 | 857 | /// An owning iterator over a SplaySet's items. 858 | pub struct IntoIter(iter::IntoIter); 859 | impl Iterator for IntoIter { 860 | type Item = T; 861 | fn next(&mut self) -> Option { 862 | self.0.next().map(|(e, _)| e) 863 | } 864 | } 865 | 866 | fn item_cmp(a: Option<&T>, b: Option<&T>) -> Option 867 | where 868 | T: Ord, 869 | { 870 | match (a, b) { 871 | (None, None) => None, 872 | (Some(_), None) => Some(cmp::Ordering::Less), 873 | (None, Some(_)) => Some(cmp::Ordering::Greater), 874 | (Some(a), Some(b)) => Some(a.cmp(b)), 875 | } 876 | } 877 | 878 | /// A lazy iterator producing elements in the set difference (in-order). 879 | pub struct Difference<'a, T: 'a>(Peekable>, Peekable>); 880 | impl<'a, T: 'a> Iterator for Difference<'a, T> 881 | where 882 | T: Ord, 883 | { 884 | type Item = &'a T; 885 | fn next(&mut self) -> Option { 886 | loop { 887 | match item_cmp(self.0.peek(), self.1.peek()) { 888 | None => return None, 889 | Some(cmp::Ordering::Less) => return self.0.next(), 890 | Some(cmp::Ordering::Greater) => { 891 | self.1.next(); 892 | } 893 | Some(cmp::Ordering::Equal) => { 894 | self.0.next(); 895 | self.1.next(); 896 | } 897 | } 898 | } 899 | } 900 | } 901 | 902 | /// A lazy iterator producing elements in the set symmetric difference (in-order). 903 | pub struct SymmetricDifference<'a, T: 'a>(Peekable>, Peekable>); 904 | impl<'a, T: 'a> Iterator for SymmetricDifference<'a, T> 905 | where 906 | T: Ord, 907 | { 908 | type Item = &'a T; 909 | fn next(&mut self) -> Option { 910 | loop { 911 | match item_cmp(self.0.peek(), self.1.peek()) { 912 | None => return None, 913 | Some(cmp::Ordering::Less) => return self.0.next(), 914 | Some(cmp::Ordering::Greater) => return self.1.next(), 915 | Some(cmp::Ordering::Equal) => { 916 | self.0.next(); 917 | self.1.next(); 918 | } 919 | } 920 | } 921 | } 922 | } 923 | 924 | /// A lazy iterator producing elements in the set intersection (in-order). 925 | pub struct Intersection<'a, T: 'a>(Peekable>, Peekable>); 926 | impl<'a, T: 'a> Iterator for Intersection<'a, T> 927 | where 928 | T: Ord, 929 | { 930 | type Item = &'a T; 931 | fn next(&mut self) -> Option { 932 | loop { 933 | match item_cmp(self.0.peek(), self.1.peek()) { 934 | None => return None, 935 | Some(cmp::Ordering::Less) => { 936 | self.0.next(); 937 | } 938 | Some(cmp::Ordering::Greater) => { 939 | self.1.next(); 940 | } 941 | Some(cmp::Ordering::Equal) => { 942 | self.0.next(); 943 | return self.1.next(); 944 | } 945 | } 946 | } 947 | } 948 | } 949 | 950 | /// A lazy iterator producing elements in the set union (in-order). 951 | pub struct Union<'a, T: 'a>(Peekable>, Peekable>); 952 | impl<'a, T: 'a> Iterator for Union<'a, T> 953 | where 954 | T: Ord, 955 | { 956 | type Item = &'a T; 957 | fn next(&mut self) -> Option { 958 | match item_cmp(self.0.peek(), self.1.peek()) { 959 | None => None, 960 | Some(cmp::Ordering::Less) => self.0.next(), 961 | Some(cmp::Ordering::Greater) => self.1.next(), 962 | Some(cmp::Ordering::Equal) => { 963 | self.0.next(); 964 | self.1.next() 965 | } 966 | } 967 | } 968 | } 969 | 970 | /// A vector like view of a set. 971 | #[derive(Debug, Clone)] 972 | pub struct VecLike<'a, T: 'a> { 973 | inner: vec_like::VecLike<'a, T, ()>, 974 | } 975 | impl<'a, T: 'a> VecLike<'a, T> { 976 | fn new(tree: &'a tree_core::Tree) -> Self { 977 | VecLike { 978 | inner: vec_like::VecLike::new(tree), 979 | } 980 | } 981 | 982 | /// Returns the element of the vector at the given index, 983 | /// or `None` if the index is out of bounds. 984 | /// 985 | /// # Examples 986 | /// ``` 987 | /// use splay_tree::SplaySet; 988 | /// 989 | /// let mut set = SplaySet::new(); 990 | /// set.insert("foo"); 991 | /// set.insert("bar"); 992 | /// set.insert("baz"); 993 | /// 994 | /// let vec = set.as_vec_like(); 995 | /// assert_eq!(vec.get(0), Some(&"foo")); 996 | /// assert_eq!(vec.get(1), Some(&"bar")); 997 | /// assert_eq!(vec.get(2), Some(&"baz")); 998 | /// assert_eq!(vec.get(3), None); 999 | /// ``` 1000 | pub fn get(&self, index: usize) -> Option<&'a T> { 1001 | self.inner.get(index).map(|(v, _)| v) 1002 | } 1003 | 1004 | /// Returns the first element of the vector, or `None` if it is empty. 1005 | /// 1006 | /// # Examples 1007 | /// ``` 1008 | /// use splay_tree::SplaySet; 1009 | /// 1010 | /// let mut set = SplaySet::new(); 1011 | /// set.insert("foo"); 1012 | /// set.insert("bar"); 1013 | /// set.insert("baz"); 1014 | /// 1015 | /// let vec = set.as_vec_like(); 1016 | /// assert_eq!(vec.first(), Some(&"foo")); 1017 | /// ``` 1018 | pub fn first(&self) -> Option<&'a T> { 1019 | self.inner.first().map(|(v, _)| v) 1020 | } 1021 | 1022 | /// Returns the last element of the vector, or `None` if it is empty. 1023 | /// 1024 | /// # Examples 1025 | /// ``` 1026 | /// use splay_tree::SplaySet; 1027 | /// 1028 | /// let mut set = SplaySet::new(); 1029 | /// set.insert("foo"); 1030 | /// set.insert("bar"); 1031 | /// set.insert("baz"); 1032 | /// 1033 | /// let vec = set.as_vec_like(); 1034 | /// assert_eq!(vec.last(), Some(&"baz")); 1035 | /// ``` 1036 | pub fn last(&self) -> Option<&'a T> { 1037 | self.inner.last().map(|(v, _)| v) 1038 | } 1039 | 1040 | /// Gets an iterator over the vector's elements, in positional order (low to high). 1041 | /// 1042 | /// # Examples 1043 | /// ``` 1044 | /// use splay_tree::SplaySet; 1045 | /// 1046 | /// let mut set = SplaySet::new(); 1047 | /// set.insert("foo"); 1048 | /// set.insert("bar"); 1049 | /// set.insert("baz"); 1050 | /// 1051 | /// assert_eq!(set.iter().cloned().collect::>(), ["bar", "baz", "foo"]); 1052 | /// 1053 | /// let vec = set.as_vec_like(); 1054 | /// assert_eq!(vec.iter().cloned().collect::>(), ["foo", "bar", "baz"]); 1055 | /// ``` 1056 | pub fn iter(&self) -> VecLikeIter<'a, T> { 1057 | VecLikeIter(self.inner.iter()) 1058 | } 1059 | 1060 | /// Returns the number of elements in the vector like set. 1061 | /// 1062 | /// # Examples 1063 | /// ``` 1064 | /// use splay_tree::SplaySet; 1065 | /// 1066 | /// let mut set = SplaySet::new(); 1067 | /// set.insert("foo"); 1068 | /// { 1069 | /// let vec = set.as_vec_like(); 1070 | /// assert_eq!(vec.len(), 1); 1071 | /// } 1072 | /// ``` 1073 | pub fn len(&self) -> usize { 1074 | self.inner.len() 1075 | } 1076 | 1077 | /// Returns `true` if the vector like set contains no elements. 1078 | /// 1079 | /// # Examples 1080 | /// ``` 1081 | /// use splay_tree::SplaySet; 1082 | /// 1083 | /// let set = SplaySet::::new(); 1084 | /// let vec = set.as_vec_like(); 1085 | /// assert!(vec.is_empty()); 1086 | /// ``` 1087 | pub fn is_empty(&self) -> bool { 1088 | self.len() == 0 1089 | } 1090 | } 1091 | 1092 | /// A vector like mutable view of a set. 1093 | #[derive(Debug)] 1094 | pub struct VecLikeMut<'a, T: 'a> { 1095 | inner: vec_like::VecLikeMut<'a, T, ()>, 1096 | } 1097 | impl<'a, T: 'a> VecLikeMut<'a, T> 1098 | where 1099 | T: Ord, 1100 | { 1101 | /// Appends a new element to the back of the vector like set. 1102 | /// 1103 | /// If the set did not have this value present, `true` is returnd. 1104 | /// 1105 | /// If the set did have this value present, `false` is returnd, 1106 | /// and the entry is not appended. 1107 | /// 1108 | /// This is a synonym of the `SplaySet::insert` function. 1109 | /// 1110 | /// # Examples 1111 | /// ``` 1112 | /// use splay_tree::SplaySet; 1113 | /// 1114 | /// let mut set = SplaySet::new(); 1115 | /// let mut vec = set.as_vec_like_mut(); 1116 | /// 1117 | /// assert_eq!(vec.push("foo"), true); 1118 | /// assert_eq!(vec.len(), 1); 1119 | /// 1120 | /// assert_eq!(vec.push("foo"), false); 1121 | /// assert_eq!(vec.len(), 1); 1122 | /// 1123 | /// assert_eq!(vec.push("bar"), true); 1124 | /// assert_eq!(vec.len(), 2); 1125 | /// 1126 | /// assert_eq!(vec.find_index("foo"), Some(0)); 1127 | /// assert_eq!(vec.get(0), Some(&"foo")); 1128 | /// ``` 1129 | pub fn push(&mut self, value: T) -> bool { 1130 | self.inner.push(value, ()) 1131 | } 1132 | 1133 | /// Removes the last element from the vector like set and returns it, or `None` if it is empty. 1134 | /// 1135 | /// # Examples 1136 | /// ``` 1137 | /// use splay_tree::SplaySet; 1138 | /// 1139 | /// let mut set = SplaySet::new(); 1140 | /// set.insert("foo"); 1141 | /// set.insert("bar"); 1142 | /// { 1143 | /// let mut vec = set.as_vec_like_mut(); 1144 | /// assert_eq!(vec.pop(), Some("bar")); 1145 | /// assert_eq!(vec.pop(), Some("foo")); 1146 | /// assert_eq!(vec.pop(), None); 1147 | /// } 1148 | /// assert!(set.is_empty()); 1149 | /// ``` 1150 | pub fn pop(&mut self) -> Option { 1151 | self.inner.pop().map(|(v, _)| v) 1152 | } 1153 | 1154 | /// Returns the index of the element that is equal to the given value, 1155 | /// or `None` if the collection does not have no such element. 1156 | /// 1157 | /// Because underlying `SplaySet` is a self-adjusting amortized data structure, 1158 | /// this function requires the `mut` qualifier for `self`. 1159 | /// 1160 | /// # Examples 1161 | /// ``` 1162 | /// use splay_tree::SplaySet; 1163 | /// 1164 | /// let mut set = SplaySet::new(); 1165 | /// set.insert("foo"); 1166 | /// set.insert("bar"); 1167 | /// set.insert("baz"); 1168 | /// 1169 | /// let mut vec = set.as_vec_like_mut(); 1170 | /// assert_eq!(vec.find_index("foo"), Some(0)); 1171 | /// assert_eq!(vec.find_index("baz"), Some(2)); 1172 | /// assert_eq!(vec.find_index("qux"), None); 1173 | /// ``` 1174 | pub fn find_index(&mut self, value: &Q) -> Option 1175 | where 1176 | T: Borrow, 1177 | Q: Ord, 1178 | { 1179 | self.inner.find_index(value) 1180 | } 1181 | } 1182 | impl<'a, T: 'a> VecLikeMut<'a, T> { 1183 | fn new(tree: &'a mut tree_core::Tree) -> Self { 1184 | VecLikeMut { 1185 | inner: vec_like::VecLikeMut::new(tree), 1186 | } 1187 | } 1188 | 1189 | /// Returns the element of the vector at the given index, 1190 | /// or `None` if the index is out of bounds. 1191 | /// 1192 | /// # Examples 1193 | /// ``` 1194 | /// use splay_tree::SplaySet; 1195 | /// 1196 | /// let mut set = SplaySet::new(); 1197 | /// set.insert("foo"); 1198 | /// set.insert("bar"); 1199 | /// set.insert("baz"); 1200 | /// 1201 | /// let vec = set.as_vec_like_mut(); 1202 | /// assert_eq!(vec.get(0), Some(&"foo")); 1203 | /// assert_eq!(vec.get(1), Some(&"bar")); 1204 | /// assert_eq!(vec.get(2), Some(&"baz")); 1205 | /// assert_eq!(vec.get(3), None); 1206 | /// ``` 1207 | pub fn get(&self, index: usize) -> Option<&T> { 1208 | self.inner.get(index).map(|(v, _)| v) 1209 | } 1210 | 1211 | /// Returns the first element of the vector, or `None` if it is empty. 1212 | /// 1213 | /// # Examples 1214 | /// ``` 1215 | /// use splay_tree::SplaySet; 1216 | /// 1217 | /// let mut set = SplaySet::new(); 1218 | /// set.insert("foo"); 1219 | /// set.insert("bar"); 1220 | /// set.insert("baz"); 1221 | /// 1222 | /// let vec = set.as_vec_like_mut(); 1223 | /// assert_eq!(vec.first(), Some(&"foo")); 1224 | /// ``` 1225 | pub fn first(&self) -> Option<&T> { 1226 | self.inner.first().map(|(v, _)| v) 1227 | } 1228 | 1229 | /// Returns the last element of the vector, or `None` if it is empty. 1230 | /// 1231 | /// # Examples 1232 | /// ``` 1233 | /// use splay_tree::SplaySet; 1234 | /// 1235 | /// let mut set = SplaySet::new(); 1236 | /// set.insert("foo"); 1237 | /// set.insert("bar"); 1238 | /// set.insert("baz"); 1239 | /// 1240 | /// let vec = set.as_vec_like_mut(); 1241 | /// assert_eq!(vec.last(), Some(&"baz")); 1242 | /// ``` 1243 | pub fn last(&self) -> Option<&T> { 1244 | self.inner.last().map(|(v, _)| v) 1245 | } 1246 | 1247 | /// Gets an iterator over the vector's elements, in positional order (low to high). 1248 | /// 1249 | /// # Examples 1250 | /// ``` 1251 | /// use splay_tree::SplaySet; 1252 | /// 1253 | /// let mut set = SplaySet::new(); 1254 | /// set.insert("foo"); 1255 | /// set.insert("bar"); 1256 | /// set.insert("baz"); 1257 | /// 1258 | /// assert_eq!(set.iter().cloned().collect::>(), ["bar", "baz", "foo"]); 1259 | /// 1260 | /// let vec = set.as_vec_like_mut(); 1261 | /// assert_eq!(vec.iter().cloned().collect::>(), ["foo", "bar", "baz"]); 1262 | /// ``` 1263 | pub fn iter(&self) -> VecLikeIter { 1264 | VecLikeIter(self.inner.iter()) 1265 | } 1266 | 1267 | /// Returns the number of elements in the vector like set. 1268 | /// 1269 | /// # Examples 1270 | /// ``` 1271 | /// use splay_tree::SplaySet; 1272 | /// 1273 | /// let mut set = SplaySet::new(); 1274 | /// set.insert("foo"); 1275 | /// { 1276 | /// let mut vec = set.as_vec_like_mut(); 1277 | /// vec.push("bar"); 1278 | /// assert_eq!(vec.len(), 2); 1279 | /// } 1280 | /// assert_eq!(set.len(), 2); 1281 | /// ``` 1282 | pub fn len(&self) -> usize { 1283 | self.inner.len() 1284 | } 1285 | 1286 | /// Returns `true` if the vector like set contains no elements. 1287 | /// 1288 | /// # Examples 1289 | /// ``` 1290 | /// use splay_tree::SplaySet; 1291 | /// 1292 | /// let mut set = SplaySet::new(); 1293 | /// 1294 | /// let mut vec = set.as_vec_like_mut(); 1295 | /// assert!(vec.is_empty()); 1296 | /// 1297 | /// vec.push(0); 1298 | /// assert!(!vec.is_empty()); 1299 | /// ``` 1300 | pub fn is_empty(&self) -> bool { 1301 | self.len() == 0 1302 | } 1303 | } 1304 | 1305 | /// An iterator over a VecLike's elements 1306 | pub struct VecLikeIter<'a, T: 'a>(vec_like::Iter<'a, T, ()>); 1307 | impl<'a, T: 'a> Iterator for VecLikeIter<'a, T> { 1308 | type Item = &'a T; 1309 | fn next(&mut self) -> Option { 1310 | self.0.next().map(|(v, _)| v) 1311 | } 1312 | } 1313 | -------------------------------------------------------------------------------- /src/tree_core.rs: -------------------------------------------------------------------------------- 1 | //! In-place top-down splay tree implementation 2 | use crate::iter; 3 | use std::borrow::Borrow; 4 | use std::cmp; 5 | use std::cmp::Ordering; 6 | use std::hash; 7 | use std::mem; 8 | use std::slice; 9 | use std::u32; 10 | use std::vec::Vec; 11 | 12 | pub type NodeIndex = u32; 13 | const NULL_NODE: NodeIndex = u32::MAX; 14 | 15 | #[derive(Debug, Clone)] 16 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] 17 | pub struct Node { 18 | lft: NodeIndex, 19 | rgt: NodeIndex, 20 | pub key: K, 21 | pub val: V, 22 | } 23 | impl Node { 24 | pub fn new(key: K, val: V, lft: NodeIndex, rgt: NodeIndex) -> Self { 25 | Node { key, val, lft, rgt } 26 | } 27 | pub fn rgt(&self) -> Option { 28 | if self.rgt != NULL_NODE { 29 | Some(self.rgt) 30 | } else { 31 | None 32 | } 33 | } 34 | pub fn lft(&self) -> Option { 35 | if self.lft != NULL_NODE { 36 | Some(self.lft) 37 | } else { 38 | None 39 | } 40 | } 41 | } 42 | impl From> for (K, V) { 43 | fn from(t: Node) -> Self { 44 | (t.key, t.val) 45 | } 46 | } 47 | impl<'a, K, V> From<&'a Node> for (&'a K, &'a V) { 48 | fn from(t: &'a Node) -> Self { 49 | (&t.key, &t.val) 50 | } 51 | } 52 | impl<'a, K, V> From<&'a mut Node> for (&'a K, &'a mut V) { 53 | fn from(t: &'a mut Node) -> Self { 54 | (&t.key, &mut t.val) 55 | } 56 | } 57 | 58 | #[derive(Debug, Clone)] 59 | #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] 60 | pub struct Tree { 61 | root: NodeIndex, 62 | nodes: Vec>, 63 | } 64 | impl Tree 65 | where 66 | K: Ord, 67 | { 68 | pub fn new() -> Self { 69 | Tree { 70 | root: 0, 71 | nodes: Vec::new(), 72 | } 73 | } 74 | pub fn contains_key(&mut self, key: &Q) -> bool 75 | where 76 | K: Borrow, 77 | Q: Ord, 78 | { 79 | self.root().map_or(false, |root| { 80 | let (root, order) = self.splay(root, key); 81 | self.root = root; 82 | order == Ordering::Equal 83 | }) 84 | } 85 | pub fn contains_key_immut(&self, key: &Q) -> bool 86 | where 87 | K: Borrow, 88 | Q: Ord, 89 | { 90 | self.get_immut(key).is_some() 91 | } 92 | pub fn find_lower_bound(&mut self, key: &Q) -> Option<&K> 93 | where 94 | K: Borrow, 95 | Q: Ord, 96 | { 97 | self.find_bound(|k| key.cmp(k.borrow())) 98 | } 99 | pub fn find_lower_bound_immut(&self, key: &Q) -> Option<&K> 100 | where 101 | K: Borrow, 102 | Q: Ord, 103 | { 104 | self.find_bound_immut(|k| key.cmp(k.borrow())) 105 | } 106 | pub fn find_upper_bound(&mut self, key: &Q) -> Option<&K> 107 | where 108 | K: Borrow, 109 | Q: Ord, 110 | { 111 | self.find_bound(|k| match key.cmp(k.borrow()) { 112 | Ordering::Equal => Ordering::Greater, 113 | other => other, 114 | }) 115 | } 116 | pub fn find_upper_bound_immut(&self, key: &Q) -> Option<&K> 117 | where 118 | K: Borrow, 119 | Q: Ord, 120 | { 121 | self.find_bound_immut(|k| match key.cmp(k.borrow()) { 122 | Ordering::Equal => Ordering::Greater, 123 | other => other, 124 | }) 125 | } 126 | pub fn get(&mut self, key: &Q) -> Option<&mut V> 127 | where 128 | K: Borrow, 129 | Q: Ord, 130 | { 131 | if self.contains_key(key) { 132 | Some(&mut self.root_mut().val) 133 | } else { 134 | None 135 | } 136 | } 137 | pub fn get_immut(&self, key: &Q) -> Option<(&K, &V)> 138 | where 139 | K: Borrow, 140 | Q: Ord, 141 | { 142 | let mut index = self.root(); 143 | while let Some(node) = index.map(|i| self.node_ref(i)) { 144 | match key.cmp(node.key.borrow()) { 145 | Ordering::Equal => return Some((&node.key, &node.val)), 146 | Ordering::Less => index = node.lft(), 147 | Ordering::Greater => index = node.rgt(), 148 | } 149 | } 150 | None 151 | } 152 | pub fn find_bound_immut(&self, cmp: F) -> Option<&K> 153 | where 154 | F: Fn(&K) -> Ordering, 155 | { 156 | let mut index = self.root(); 157 | let mut candidate = None; 158 | while let Some(node) = index.map(|i| self.node_ref(i)) { 159 | match cmp(&node.key) { 160 | Ordering::Equal => return Some(&node.key), 161 | Ordering::Less => { 162 | candidate = Some(&node.key); 163 | index = node.lft(); 164 | } 165 | Ordering::Greater => index = node.rgt(), 166 | } 167 | } 168 | candidate 169 | } 170 | pub fn insert(&mut self, key: K, value: V) -> Option { 171 | if let Some(root) = self.root() { 172 | let (root, order) = self.splay(root, &key); 173 | self.root = root; 174 | match order { 175 | Ordering::Equal => { 176 | let old = mem::replace(&mut self.root_mut().val, value); 177 | Some(old) 178 | } 179 | Ordering::Less => { 180 | let lft = mem::replace(&mut self.root_mut().lft, NULL_NODE); 181 | let rgt = self.root; 182 | self.push_root(Node::new(key, value, lft, rgt)); 183 | None 184 | } 185 | Ordering::Greater => { 186 | let rgt = mem::replace(&mut self.root_mut().rgt, NULL_NODE); 187 | let lft = self.root; 188 | self.push_root(Node::new(key, value, lft, rgt)); 189 | None 190 | } 191 | } 192 | } else { 193 | self.push_root(Node::new(key, value, NULL_NODE, NULL_NODE)); 194 | None 195 | } 196 | } 197 | pub fn remove(&mut self, key: &Q) -> Option 198 | where 199 | K: Borrow, 200 | Q: Ord, 201 | { 202 | if self.contains_key(key) { 203 | Some(self.non_empty_pop_root().1) 204 | } else { 205 | None 206 | } 207 | } 208 | pub fn pop_last(&mut self) -> Option<(K, V)> { 209 | self.nodes 210 | .last() 211 | .map(|n| unsafe { &*(&n.key as *const _) }) 212 | .map(|key| { 213 | self.contains_key(key); 214 | self.non_empty_pop_root() 215 | }) 216 | } 217 | pub fn pop_root(&mut self) -> Option<(K, V)> { 218 | self.root().map(|_| self.non_empty_pop_root()) 219 | } 220 | pub fn get_lftmost(&mut self) -> Option<(&K, &V)> { 221 | self.root().map(move |root| { 222 | self.root = self.splay_lftmost(root); 223 | self.root_ref().into() 224 | }) 225 | } 226 | pub fn get_lftmost_immut(&self) -> Option<(&K, &V)> { 227 | self.root().map(|i| self.node_ref(i)).map(|mut node| { 228 | while let Some(next) = node.lft().map(|i| self.node_ref(i)) { 229 | node = next; 230 | } 231 | (&node.key, &node.val) 232 | }) 233 | } 234 | pub fn take_lftmost(&mut self) -> Option<(K, V)> { 235 | self.root().map(|root| { 236 | self.root = self.splay_lftmost(root); 237 | self.non_empty_pop_root() 238 | }) 239 | } 240 | pub fn get_rgtmost(&mut self) -> Option<(&K, &V)> { 241 | self.root().map(move |root| { 242 | self.root = self.splay_rgtmost(root); 243 | self.root_ref().into() 244 | }) 245 | } 246 | pub fn get_rgtmost_immut(&self) -> Option<(&K, &V)> { 247 | self.root().map(|i| self.node_ref(i)).map(|mut node| { 248 | while let Some(next) = node.rgt().map(|i| self.node_ref(i)) { 249 | node = next; 250 | } 251 | (&node.key, &node.val) 252 | }) 253 | } 254 | pub fn take_rgtmost(&mut self) -> Option<(K, V)> { 255 | self.root().map(|root| { 256 | self.root = self.splay_rgtmost(root); 257 | self.non_empty_pop_root() 258 | }) 259 | } 260 | fn push_root(&mut self, node: Node) { 261 | self.nodes.push(node); 262 | self.root = self.nodes.len() as NodeIndex - 1; 263 | assert!(self.root != NULL_NODE); 264 | } 265 | fn splay(&mut self, root: NodeIndex, key: &Q) -> (NodeIndex, Ordering) 266 | where 267 | K: Borrow, 268 | Q: Ord, 269 | { 270 | self.splay_by(root, |k| key.cmp(k.borrow())) 271 | } 272 | fn splay_lftmost(&mut self, root: NodeIndex) -> NodeIndex { 273 | self.splay_by(root, |_| Ordering::Less).0 274 | } 275 | fn splay_rgtmost(&mut self, root: NodeIndex) -> NodeIndex { 276 | self.splay_by(root, |_| Ordering::Greater).0 277 | } 278 | fn splay_by(&mut self, mut curr_idx: NodeIndex, cmp: F) -> (NodeIndex, Ordering) 279 | where 280 | F: Fn(&K) -> Ordering, 281 | { 282 | use std::mem::replace; 283 | let mut lft_root_idx = NULL_NODE; 284 | let mut rgt_root_idx = NULL_NODE; 285 | let mut curr_mut = unsafe { self.aliasable_node_mut(curr_idx) }; 286 | let mut order = cmp(curr_mut.key.borrow()); 287 | { 288 | let mut lft_rgtmost_idx = &mut lft_root_idx; 289 | let mut rgt_lftmost_idx = &mut rgt_root_idx; 290 | loop { 291 | let mut child_idx; 292 | let mut child_mut; 293 | match order { 294 | Ordering::Less if curr_mut.lft != NULL_NODE => { 295 | // zig 296 | child_idx = replace(&mut curr_mut.lft, NULL_NODE); 297 | child_mut = unsafe { self.aliasable_node_mut(child_idx) }; 298 | order = cmp(child_mut.key.borrow()); 299 | if Ordering::Less == order && child_mut.lft != NULL_NODE { 300 | // zig-zig 301 | let grand_child_idx = replace(&mut child_mut.lft, NULL_NODE); 302 | curr_mut.lft = replace(&mut child_mut.rgt, curr_idx); 303 | curr_idx = replace(&mut child_idx, grand_child_idx); 304 | curr_mut = replace(&mut child_mut, unsafe { 305 | self.aliasable_node_mut(grand_child_idx) 306 | }); 307 | order = cmp(child_mut.key.borrow()); 308 | } 309 | *rgt_lftmost_idx = curr_idx; 310 | rgt_lftmost_idx = unsafe { &mut *(&mut curr_mut.lft as *mut _) }; 311 | } 312 | Ordering::Greater if curr_mut.rgt != NULL_NODE => { 313 | // zag 314 | child_idx = replace(&mut curr_mut.rgt, NULL_NODE); 315 | child_mut = unsafe { self.aliasable_node_mut(child_idx) }; 316 | order = cmp(child_mut.key.borrow()); 317 | if Ordering::Greater == order && child_mut.rgt != NULL_NODE { 318 | // zag-zag 319 | let grand_child_idx = replace(&mut child_mut.rgt, NULL_NODE); 320 | curr_mut.rgt = replace(&mut child_mut.lft, curr_idx); 321 | curr_idx = replace(&mut child_idx, grand_child_idx); 322 | curr_mut = replace(&mut child_mut, unsafe { 323 | self.aliasable_node_mut(grand_child_idx) 324 | }); 325 | order = cmp(child_mut.key.borrow()); 326 | } 327 | *lft_rgtmost_idx = curr_idx; 328 | lft_rgtmost_idx = unsafe { &mut *(&mut curr_mut.rgt as *mut _) }; 329 | } 330 | _ => break, 331 | } 332 | curr_mut = child_mut; 333 | curr_idx = child_idx; 334 | } 335 | *lft_rgtmost_idx = replace(&mut curr_mut.lft, NULL_NODE); 336 | *rgt_lftmost_idx = replace(&mut curr_mut.rgt, NULL_NODE); 337 | } 338 | curr_mut.lft = lft_root_idx; 339 | curr_mut.rgt = rgt_root_idx; 340 | (curr_idx, order) 341 | } 342 | fn non_empty_pop_root(&mut self) -> (K, V) { 343 | let new_root = match *self.root_ref() { 344 | Node { 345 | lft: NULL_NODE, 346 | rgt: NULL_NODE, 347 | .. 348 | } => NULL_NODE, 349 | Node { 350 | lft, 351 | rgt: NULL_NODE, 352 | .. 353 | } => lft, 354 | Node { 355 | lft: NULL_NODE, 356 | rgt, 357 | .. 358 | } => rgt, 359 | Node { lft, rgt, .. } if self.node_ref(rgt).lft == NULL_NODE => { 360 | self.node_mut(rgt).lft = lft; 361 | rgt 362 | } 363 | Node { lft, mut rgt, .. } => { 364 | let lft_rgt = mem::replace(&mut self.node_mut(lft).rgt, NULL_NODE); 365 | if lft_rgt != NULL_NODE { 366 | rgt = self.splay_lftmost(rgt); 367 | self.node_mut(rgt).lft = lft_rgt; 368 | } 369 | self.node_mut(lft).rgt = rgt; 370 | lft 371 | } 372 | }; 373 | if self.len() as NodeIndex - 1 != self.root { 374 | let key = &self.node_ref(self.len() as NodeIndex - 1).key as *const _; 375 | let _ = self.splay(new_root, unsafe { &*key }); 376 | let last = self.nodes.pop().unwrap(); 377 | mem::replace(self.root_mut(), last).into() 378 | } else { 379 | self.root = new_root; 380 | self.nodes.pop().unwrap().into() 381 | } 382 | } 383 | fn find_bound(&mut self, cmp: F) -> Option<&K> 384 | where 385 | F: Fn(&K) -> Ordering, 386 | { 387 | self.root().and_then(move |root| { 388 | let (root, order) = self.splay_by(root, cmp); 389 | self.root = root; 390 | if let Ordering::Greater = order { 391 | let mut root_rgt = self.root_ref().rgt; 392 | if root_rgt != NULL_NODE { 393 | root_rgt = self.splay_lftmost(root_rgt); 394 | self.root_mut().rgt = root_rgt; 395 | Some(&self.node_ref(root_rgt).key) 396 | } else { 397 | None 398 | } 399 | } else { 400 | Some(&self.root_ref().key) 401 | } 402 | }) 403 | } 404 | } 405 | impl Tree { 406 | pub fn root(&self) -> Option { 407 | if self.nodes.is_empty() { 408 | None 409 | } else { 410 | Some(self.root) 411 | } 412 | } 413 | pub fn root_ref(&self) -> &Node { 414 | let root = self.root; 415 | self.node_ref(root) 416 | } 417 | pub fn root_mut(&mut self) -> &mut Node { 418 | let root = self.root; 419 | self.node_mut(root) 420 | } 421 | pub fn node_ref(&self, i: NodeIndex) -> &Node { 422 | unsafe { self.nodes.get_unchecked(i as usize) } 423 | } 424 | pub fn node_mut(&mut self, i: NodeIndex) -> &mut Node { 425 | unsafe { self.nodes.get_unchecked_mut(i as usize) } 426 | } 427 | unsafe fn aliasable_node_mut<'a>(&mut self, i: NodeIndex) -> &'a mut Node { 428 | &mut *(self.node_mut(i) as *mut _) 429 | } 430 | pub fn len(&self) -> usize { 431 | self.nodes.len() 432 | } 433 | #[allow(dead_code)] 434 | pub fn capacity(&self) -> usize { 435 | self.nodes.capacity() 436 | } 437 | pub fn iter(&self) -> iter::Iter { 438 | iter::InOrderIter::new(self.root(), &self.nodes) 439 | } 440 | pub fn iter_mut(&mut self) -> iter::IterMut { 441 | iter::InOrderIter::new(self.root(), &mut self.nodes) 442 | } 443 | pub fn into_iter(self) -> iter::IntoIter { 444 | iter::InOrderIter::new( 445 | self.root(), 446 | iter::OwnedNodes(self.nodes.into_iter().map(Some).collect()), 447 | ) 448 | } 449 | pub fn nodes_iter(&self) -> slice::Iter> { 450 | self.nodes.iter() 451 | } 452 | pub fn nodes_iter_mut(&mut self) -> slice::IterMut> { 453 | self.nodes.iter_mut() 454 | } 455 | } 456 | impl hash::Hash for Tree 457 | where 458 | K: hash::Hash, 459 | V: hash::Hash, 460 | { 461 | fn hash(&self, state: &mut H) 462 | where 463 | H: hash::Hasher, 464 | { 465 | for e in self.iter() { 466 | e.hash(state); 467 | } 468 | } 469 | } 470 | impl PartialEq for Tree 471 | where 472 | K: PartialEq, 473 | V: PartialEq, 474 | { 475 | fn eq(&self, other: &Self) -> bool { 476 | self.len() == other.len() && self.iter().zip(other.iter()).all(|(a, b)| a.eq(&b)) 477 | } 478 | } 479 | impl Eq for Tree 480 | where 481 | K: Eq, 482 | V: Eq, 483 | { 484 | } 485 | impl PartialOrd for Tree 486 | where 487 | K: PartialOrd, 488 | V: PartialOrd, 489 | { 490 | fn partial_cmp(&self, other: &Self) -> Option { 491 | let mut i0 = self.iter(); 492 | let mut i1 = other.iter(); 493 | loop { 494 | match (i0.next(), i1.next()) { 495 | (None, None) => return Some(cmp::Ordering::Equal), 496 | (None, _) => return Some(cmp::Ordering::Less), 497 | (_, None) => return Some(cmp::Ordering::Greater), 498 | (Some(e0), Some(e1)) => match e0.partial_cmp(&e1) { 499 | Some(cmp::Ordering::Equal) => {} 500 | not_equal => return not_equal, 501 | }, 502 | } 503 | } 504 | } 505 | } 506 | impl Ord for Tree 507 | where 508 | K: Ord, 509 | V: Ord, 510 | { 511 | fn cmp(&self, other: &Self) -> cmp::Ordering { 512 | let mut i0 = self.iter(); 513 | let mut i1 = other.iter(); 514 | loop { 515 | match (i0.next(), i1.next()) { 516 | (None, None) => return cmp::Ordering::Equal, 517 | (None, _) => return cmp::Ordering::Less, 518 | (_, None) => return cmp::Ordering::Greater, 519 | (Some(e0), Some(e1)) => match e0.cmp(&e1) { 520 | cmp::Ordering::Equal => {} 521 | not_equal => return not_equal, 522 | }, 523 | } 524 | } 525 | } 526 | } 527 | -------------------------------------------------------------------------------- /src/vec_like.rs: -------------------------------------------------------------------------------- 1 | use crate::tree_core; 2 | use std::borrow::Borrow; 3 | use std::slice; 4 | 5 | #[derive(Debug, Clone)] 6 | pub struct VecLike<'a, K: 'a, V: 'a> { 7 | tree: &'a tree_core::Tree, 8 | } 9 | impl<'a, K: 'a, V: 'a> VecLike<'a, K, V> { 10 | pub fn new(tree: &'a tree_core::Tree) -> Self { 11 | VecLike { tree } 12 | } 13 | pub fn len(&self) -> usize { 14 | self.tree.len() 15 | } 16 | pub fn get(&self, index: usize) -> Option<(&'a K, &'a V)> { 17 | if index < self.tree.len() { 18 | Some(self.tree.node_ref(index as tree_core::NodeIndex).into()) 19 | } else { 20 | None 21 | } 22 | } 23 | pub fn first(&self) -> Option<(&'a K, &'a V)> { 24 | self.get(0) 25 | } 26 | pub fn last(&self) -> Option<(&'a K, &'a V)> { 27 | let last = self.tree.len().wrapping_sub(1); 28 | self.get(last) 29 | } 30 | pub fn iter(&self) -> Iter<'a, K, V> { 31 | Iter(self.tree.nodes_iter()) 32 | } 33 | } 34 | 35 | #[derive(Debug)] 36 | pub struct VecLikeMut<'a, K: 'a, V: 'a> { 37 | tree: &'a mut tree_core::Tree, 38 | } 39 | impl<'a, K: 'a, V: 'a> VecLikeMut<'a, K, V> 40 | where 41 | K: Ord, 42 | { 43 | pub fn push(&mut self, key: K, value: V) -> bool { 44 | if self.tree.contains_key(&key) { 45 | false 46 | } else { 47 | self.tree.insert(key, value); 48 | true 49 | } 50 | } 51 | pub fn pop(&mut self) -> Option<(K, V)> { 52 | self.tree.pop_last() 53 | } 54 | pub fn find_index(&mut self, key: &Q) -> Option 55 | where 56 | K: Borrow, 57 | Q: Ord, 58 | { 59 | if self.tree.contains_key(key) { 60 | self.tree.root().map(|i| i as usize) 61 | } else { 62 | None 63 | } 64 | } 65 | } 66 | impl<'a, K: 'a, V: 'a> VecLikeMut<'a, K, V> { 67 | pub fn new(tree: &'a mut tree_core::Tree) -> Self { 68 | VecLikeMut { tree } 69 | } 70 | pub fn len(&self) -> usize { 71 | self.tree.len() 72 | } 73 | pub fn get(&self, index: usize) -> Option<(&K, &V)> { 74 | if index < self.tree.len() { 75 | Some(self.tree.node_ref(index as tree_core::NodeIndex).into()) 76 | } else { 77 | None 78 | } 79 | } 80 | #[allow(dead_code)] 81 | pub fn get_mut(&mut self, index: usize) -> Option<(&K, &mut V)> { 82 | if index < self.tree.len() { 83 | Some(self.tree.node_mut(index as tree_core::NodeIndex).into()) 84 | } else { 85 | None 86 | } 87 | } 88 | pub fn first(&self) -> Option<(&K, &V)> { 89 | self.get(0) 90 | } 91 | #[allow(dead_code)] 92 | pub fn first_mut(&mut self) -> Option<(&K, &mut V)> { 93 | self.get_mut(0) 94 | } 95 | pub fn last(&self) -> Option<(&K, &V)> { 96 | let last = self.tree.len().wrapping_sub(1); 97 | self.get(last) 98 | } 99 | #[allow(dead_code)] 100 | pub fn last_mut(&mut self) -> Option<(&K, &mut V)> { 101 | let last = self.tree.len().wrapping_sub(1); 102 | self.get_mut(last) 103 | } 104 | pub fn iter(&self) -> Iter { 105 | Iter(self.tree.nodes_iter()) 106 | } 107 | #[allow(dead_code)] 108 | pub fn iter_mut(&mut self) -> IterMut { 109 | IterMut(self.tree.nodes_iter_mut()) 110 | } 111 | } 112 | 113 | pub struct Iter<'a, K: 'a, V: 'a>(slice::Iter<'a, tree_core::Node>); 114 | impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> { 115 | type Item = (&'a K, &'a V); 116 | fn next(&mut self) -> Option { 117 | self.0.next().map(|n| n.into()) 118 | } 119 | } 120 | 121 | pub struct IterMut<'a, K: 'a, V: 'a>(slice::IterMut<'a, tree_core::Node>); 122 | impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> { 123 | type Item = (&'a K, &'a mut V); 124 | fn next(&mut self) -> Option { 125 | self.0.next().map(|n| n.into()) 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /tests/lib.rs: -------------------------------------------------------------------------------- 1 | use rand::seq::SliceRandom; 2 | use std::collections::hash_map::DefaultHasher; 3 | use std::hash; 4 | 5 | fn hash(x: &T) -> u64 { 6 | use std::hash::Hasher; 7 | let mut hasher = DefaultHasher::new(); 8 | x.hash(&mut hasher); 9 | hasher.finish() 10 | } 11 | 12 | mod map { 13 | use super::*; 14 | #[cfg(feature = "serde")] 15 | use serde_json::{from_str, to_string}; 16 | use splay_tree::SplayMap; 17 | 18 | #[test] 19 | fn new() { 20 | let map: SplayMap<(), ()> = SplayMap::new(); 21 | assert!(map.is_empty()); 22 | } 23 | 24 | #[test] 25 | fn default() { 26 | let map: SplayMap<(), ()> = SplayMap::default(); 27 | assert!(map.is_empty()); 28 | } 29 | 30 | #[test] 31 | fn insert_and_contains_key() { 32 | let mut map = SplayMap::new(); 33 | assert!(!map.contains_key("foo")); 34 | assert_eq!(map.insert("foo", 1), None); 35 | assert!(map.contains_key("foo")); 36 | assert_eq!(map.insert("foo", 2), Some(1)); 37 | assert!(map.contains_key("foo")); 38 | } 39 | 40 | #[test] 41 | fn clear() { 42 | let mut map = SplayMap::new(); 43 | map.insert("foo", 1); 44 | assert!(map.contains_key("foo")); 45 | map.clear(); 46 | assert!(!map.contains_key("foo")); 47 | } 48 | 49 | #[test] 50 | fn get_and_get_mut() { 51 | let mut map = SplayMap::new(); 52 | assert_eq!(map.get("foo"), None); 53 | map.insert("foo", 1); 54 | assert_eq!(map.get("foo"), Some(&1)); 55 | 56 | *map.get_mut("foo").unwrap() += 10; 57 | assert_eq!(map.get("foo"), Some(&11)); 58 | } 59 | 60 | #[test] 61 | fn iterator() { 62 | let mut map: SplayMap<_, _> = vec![("foo", 1), ("bar", 2), ("baz", 3)] 63 | .into_iter() 64 | .collect(); 65 | assert_eq!( 66 | vec!["bar", "baz", "foo"], 67 | map.keys().cloned().collect::>() 68 | ); 69 | assert_eq!(vec![2, 3, 1], map.values().cloned().collect::>()); 70 | for v in map.values_mut() { 71 | *v += 10; 72 | } 73 | assert_eq!( 74 | vec![("bar", 12), ("baz", 13), ("foo", 11)], 75 | map.into_iter().collect::>() 76 | ); 77 | } 78 | 79 | #[test] 80 | fn find_lower_or_upper_bound_key() { 81 | // small map 82 | let mut map: SplayMap<_, _> = vec![("foo", 1), ("bar", 2), ("baz", 3)] 83 | .into_iter() 84 | .collect(); 85 | assert_eq!(map.find_lower_bound_key("aaa"), Some(&"bar")); 86 | assert_eq!(map.find_upper_bound_key("aaa"), Some(&"bar")); 87 | assert_eq!(map.find_lower_bound_key("baz"), Some(&"baz")); 88 | assert_eq!(map.find_upper_bound_key("baz"), Some(&"foo")); 89 | assert_eq!(map.find_lower_bound_key("zzz"), None); 90 | assert_eq!(map.find_upper_bound_key("zzz"), None); 91 | 92 | // large map 93 | let mut input = (0..1000).into_iter().collect::>(); 94 | input.shuffle(&mut rand::thread_rng()); 95 | 96 | let mut map: SplayMap<_, _> = input.into_iter().map(|n| (n, n)).collect(); 97 | assert_eq!(map.find_lower_bound_key(&500), Some(&500)); 98 | assert_eq!(map.find_upper_bound_key(&500), Some(&501)); 99 | assert_eq!(map.find_lower_bound_key(&999), Some(&999)); 100 | assert_eq!(map.find_upper_bound_key(&999), None); 101 | } 102 | 103 | #[test] 104 | fn remove() { 105 | let mut map = SplayMap::new(); 106 | map.insert("foo", 1); 107 | map.insert("bar", 2); 108 | map.insert("baz", 3); 109 | assert_eq!(map.remove("bar"), Some(2)); 110 | assert_eq!(map.remove("bar"), None); 111 | assert_eq!(map.len(), 2); 112 | } 113 | 114 | #[test] 115 | fn enry() { 116 | let mut count = SplayMap::new(); 117 | 118 | for x in vec!["a", "b", "a", "c", "a", "b"] { 119 | *count.entry(x).or_insert(0) += 1; 120 | } 121 | 122 | assert_eq!(count.get("a"), Some(&3)); 123 | assert_eq!(count.get("b"), Some(&2)); 124 | assert_eq!(count.get("c"), Some(&1)); 125 | } 126 | 127 | #[test] 128 | fn extend() { 129 | let mut map = SplayMap::new(); 130 | map.extend(vec![("foo", 1), ("bar", 2)]); 131 | map.extend(vec![("bar", 3), ("baz", 4)]); 132 | assert_eq!( 133 | vec![("bar", 3), ("baz", 4), ("foo", 1)], 134 | map.into_iter().collect::>() 135 | ); 136 | } 137 | 138 | #[test] 139 | fn hash_eq_ord() { 140 | let mut a: SplayMap<_, _> = vec![("bar", 2), ("baz", 3)].into_iter().collect(); 141 | let mut b: SplayMap<_, _> = vec![("foo", 1), ("bar", 2)].into_iter().collect(); 142 | 143 | assert!(hash(&a) != hash(&b)); 144 | assert!(a != b); 145 | assert!(a < b); 146 | 147 | b.insert("baz", 3); 148 | assert!(a < b); 149 | 150 | a.insert("foo", 1); 151 | assert!(hash(&a) == hash(&b)); 152 | assert!(a == b); 153 | } 154 | 155 | #[test] 156 | fn large_map() { 157 | let mut input = (0..1000).into_iter().collect::>(); 158 | input.shuffle(&mut rand::thread_rng()); 159 | 160 | let mut map: SplayMap<_, _> = input.into_iter().map(|n| (n, n)).collect(); 161 | for i in 0..1000 { 162 | assert_eq!(map.remove(&i), Some(i)); 163 | } 164 | assert!(map.is_empty()); 165 | } 166 | 167 | #[cfg(feature = "serde")] 168 | #[test] 169 | fn map_serde() { 170 | let mut input = (0..1000).into_iter().collect::>(); 171 | input.shuffle(&mut rand::thread_rng()); 172 | 173 | let map: SplayMap<_, _> = input.into_iter().map(|n| (n, n)).collect(); 174 | let ser_map: SplayMap<_, _> = from_str(&to_string(&map).unwrap()).unwrap(); 175 | assert_eq!(ser_map, map); 176 | } 177 | } 178 | 179 | mod set { 180 | use super::*; 181 | #[cfg(feature = "serde")] 182 | use serde_json::{from_str, to_string}; 183 | use splay_tree::SplaySet; 184 | 185 | #[test] 186 | fn new() { 187 | let set: SplaySet<()> = SplaySet::new(); 188 | assert!(set.is_empty()); 189 | } 190 | 191 | #[test] 192 | fn default() { 193 | let set: SplaySet<()> = SplaySet::default(); 194 | assert!(set.is_empty()); 195 | } 196 | 197 | #[test] 198 | fn insert_and_replace_contains() { 199 | let mut set = SplaySet::new(); 200 | 201 | assert!(!set.contains("foo")); 202 | assert_eq!(set.insert("foo"), true); 203 | assert!(set.contains("foo")); 204 | assert_eq!(set.insert("foo"), false); 205 | assert!(set.contains("foo")); 206 | 207 | assert_eq!(set.replace("bar"), None); 208 | assert_eq!(set.replace("bar"), Some("bar")); 209 | assert!(set.contains("bar")); 210 | } 211 | 212 | #[test] 213 | fn clear() { 214 | let mut set = SplaySet::new(); 215 | set.insert("foo"); 216 | assert!(set.contains("foo")); 217 | set.clear(); 218 | assert!(!set.contains("foo")); 219 | } 220 | 221 | #[test] 222 | fn get() { 223 | let mut set = SplaySet::new(); 224 | assert_eq!(set.get("foo"), None); 225 | set.insert("foo"); 226 | assert_eq!(set.get("foo"), Some(&"foo")); 227 | } 228 | 229 | #[test] 230 | fn iterator() { 231 | let set: SplaySet<_> = vec!["foo", "bar", "baz"].into_iter().collect(); 232 | assert_eq!( 233 | set.iter().cloned().collect::>(), 234 | ["bar", "baz", "foo"] 235 | ); 236 | assert_eq!( 237 | (&set).into_iter().cloned().collect::>(), 238 | ["bar", "baz", "foo"] 239 | ); 240 | assert_eq!(set.into_iter().collect::>(), ["bar", "baz", "foo"]); 241 | } 242 | 243 | #[test] 244 | fn find_lower_or_upper_bound() { 245 | // small set 246 | let mut set: SplaySet<_> = vec!["foo", "bar", "baz"].into_iter().collect(); 247 | assert_eq!(set.find_lower_bound("aaa"), Some(&"bar")); 248 | assert_eq!(set.find_upper_bound("aaa"), Some(&"bar")); 249 | assert_eq!(set.find_lower_bound("baz"), Some(&"baz")); 250 | assert_eq!(set.find_upper_bound("baz"), Some(&"foo")); 251 | assert_eq!(set.find_lower_bound("zzz"), None); 252 | assert_eq!(set.find_upper_bound("zzz"), None); 253 | 254 | // large set 255 | let mut input = (0..1000).into_iter().collect::>(); 256 | input.shuffle(&mut rand::thread_rng()); 257 | 258 | let mut set: SplaySet<_> = input.into_iter().collect(); 259 | assert_eq!(set.find_lower_bound(&500), Some(&500)); 260 | assert_eq!(set.find_upper_bound(&500), Some(&501)); 261 | assert_eq!(set.find_lower_bound(&999), Some(&999)); 262 | assert_eq!(set.find_upper_bound(&999), None); 263 | } 264 | 265 | #[test] 266 | fn remove_and_take() { 267 | let mut set = SplaySet::new(); 268 | set.insert("foo"); 269 | set.insert("bar"); 270 | set.insert("baz"); 271 | 272 | assert_eq!(set.remove("bar"), true); 273 | assert_eq!(set.remove("bar"), false); 274 | assert_eq!(set.len(), 2); 275 | 276 | assert_eq!(set.take("foo"), Some("foo")); 277 | assert_eq!(set.take("foo"), None); 278 | assert_eq!(set.len(), 1); 279 | } 280 | 281 | #[test] 282 | fn extend() { 283 | let mut set = SplaySet::new(); 284 | set.extend(vec!["foo", "bar"]); 285 | set.extend(vec!["bar", "baz"]); 286 | assert_eq!(set.into_iter().collect::>(), ["bar", "baz", "foo"]); 287 | } 288 | 289 | #[test] 290 | fn hash_eq_ord() { 291 | let mut a: SplaySet<_> = vec!["bar", "baz"].into_iter().collect(); 292 | let mut b: SplaySet<_> = vec!["foo", "bar"].into_iter().collect(); 293 | 294 | assert!(hash(&a) != hash(&b)); 295 | assert!(a != b); 296 | assert!(a < b); 297 | 298 | b.insert("baz"); 299 | assert!(a < b); 300 | 301 | a.insert("foo"); 302 | assert!(hash(&a) == hash(&b)); 303 | assert!(a == b); 304 | } 305 | 306 | #[test] 307 | fn large_set() { 308 | let mut input = (0..1000).collect::>(); 309 | input.shuffle(&mut rand::thread_rng()); 310 | 311 | let mut set: SplaySet<_> = input.iter().cloned().collect(); 312 | for i in input { 313 | assert!(set.remove(&i)); 314 | } 315 | assert!(set.is_empty()); 316 | } 317 | 318 | #[test] 319 | fn set_operations() { 320 | let a: SplaySet<_> = vec![1, 2, 3].into_iter().collect(); 321 | let b: SplaySet<_> = vec![3, 4, 5].into_iter().collect(); 322 | let c: SplaySet<_> = vec![5, 6, 7].into_iter().collect(); 323 | let d: SplaySet<_> = vec![1, 2, 3, 4].into_iter().collect(); 324 | 325 | assert_eq!(a.difference(&b).cloned().collect::>(), [1, 2]); 326 | assert_eq!((&a - &b).into_iter().collect::>(), [1, 2]); 327 | 328 | assert_eq!( 329 | a.symmetric_difference(&b).cloned().collect::>(), 330 | [1, 2, 4, 5] 331 | ); 332 | assert_eq!((&a ^ &b).into_iter().collect::>(), [1, 2, 4, 5]); 333 | 334 | assert_eq!(a.intersection(&b).cloned().collect::>(), [3]); 335 | assert_eq!((&a & &b).into_iter().collect::>(), [3]); 336 | 337 | assert_eq!(a.union(&b).cloned().collect::>(), [1, 2, 3, 4, 5]); 338 | assert_eq!((&a | &b).into_iter().collect::>(), [1, 2, 3, 4, 5]); 339 | 340 | assert!(!a.is_disjoint(&a)); 341 | assert!(!a.is_disjoint(&b)); 342 | assert!(a.is_disjoint(&c)); 343 | assert!(!a.is_disjoint(&d)); 344 | 345 | assert!(a.is_subset(&a)); 346 | assert!(!a.is_subset(&b)); 347 | assert!(!a.is_subset(&c)); 348 | assert!(a.is_subset(&d)); 349 | 350 | assert!(a.is_superset(&a)); 351 | assert!(!a.is_superset(&b)); 352 | assert!(!a.is_superset(&c)); 353 | assert!(!a.is_superset(&d)); 354 | assert!(d.is_superset(&a)); 355 | assert!(!d.is_superset(&b)); 356 | assert!(!d.is_superset(&c)); 357 | } 358 | 359 | #[test] 360 | fn vec_like() { 361 | let mut set = SplaySet::new(); 362 | { 363 | let mut vec = set.as_vec_like_mut(); 364 | vec.push(10); 365 | vec.push(3); 366 | vec.push(7); 367 | vec.push(8); 368 | vec.pop(); 369 | assert_eq!(vec.get(0), Some(&10)); 370 | assert_eq!(vec.get(1), Some(&3)); 371 | assert_eq!(vec.get(2), Some(&7)); 372 | assert_eq!(vec.get(3), None); 373 | 374 | assert_eq!(vec.find_index(&3), Some(1)); 375 | assert_eq!(vec.find_index(&300), None); 376 | 377 | assert_eq!(vec.iter().cloned().collect::>(), [10, 3, 7]); 378 | } 379 | assert_eq!(set.iter().cloned().collect::>(), [3, 7, 10]); 380 | } 381 | 382 | #[cfg(feature = "serde")] 383 | #[test] 384 | fn set_serde() { 385 | let mut input = (0..1000).into_iter().collect::>(); 386 | input.shuffle(&mut rand::thread_rng()); 387 | 388 | let set: SplaySet<_> = input.into_iter().collect(); 389 | let ser_set: SplaySet<_> = from_str(&to_string(&set).unwrap()).unwrap(); 390 | assert_eq!(ser_set, set); 391 | } 392 | } 393 | 394 | mod heap { 395 | use super::*; 396 | #[cfg(feature = "serde")] 397 | use serde_json::{from_str, to_string}; 398 | use splay_tree::SplayHeap; 399 | 400 | #[test] 401 | fn new() { 402 | let heap: SplayHeap<()> = SplayHeap::new(); 403 | assert!(heap.is_empty()); 404 | } 405 | 406 | #[test] 407 | fn default() { 408 | let heap: SplayHeap<()> = SplayHeap::default(); 409 | assert!(heap.is_empty()); 410 | } 411 | 412 | #[test] 413 | fn push_and_pop() { 414 | let mut heap = SplayHeap::new(); 415 | 416 | heap.push(10); 417 | heap.push(1); 418 | heap.push(30); 419 | heap.push(7); 420 | assert_eq!(heap.len(), 4); 421 | 422 | assert_eq!(heap.pop(), Some(30)); 423 | assert_eq!(heap.pop(), Some(10)); 424 | assert_eq!(heap.pop(), Some(7)); 425 | assert_eq!(heap.pop(), Some(1)); 426 | assert!(heap.is_empty()); 427 | } 428 | 429 | #[test] 430 | fn peek() { 431 | let mut heap = vec![1, 2, 3].into_iter().collect::>(); 432 | assert_eq!(heap.peek(), Some(&3)); 433 | assert_eq!(heap.pop(), Some(3)); 434 | heap.clear(); 435 | 436 | assert_eq!(heap.peek(), None); 437 | } 438 | 439 | #[test] 440 | fn iterator() { 441 | let heap = vec![1, 2, 3].into_iter().collect::>(); 442 | assert_eq!(vec![3, 2, 1], heap.iter().cloned().collect::>()); 443 | assert_eq!( 444 | vec![3, 2, 1], 445 | (&heap).into_iter().cloned().collect::>() 446 | ); 447 | assert_eq!(vec![3, 2, 1], heap.into_iter().collect::>()); 448 | } 449 | 450 | #[test] 451 | fn extend() { 452 | let mut heap = SplayHeap::new(); 453 | heap.extend(vec![1, 2, 3]); 454 | heap.extend(vec![&3, &4]); 455 | assert_eq!( 456 | vec![4, 3, 3, 2, 1], 457 | heap.iter().cloned().collect::>() 458 | ); 459 | } 460 | 461 | #[test] 462 | fn large_heap() { 463 | let mut input = (0..1000).into_iter().collect::>(); 464 | input.shuffle(&mut rand::thread_rng()); 465 | 466 | let mut heap = input.into_iter().collect::>(); 467 | while let Some(n) = heap.pop() { 468 | assert_eq!(n, heap.len()); 469 | } 470 | } 471 | 472 | #[cfg(feature = "serde")] 473 | #[test] 474 | fn heap_serde() { 475 | use std::iter::FromIterator; 476 | 477 | let mut input = (0..1000).into_iter().collect::>(); 478 | input.shuffle(&mut rand::thread_rng()); 479 | 480 | let heap: SplayHeap<_> = input.into_iter().collect(); 481 | let ser_heap: SplayHeap = from_str(&to_string(&heap).unwrap()).unwrap(); 482 | assert_eq!(Vec::from_iter(ser_heap), Vec::from_iter(heap)); 483 | } 484 | } 485 | --------------------------------------------------------------------------------