├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── deploy-docs.sh └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | sudo: false 3 | matrix: 4 | include: 5 | - rust: stable 6 | - rust: nightly 7 | script: 8 | - cargo build 9 | - cargo test 10 | - cargo doc --no-deps 11 | after_success: | 12 | [ $TRAVIS_RUST_VERSION = stable ] && 13 | [ $TRAVIS_BRANCH = master ] && 14 | [ $TRAVIS_PULL_REQUEST = false ] && 15 | bash deploy-docs.sh 16 | notifications: 17 | webhooks: http://huon.me:54857/travis 18 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | 3 | name = "interval-heap" 4 | version = "0.0.5" 5 | license = "MIT/Apache-2.0" 6 | description = "A double-ended priority queue implemented with an interval heap" 7 | authors = [ 8 | "Andrew Paseltiner ", 9 | "Sebastian Gesemann ", 10 | ] 11 | 12 | repository = "https://github.com/contain-rs/interval-heap" 13 | homepage = "https://github.com/contain-rs/interval-heap" 14 | documentation = "https://contain-rs.github.io/interval-heap/interval_heap" 15 | keywords = ["data-structures"] 16 | readme = "README.md" 17 | 18 | [dependencies] 19 | compare = "0.0.6" 20 | 21 | [dev-dependencies] 22 | rand = "0.3" 23 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2015 The Rust Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | A double-ended priority queue implemented with an interval heap. 2 | 3 | Documentation is available at https://contain-rs.github.io/interval-heap/interval_heap. 4 | -------------------------------------------------------------------------------- /deploy-docs.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -o errexit -o nounset 4 | 5 | rev=$(git rev-parse --short HEAD) 6 | 7 | cd target/doc 8 | 9 | git init 10 | git config user.email 'FlashCat@users.noreply.github.com' 11 | git config user.name 'FlashCat' 12 | git remote add upstream "https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git" 13 | git fetch upstream gh-pages 14 | git reset upstream/gh-pages 15 | 16 | touch . 17 | 18 | git add -A . 19 | git commit -m "rebuild pages at ${rev}" 20 | git push -q upstream HEAD:gh-pages 21 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT 2 | // file at the top-level directory of this distribution and at 3 | // http://rust-lang.org/COPYRIGHT. 4 | // 5 | // Licensed under the Apache License, Version 2.0 or the MIT license 7 | // , at your 8 | // option. This file may not be copied, modified, or distributed 9 | // except according to those terms. 10 | 11 | //! A double-ended priority queue implemented with an interval heap. 12 | //! 13 | //! An `IntervalHeap` can be used wherever a [`BinaryHeap`][bh] can, but has the ability to 14 | //! efficiently access the heap's smallest item and accepts custom comparators. If you only need 15 | //! access to either the smallest item or the greatest item, `BinaryHeap` is more efficient. 16 | //! 17 | //! Insertion has amortized `O(log n)` time complexity. Popping the smallest or greatest item is 18 | //! `O(log n)`. Retrieving the smallest or greatest item is `O(1)`. 19 | //! 20 | //! [bh]: https://doc.rust-lang.org/stable/std/collections/struct.BinaryHeap.html 21 | 22 | extern crate compare; 23 | #[cfg(test)] extern crate rand; 24 | 25 | use std::fmt::{self, Debug}; 26 | use std::iter; 27 | use std::slice; 28 | use std::vec; 29 | 30 | use compare::{Compare, Natural, natural}; 31 | 32 | // An interval heap is a binary tree structure with the following properties: 33 | // 34 | // (1) Each node (except possibly the last leaf) contains two values 35 | // where the first one is less than or equal to the second one. 36 | // (2) Each node represents a closed interval. 37 | // (3) A child node's interval is completely contained in the parent node's 38 | // interval. 39 | // 40 | // This implies that the min and max items are always in the root node. 41 | // 42 | // This interval heap implementation stores its nodes in a linear array 43 | // using a Vec. Here's an example of the layout of a tree with 13 items 44 | // (7 nodes) where the numbers represent the *offsets* in the array: 45 | // 46 | // (0 1) 47 | // / \ 48 | // (2 3) (4 5) 49 | // / \ / \ 50 | // (6 7)(8 9)(10 11)(12 --) 51 | // 52 | // Even indices are used for the "left" item of a node while odd indices 53 | // are used for the "right" item of a node. Note: the last node may not 54 | // have a "right" item. 55 | 56 | // FIXME: There may be a better algorithm for turning a vector into an 57 | // interval heap. Right now, this takes O(n log n) time, I think. 58 | 59 | fn is_root(x: usize) -> bool { x < 2 } 60 | 61 | /// Set LSB to zero for the "left" item index of a node. 62 | fn left(x: usize) -> usize { x & !1 } 63 | 64 | /// Returns index of "left" item of parent node. 65 | fn parent_left(x: usize) -> usize { 66 | debug_assert!(!is_root(x)); 67 | left((x - 2) / 2) 68 | } 69 | 70 | /// The first `v.len() - 1` items are considered a valid interval heap 71 | /// and the last item is to be inserted. 72 | fn interval_heap_push>(v: &mut [T], cmp: &C) { 73 | debug_assert!(v.len() > 0); 74 | // Start with the last new/modified node and work our way to 75 | // the root if necessary... 76 | let mut node_max = v.len() - 1; 77 | let mut node_min = left(node_max); 78 | // The reason for using two variables instead of one is to 79 | // get around the special case of the last node only containing 80 | // one item (node_min == node_max). 81 | if cmp.compares_gt(&v[node_min], &v[node_max]) { v.swap(node_min, node_max); } 82 | while !is_root(node_min) { 83 | let par_min = parent_left(node_min); 84 | let par_max = par_min + 1; 85 | if cmp.compares_lt(&v[node_min], &v[par_min]) { 86 | v.swap(par_min, node_min); 87 | } else if cmp.compares_lt(&v[par_max], &v[node_max]) { 88 | v.swap(par_max, node_max); 89 | } else { 90 | return; // nothing to do anymore 91 | } 92 | debug_assert!(cmp.compares_le(&v[node_min], &v[node_max])); 93 | node_min = par_min; 94 | node_max = par_max; 95 | } 96 | } 97 | 98 | /// The min item in the root node of an otherwise valid interval heap 99 | /// has been been replaced with some other value without violating rule (1) 100 | /// for the root node. This function restores the interval heap properties. 101 | fn update_min>(v: &mut [T], cmp: &C) { 102 | // Starting at the root, we go down the tree... 103 | debug_assert!(cmp.compares_le(&v[0], &v[1])); 104 | let mut left = 0; 105 | loop { 106 | let c1 = left * 2 + 2; // index of 1st child's left item 107 | let c2 = left * 2 + 4; // index of 2nd child's left item 108 | if v.len() <= c1 { return; } // No children. We're done. 109 | // Pick child with lowest min 110 | let ch = if v.len() <= c2 || cmp.compares_lt(&v[c1], &v[c2]) { c1 } 111 | else { c2 }; 112 | if cmp.compares_lt(&v[ch], &v[left]) { 113 | v.swap(ch, left); 114 | left = ch; 115 | let right = left + 1; 116 | if right < v.len() { 117 | if cmp.compares_gt(&v[left], &v[right]) { v.swap(left, right); } 118 | } 119 | } else { 120 | break; 121 | } 122 | } 123 | } 124 | 125 | /// The max item in the root node of an otherwise valid interval heap 126 | /// has been been replaced with some other value without violating rule (1) 127 | /// for the root node. This function restores the interval heap properties. 128 | fn update_max>(v: &mut [T], cmp: &C) { 129 | debug_assert!(cmp.compares_le(&v[0], &v[1])); 130 | // Starting at the root, we go down the tree... 131 | let mut right = 1; 132 | loop { 133 | let c1 = right * 2 + 1; // index of 1st child's right item 134 | let c2 = right * 2 + 3; // index of 2nd child's right item 135 | if v.len() <= c1 { return; } // No children. We're done. 136 | // Pick child with greatest max 137 | let ch = if v.len() <= c2 || cmp.compares_gt(&v[c1], &v[c2]) { c1 } 138 | else { c2 }; 139 | if cmp.compares_gt(&v[ch], &v[right]) { 140 | v.swap(ch, right); 141 | right = ch; 142 | let left = right - 1; // always exists 143 | if cmp.compares_gt(&v[left], &v[right]) { v.swap(left, right); } 144 | } else { 145 | break; 146 | } 147 | } 148 | } 149 | 150 | /// A double-ended priority queue implemented with an interval heap. 151 | /// 152 | /// It is a logic error for an item to be modified in such a way that the 153 | /// item's ordering relative to any other item, as determined by the heap's 154 | /// comparator, changes while it is in the heap. This is normally only 155 | /// possible through `Cell`, `RefCell`, global state, I/O, or unsafe code. 156 | #[derive(Clone)] 157 | pub struct IntervalHeap = Natural> { 158 | data: Vec, 159 | cmp: C, 160 | } 161 | 162 | impl + Default> Default for IntervalHeap { 163 | #[inline] 164 | fn default() -> IntervalHeap { 165 | Self::with_comparator(C::default()) 166 | } 167 | } 168 | 169 | impl IntervalHeap { 170 | /// Returns an empty heap ordered according to the natural order of its items. 171 | /// 172 | /// # Examples 173 | /// 174 | /// ``` 175 | /// use interval_heap::IntervalHeap; 176 | /// 177 | /// let heap = IntervalHeap::::new(); 178 | /// assert!(heap.is_empty()); 179 | /// ``` 180 | pub fn new() -> IntervalHeap { Self::with_comparator(natural()) } 181 | 182 | /// Returns an empty heap with the given capacity and ordered according to the 183 | /// natural order of its items. 184 | /// 185 | /// The heap will be able to hold exactly `capacity` items without reallocating. 186 | /// 187 | /// # Examples 188 | /// 189 | /// ``` 190 | /// use interval_heap::IntervalHeap; 191 | /// 192 | /// let heap = IntervalHeap::::with_capacity(5); 193 | /// assert!(heap.is_empty()); 194 | /// assert!(heap.capacity() >= 5); 195 | /// ``` 196 | pub fn with_capacity(capacity: usize) -> IntervalHeap { 197 | Self::with_capacity_and_comparator(capacity, natural()) 198 | } 199 | } 200 | 201 | impl From> for IntervalHeap { 202 | /// Returns a heap containing all the items of the given vector and ordered 203 | /// according to the natural order of its items. 204 | /// 205 | /// # Examples 206 | /// 207 | /// ``` 208 | /// use interval_heap::IntervalHeap; 209 | /// 210 | /// let heap = IntervalHeap::from(vec![5, 1, 6, 4]); 211 | /// assert_eq!(heap.len(), 4); 212 | /// assert_eq!(heap.min_max(), Some((&1, &6))); 213 | /// ``` 214 | fn from(vec: Vec) -> IntervalHeap { 215 | Self::from_vec_and_comparator(vec, natural()) 216 | } 217 | } 218 | 219 | impl> IntervalHeap { 220 | /// Returns an empty heap ordered according to the given comparator. 221 | pub fn with_comparator(cmp: C) -> IntervalHeap { 222 | IntervalHeap { data: vec![], cmp: cmp } 223 | } 224 | 225 | /// Returns an empty heap with the given capacity and ordered according to the given 226 | /// comparator. 227 | pub fn with_capacity_and_comparator(capacity: usize, cmp: C) -> IntervalHeap { 228 | IntervalHeap { data: Vec::with_capacity(capacity), cmp: cmp } 229 | } 230 | 231 | /// Returns a heap containing all the items of the given vector and ordered 232 | /// according to the given comparator. 233 | pub fn from_vec_and_comparator(mut vec: Vec, cmp: C) -> IntervalHeap { 234 | for to in 2 .. vec.len() + 1 { 235 | interval_heap_push(&mut vec[..to], &cmp); 236 | } 237 | let heap = IntervalHeap { data: vec, cmp: cmp }; 238 | debug_assert!(heap.is_valid()); 239 | heap 240 | } 241 | 242 | /// Returns an iterator visiting all items in the heap in arbitrary order. 243 | pub fn iter(&self) -> Iter { 244 | debug_assert!(self.is_valid()); 245 | Iter(self.data.iter()) 246 | } 247 | 248 | /// Returns a reference to the smallest item in the heap. 249 | /// 250 | /// Returns `None` if the heap is empty. 251 | pub fn min(&self) -> Option<&T> { 252 | debug_assert!(self.is_valid()); 253 | match self.data.len() { 254 | 0 => None, 255 | _ => Some(&self.data[0]), 256 | } 257 | } 258 | 259 | /// Returns a reference to the greatest item in the heap. 260 | /// 261 | /// Returns `None` if the heap is empty. 262 | pub fn max(&self) -> Option<&T> { 263 | debug_assert!(self.is_valid()); 264 | match self.data.len() { 265 | 0 => None, 266 | 1 => Some(&self.data[0]), 267 | _ => Some(&self.data[1]), 268 | } 269 | } 270 | 271 | /// Returns references to the smallest and greatest items in the heap. 272 | /// 273 | /// Returns `None` if the heap is empty. 274 | pub fn min_max(&self) -> Option<(&T, &T)> { 275 | debug_assert!(self.is_valid()); 276 | match self.data.len() { 277 | 0 => None, 278 | 1 => Some((&self.data[0], &self.data[0])), 279 | _ => Some((&self.data[0], &self.data[1])), 280 | } 281 | } 282 | 283 | /// Returns the number of items the heap can hold without reallocation. 284 | pub fn capacity(&self) -> usize { 285 | self.data.capacity() 286 | } 287 | 288 | /// Reserves the minimum capacity for exactly `additional` more items to be inserted into the 289 | /// heap. 290 | /// 291 | /// Does nothing if the capacity is already sufficient. 292 | /// 293 | /// Note that the allocator may give the heap more space than it 294 | /// requests. Therefore capacity can not be relied upon to be precisely 295 | /// minimal. Prefer `reserve` if future insertions are expected. 296 | pub fn reserve_exact(&mut self, additional: usize) { 297 | self.data.reserve_exact(additional); 298 | } 299 | 300 | /// Reserves capacity for at least `additional` more items to be inserted into the heap. 301 | /// 302 | /// The heap may reserve more space to avoid frequent reallocations. 303 | pub fn reserve(&mut self, additional: usize) { 304 | self.data.reserve(additional); 305 | } 306 | 307 | /// Discards as much additional capacity from the heap as possible. 308 | pub fn shrink_to_fit(&mut self) { 309 | self.data.shrink_to_fit() 310 | } 311 | 312 | /// Removes the smallest item from the heap and returns it. 313 | /// 314 | /// Returns `None` if the heap was empty. 315 | pub fn pop_min(&mut self) -> Option { 316 | debug_assert!(self.is_valid()); 317 | let min = match self.data.len() { 318 | 0 => None, 319 | 1...2 => Some(self.data.swap_remove(0)), 320 | _ => { 321 | let res = self.data.swap_remove(0); 322 | update_min(&mut self.data, &self.cmp); 323 | Some(res) 324 | } 325 | }; 326 | debug_assert!(self.is_valid()); 327 | min 328 | } 329 | 330 | /// Removes the greatest item from the heap and returns it. 331 | /// 332 | /// Returns `None` if the heap was empty. 333 | pub fn pop_max(&mut self) -> Option { 334 | debug_assert!(self.is_valid()); 335 | let max = match self.data.len() { 336 | 0...2 => self.data.pop(), 337 | _ => { 338 | let res = self.data.swap_remove(1); 339 | update_max(&mut self.data, &self.cmp); 340 | Some(res) 341 | } 342 | }; 343 | debug_assert!(self.is_valid()); 344 | max 345 | } 346 | 347 | /// Pushes an item onto the heap. 348 | pub fn push(&mut self, item: T) { 349 | debug_assert!(self.is_valid()); 350 | self.data.push(item); 351 | interval_heap_push(&mut self.data, &self.cmp); 352 | debug_assert!(self.is_valid()); 353 | } 354 | 355 | /// Consumes the heap and returns its items as a vector in arbitrary order. 356 | pub fn into_vec(self) -> Vec { self.data } 357 | 358 | /// Consumes the heap and returns its items as a vector in sorted (ascending) order. 359 | pub fn into_sorted_vec(self) -> Vec { 360 | let mut vec = self.data; 361 | for hsize in (2..vec.len()).rev() { 362 | vec.swap(1, hsize); 363 | update_max(&mut vec[..hsize], &self.cmp); 364 | } 365 | vec 366 | } 367 | 368 | /// Returns the number of items in the heap. 369 | pub fn len(&self) -> usize { 370 | self.data.len() 371 | } 372 | 373 | /// Returns `true` if the heap contains no items. 374 | pub fn is_empty(&self) -> bool { 375 | self.data.is_empty() 376 | } 377 | 378 | /// Removes all items from the heap. 379 | pub fn clear(&mut self) { 380 | self.data.clear(); 381 | } 382 | 383 | /// Clears the heap, returning an iterator over the removed items in arbitrary order. 384 | pub fn drain(&mut self) -> Drain { 385 | Drain(self.data.drain(..)) 386 | } 387 | 388 | /// Checks if the heap is valid. 389 | /// 390 | /// The heap is valid if: 391 | /// 392 | /// 1. It has fewer than two items, OR 393 | /// 2a. Each node's left item is less than or equal to its right item, AND 394 | /// 2b. Each node's left item is greater than or equal to the left item of the 395 | /// node's parent, AND 396 | /// 2c. Each node's right item is less than or equal to the right item of the 397 | /// node's parent 398 | fn is_valid(&self) -> bool { 399 | let mut nodes = self.data.chunks(2); 400 | 401 | match nodes.next() { 402 | Some(chunk) if chunk.len() == 2 => { 403 | let l = &chunk[0]; 404 | let r = &chunk[1]; 405 | 406 | self.cmp.compares_le(l, r) && // 2a 407 | nodes.enumerate().all(|(i, node)| { 408 | let p = i & !1; 409 | let l = &node[0]; 410 | let r = node.last().unwrap(); 411 | 412 | self.cmp.compares_le(l, r) && // 2a 413 | self.cmp.compares_ge(l, &self.data[p]) && // 2b 414 | self.cmp.compares_le(r, &self.data[p + 1]) // 2c 415 | }) 416 | } 417 | _ => true, // 1 418 | } 419 | } 420 | } 421 | 422 | impl> Debug for IntervalHeap { 423 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 424 | f.debug_list().entries(self).finish() 425 | } 426 | } 427 | 428 | impl + Default> iter::FromIterator for IntervalHeap { 429 | fn from_iter>(iter: I) -> IntervalHeap { 430 | IntervalHeap::from_vec_and_comparator(iter.into_iter().collect(), C::default()) 431 | } 432 | } 433 | 434 | impl> Extend for IntervalHeap { 435 | fn extend>(&mut self, iter: I) { 436 | let iter = iter.into_iter(); 437 | let (lower, _) = iter.size_hint(); 438 | self.reserve(lower); 439 | for elem in iter { 440 | self.push(elem); 441 | } 442 | } 443 | } 444 | 445 | impl<'a, T: 'a + Copy, C: Compare> Extend<&'a T> for IntervalHeap { 446 | fn extend>(&mut self, iter: I) { 447 | self.extend(iter.into_iter().map(|&item| item)); 448 | } 449 | } 450 | 451 | /// An iterator over an `IntervalHeap` in arbitrary order. 452 | /// 453 | /// Acquire through [`IntervalHeap::iter`](struct.IntervalHeap.html#method.iter). 454 | pub struct Iter<'a, T: 'a>(slice::Iter<'a, T>); 455 | 456 | impl<'a, T> Clone for Iter<'a, T> { 457 | fn clone(&self) -> Iter<'a, T> { Iter(self.0.clone()) } 458 | } 459 | 460 | impl<'a, T> Iterator for Iter<'a, T> { 461 | type Item = &'a T; 462 | #[inline] fn next(&mut self) -> Option<&'a T> { self.0.next() } 463 | #[inline] fn size_hint(&self) -> (usize, Option) { self.0.size_hint() } 464 | } 465 | 466 | impl<'a, T> DoubleEndedIterator for Iter<'a, T> { 467 | fn next_back(&mut self) -> Option<&'a T> { self.0.next_back() } 468 | } 469 | 470 | impl<'a, T> ExactSizeIterator for Iter<'a, T> {} 471 | 472 | /// A consuming iterator over an `IntervalHeap` in arbitrary order. 473 | /// 474 | /// Acquire through [`IntoIterator::into_iter`]( 475 | /// https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html#tymethod.into_iter). 476 | pub struct IntoIter(vec::IntoIter); 477 | 478 | impl Iterator for IntoIter { 479 | type Item = T; 480 | fn next(&mut self) -> Option { self.0.next() } 481 | fn size_hint(&self) -> (usize, Option) { self.0.size_hint() } 482 | } 483 | 484 | impl DoubleEndedIterator for IntoIter { 485 | fn next_back(&mut self) -> Option { self.0.next_back() } 486 | } 487 | 488 | impl ExactSizeIterator for IntoIter {} 489 | 490 | /// An iterator that drains an `IntervalHeap` in arbitrary oder. 491 | /// 492 | /// Acquire through [`IntervalHeap::drain`](struct.IntervalHeap.html#method.drain). 493 | pub struct Drain<'a, T: 'a>(vec::Drain<'a, T>); 494 | 495 | impl<'a, T: 'a> Iterator for Drain<'a, T> { 496 | type Item = T; 497 | fn next(&mut self) -> Option { self.0.next() } 498 | fn size_hint(&self) -> (usize, Option) { self.0.size_hint() } 499 | } 500 | 501 | impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> { 502 | fn next_back(&mut self) -> Option { self.0.next_back() } 503 | } 504 | 505 | impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {} 506 | 507 | impl> IntoIterator for IntervalHeap { 508 | type Item = T; 509 | type IntoIter = IntoIter; 510 | fn into_iter(self) -> IntoIter { IntoIter(self.data.into_iter()) } 511 | } 512 | 513 | impl<'a, T, C: Compare> IntoIterator for &'a IntervalHeap { 514 | type Item = &'a T; 515 | type IntoIter = Iter<'a, T>; 516 | fn into_iter(self) -> Iter<'a, T> { self.iter() } 517 | } 518 | 519 | #[cfg(test)] 520 | mod test { 521 | use rand::{thread_rng, Rng}; 522 | use super::IntervalHeap; 523 | 524 | #[test] 525 | fn fuzz_push_into_sorted_vec() { 526 | let mut rng = thread_rng(); 527 | let mut tmp = Vec::with_capacity(100); 528 | for _ in 0..100 { 529 | tmp.clear(); 530 | let mut ih = IntervalHeap::from(tmp); 531 | for _ in 0..100 { 532 | ih.push(rng.next_u32()); 533 | } 534 | tmp = ih.into_sorted_vec(); 535 | for pair in tmp.windows(2) { 536 | assert!(pair[0] <= pair[1]); 537 | } 538 | } 539 | } 540 | 541 | #[test] 542 | fn fuzz_pop_min() { 543 | let mut rng = thread_rng(); 544 | let mut tmp = Vec::with_capacity(100); 545 | for _ in 0..100 { 546 | tmp.clear(); 547 | let mut ih = IntervalHeap::from(tmp); 548 | for _ in 0..100 { 549 | ih.push(rng.next_u32()); 550 | } 551 | let mut tmpx: Option = None; 552 | loop { 553 | let tmpy = ih.pop_min(); 554 | match (tmpx, tmpy) { 555 | (_, None) => break, 556 | (Some(x), Some(y)) => assert!(x <= y), 557 | _ => () 558 | } 559 | tmpx = tmpy; 560 | } 561 | tmp = ih.into_vec(); 562 | } 563 | } 564 | 565 | #[test] 566 | fn fuzz_pop_max() { 567 | let mut rng = thread_rng(); 568 | let mut tmp = Vec::with_capacity(100); 569 | for _ in 0..100 { 570 | tmp.clear(); 571 | let mut ih = IntervalHeap::from(tmp); 572 | for _ in 0..100 { 573 | ih.push(rng.next_u32()); 574 | } 575 | let mut tmpx: Option = None; 576 | loop { 577 | let tmpy = ih.pop_max(); 578 | match (tmpx, tmpy) { 579 | (_, None) => break, 580 | (Some(x), Some(y)) => assert!(x >= y), 581 | _ => () 582 | } 583 | tmpx = tmpy; 584 | } 585 | tmp = ih.into_vec(); 586 | } 587 | } 588 | 589 | #[test] 590 | fn test_from_vec() { 591 | let heap = IntervalHeap::::from(vec![]); 592 | assert_eq!(heap.min_max(), None); 593 | 594 | let heap = IntervalHeap::from(vec![2]); 595 | assert_eq!(heap.min_max(), Some((&2, &2))); 596 | 597 | let heap = IntervalHeap::from(vec![2, 1]); 598 | assert_eq!(heap.min_max(), Some((&1, &2))); 599 | 600 | let heap = IntervalHeap::from(vec![2, 1, 3]); 601 | assert_eq!(heap.min_max(), Some((&1, &3))); 602 | } 603 | 604 | #[test] 605 | fn test_is_valid() { 606 | fn new(data: Vec) -> IntervalHeap { 607 | IntervalHeap { data: data, cmp: ::compare::natural() } 608 | } 609 | 610 | assert!(new(vec![]).is_valid()); 611 | assert!(new(vec![1]).is_valid()); 612 | assert!(new(vec![1, 1]).is_valid()); 613 | assert!(new(vec![1, 5]).is_valid()); 614 | assert!(new(vec![1, 5, 1]).is_valid()); 615 | assert!(new(vec![1, 5, 1, 1]).is_valid()); 616 | assert!(new(vec![1, 5, 5]).is_valid()); 617 | assert!(new(vec![1, 5, 5, 5]).is_valid()); 618 | assert!(new(vec![1, 5, 2, 4]).is_valid()); 619 | assert!(new(vec![1, 5, 2, 4, 3]).is_valid()); 620 | assert!(new(vec![1, 5, 2, 4, 3, 3]).is_valid()); 621 | 622 | assert!(!new(vec![2, 1]).is_valid()); // violates 2a 623 | assert!(!new(vec![1, 5, 4, 3]).is_valid()); // violates 2a 624 | assert!(!new(vec![1, 5, 0]).is_valid()); // violates 2b 625 | assert!(!new(vec![1, 5, 0, 5]).is_valid()); // violates 2b 626 | assert!(!new(vec![1, 5, 6]).is_valid()); // violates 2c 627 | assert!(!new(vec![1, 5, 1, 6]).is_valid()); // violates 2c 628 | assert!(!new(vec![1, 5, 0, 6]).is_valid()); // violates 2b and 2c 629 | } 630 | } 631 | --------------------------------------------------------------------------------