priority_queue/double_priority_queue/mod.rs
1/*
2 * Copyright 2017 Gianmarco Garrisi
3 *
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version, or (at your option) under the terms
9 * of the Mozilla Public License version 2.0.
10 *
11 * ----
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 *
21 * ----
22 *
23 * This Source Code Form is subject to the terms of the Mozilla Public License,
24 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
25 * obtain one at http://mozilla.org/MPL/2.0/.
26 *
27 */
28//! This module contains the [`DoublePriorityQueue`] type and the related iterators.
29//!
30//! See the type level documentation for more details and examples.
31
32pub mod iterators;
33
34#[cfg(not(feature = "std"))]
35use std::vec::Vec;
36
37use crate::TryReserveError;
38use crate::core_iterators::*;
39use crate::store::{Index, Position, Store};
40use iterators::*;
41
42use std::borrow::Borrow;
43use std::cmp::{Eq, Ord};
44#[cfg(feature = "std")]
45use std::collections::hash_map::RandomState;
46use std::hash::{BuildHasher, Hash};
47use std::iter::{Extend, FromIterator, IntoIterator, Iterator};
48use std::mem::replace;
49
50/// A double priority queue with efficient change function to change the priority of an
51/// element.
52///
53/// The priority is of type P, that must implement `std::cmp::Ord`.
54///
55/// The item is of type I, that must implement `Hash` and `Eq`.
56///
57/// Implemented as a heap of indexes, stores the items inside an `IndexMap`
58/// to be able to retrieve them quickly.
59///
60/// With this data structure it is possible to efficiently extract both
61/// the maximum and minimum elements arbitrarily.
62///
63/// If your need is to always extract the minimum, use a
64/// `PriorityQueue<I, Reverse<P>>` wrapping
65/// your priorities in the standard wrapper
66/// [`Reverse<T>`](https://doc.rust-lang.org/std/cmp/struct.Reverse.html).
67///
68///
69/// # Example
70/// ```rust
71/// use priority_queue::DoublePriorityQueue;
72///
73/// let mut pq = DoublePriorityQueue::new();
74///
75/// assert!(pq.is_empty());
76/// pq.push("Apples", 5);
77/// pq.push("Bananas", 8);
78/// pq.push("Strawberries", 23);
79///
80/// assert_eq!(pq.peek_max(), Some((&"Strawberries", &23)));
81/// assert_eq!(pq.peek_min(), Some((&"Apples", &5)));
82///
83/// pq.change_priority("Bananas", 25);
84/// assert_eq!(pq.peek_max(), Some((&"Bananas", &25)));
85///
86/// for (item, _) in pq.into_sorted_iter() {
87/// println!("{}", item);
88/// }
89/// ```
90#[derive(Clone)]
91#[cfg(feature = "std")]
92pub struct DoublePriorityQueue<I, P, H = RandomState> {
93 pub(crate) store: Store<I, P, H>,
94}
95
96#[derive(Clone)]
97#[cfg(not(feature = "std"))]
98pub struct DoublePriorityQueue<I, P, H> {
99 pub(crate) store: Store<I, P, H>,
100}
101
102// do not [derive(Eq)] to loosen up trait requirements for other types and impls
103impl<I, P, H> Eq for DoublePriorityQueue<I, P, H>
104where
105 I: Hash + Eq,
106 P: Ord,
107 H: BuildHasher,
108{
109}
110
111impl<I, P, H> Default for DoublePriorityQueue<I, P, H>
112where
113 I: Hash + Eq,
114 P: Ord,
115 H: BuildHasher + Default,
116{
117 fn default() -> Self {
118 Self::with_default_hasher()
119 }
120}
121
122#[cfg(feature = "std")]
123impl<I, P> DoublePriorityQueue<I, P>
124where
125 P: Ord,
126 I: Hash + Eq,
127{
128 /// Creates an empty `DoublePriorityQueue`
129 pub fn new() -> Self {
130 Self::with_capacity(0)
131 }
132
133 /// Creates an empty `DoublePriorityQueue` with the specified capacity.
134 pub fn with_capacity(capacity: usize) -> Self {
135 Self::with_capacity_and_default_hasher(capacity)
136 }
137}
138
139impl<I, P, H> DoublePriorityQueue<I, P, H>
140where
141 P: Ord,
142 I: Hash + Eq,
143 H: BuildHasher + Default,
144{
145 /// Creates an empty `DoublePriorityQueue` with the default hasher
146 pub fn with_default_hasher() -> Self {
147 Self::with_capacity_and_default_hasher(0)
148 }
149
150 /// Creates an empty `DoublePriorityQueue` with the specified capacity and default hasher
151 pub fn with_capacity_and_default_hasher(capacity: usize) -> Self {
152 Self::with_capacity_and_hasher(capacity, H::default())
153 }
154}
155
156impl<I, P, H> DoublePriorityQueue<I, P, H>
157where
158 P: Ord,
159 I: Hash + Eq,
160 H: BuildHasher,
161{
162 /// Creates an empty `DoublePriorityQueue` with the specified hasher
163 pub fn with_hasher(hash_builder: H) -> Self {
164 Self::with_capacity_and_hasher(0, hash_builder)
165 }
166
167 /// Creates an empty `DoublePriorityQueue` with the specified capacity and hasher
168 ///
169 /// The internal collections will be able to hold at least `capacity`
170 /// elements without reallocating.
171 /// If `capacity` is 0, there will be no allocation.
172 pub fn with_capacity_and_hasher(capacity: usize, hash_builder: H) -> Self {
173 Self {
174 store: Store::with_capacity_and_hasher(capacity, hash_builder),
175 }
176 }
177}
178
179impl<I, P, H> DoublePriorityQueue<I, P, H> {
180 /// Returns the number of elements the internal map can hold without
181 /// reallocating.
182 ///
183 /// This number is a lower bound; the map might be able to hold more,
184 /// but is guaranteed to be able to hold at least this many.
185 pub fn capacity(&self) -> usize {
186 self.store.capacity()
187 }
188
189 /// Returns an iterator in arbitrary order over the
190 /// (item, priority) elements in the queue
191 pub fn iter(&self) -> Iter<I, P> {
192 self.store.iter()
193 }
194
195 /// Clears the PriorityQueue, returning an iterator over the removed elements in arbitrary order.
196 /// If the iterator is dropped before being fully consumed, it drops the remaining elements in arbitrary order.
197 pub fn drain(&mut self) -> Drain<I, P> {
198 self.store.drain()
199 }
200
201 /// Shrinks the capacity of the internal data structures
202 /// that support this operation as much as possible.
203 pub fn shrink_to_fit(&mut self) {
204 self.store.shrink_to_fit();
205 }
206
207 /// Returns the number of elements in the priority queue.
208 #[inline]
209 pub fn len(&self) -> usize {
210 self.store.len()
211 }
212
213 /// Returns true if the priority queue contains no elements.
214 pub fn is_empty(&self) -> bool {
215 self.store.is_empty()
216 }
217
218 /// Returns the couple (item, priority) with the lowest
219 /// priority in the queue, or None if it is empty.
220 ///
221 /// Computes in **O(1)** time
222 pub fn peek_min(&self) -> Option<(&I, &P)> {
223 self.find_min().and_then(|i| {
224 self.store
225 .map
226 .get_index(unsafe { *self.store.heap.get_unchecked(i.0) }.0)
227 })
228 }
229
230 /// Reserves capacity for at least `additional` more elements to be inserted
231 /// in the given `DoublePriorityQueue`. The collection may reserve more space to avoid
232 /// frequent reallocations. After calling `reserve`, capacity will be
233 /// greater than or equal to `self.len() + additional`. Does nothing if
234 /// capacity is already sufficient.
235 ///
236 /// # Panics
237 ///
238 /// Panics if the new capacity overflows `usize`.
239 pub fn reserve(&mut self, additional: usize) {
240 self.store.reserve(additional);
241 }
242
243 /// Reserve capacity for `additional` more elements, without over-allocating.
244 ///
245 /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid
246 /// frequent re-allocations. However, the underlying data structures may still have internal
247 /// capacity requirements, and the allocator itself may give more space than requested, so this
248 /// cannot be relied upon to be precisely minimal.
249 ///
250 /// Computes in **O(n)** time.
251 pub fn reserve_exact(&mut self, additional: usize) {
252 self.store.reserve_exact(additional);
253 }
254
255 /// Try to reserve capacity for at least `additional` more elements.
256 ///
257 /// Computes in O(n) time.
258 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
259 self.store.try_reserve(additional)
260 }
261
262 /// Try to reserve capacity for `additional` more elements, without over-allocating.
263 ///
264 /// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid
265 /// frequent re-allocations. However, the underlying data structures may still have internal
266 /// capacity requirements, and the allocator itself may give more space than requested, so this
267 /// cannot be relied upon to be precisely minimal.
268 ///
269 /// Computes in **O(n)** time.
270 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
271 self.store.try_reserve_exact(additional)
272 }
273}
274impl<I, P, H> DoublePriorityQueue<I, P, H>
275where
276 P: Ord,
277{
278 /// Return an iterator in arbitrary order over the
279 /// (item, priority) elements in the queue.
280 ///
281 /// The item and the priority are mutable references, but it's a logic error
282 /// to modify the item in a way that change the result of `Hash` or `Eq`.
283 ///
284 /// It's *not* an error, instead, to modify the priorities, because the heap
285 /// will be rebuilt once the `IterMut` goes out of scope. It would be
286 /// rebuilt even if no priority value would have been modified, but the
287 /// procedure will not move anything, but just compare the priorities.
288 pub fn iter_mut(&mut self) -> IterMut<I, P, H> {
289 IterMut::new(self)
290 }
291
292 /// Returns the couple (item, priority) with the greatest
293 /// priority in the queue, or None if it is empty.
294 ///
295 /// Computes in **O(1)** time
296 pub fn peek_max(&self) -> Option<(&I, &P)> {
297 self.find_max().and_then(|i| {
298 self.store
299 .map
300 .get_index(unsafe { *self.store.heap.get_unchecked(i.0) }.0)
301 })
302 }
303
304 /// Removes the item with the lowest priority from
305 /// the priority queue and returns the pair (item, priority),
306 /// or None if the queue is empty.
307 pub fn pop_min(&mut self) -> Option<(I, P)> {
308 self.find_min().and_then(|i| {
309 let r = self.store.swap_remove(i);
310 self.heapify(i);
311 r
312 })
313 }
314
315 /// Removes the item with the greatest priority from
316 /// the priority queue and returns the pair (item, priority),
317 /// or None if the queue is empty.
318 pub fn pop_max(&mut self) -> Option<(I, P)> {
319 self.find_max().and_then(|i| {
320 let r = self.store.swap_remove(i);
321 self.heapify(i);
322 r
323 })
324 }
325
326 /// Implements a HeapSort.
327 ///
328 /// Consumes the PriorityQueue and returns a vector
329 /// with all the items sorted from the one associated to
330 /// the lowest priority to the highest.
331 pub fn into_ascending_sorted_vec(mut self) -> Vec<I> {
332 let mut res = Vec::with_capacity(self.store.size);
333 while let Some((i, _)) = self.pop_min() {
334 res.push(i);
335 }
336 res
337 }
338
339 /// Implements a HeapSort
340 ///
341 /// Consumes the PriorityQueue and returns a vector
342 /// with all the items sorted from the one associated to
343 /// the highest priority to the lowest.
344 pub fn into_descending_sorted_vec(mut self) -> Vec<I> {
345 let mut res = Vec::with_capacity(self.store.size);
346 while let Some((i, _)) = self.pop_max() {
347 res.push(i);
348 }
349 res
350 }
351
352 /// Generates a new double ended iterator from self that
353 /// will extract the elements from the one with the lowest priority
354 /// to the highest one.
355 pub fn into_sorted_iter(self) -> IntoSortedIter<I, P, H> {
356 IntoSortedIter { pq: self }
357 }
358}
359
360impl<I, P, H> DoublePriorityQueue<I, P, H>
361where
362 H: BuildHasher,
363{
364 /// Returns the couple (item, priority) with the lowest
365 /// priority in the queue, or None if it is empty.
366 ///
367 /// The item is a mutable reference, but it's a logic error to modify it
368 /// in a way that change the result of `Hash` or `Eq`.
369 ///
370 /// The priority cannot be modified with a call to this function.
371 /// To modify the priority use [`push`](DoublePriorityQueue::push),
372 /// [`change_priority`](DoublePriorityQueue::change_priority) or
373 /// [`change_priority_by`](DoublePriorityQueue::change_priority_by).
374 ///
375 /// Computes in **O(1)** time
376 pub fn peek_min_mut(&mut self) -> Option<(&mut I, &P)> {
377 use indexmap::map::MutableKeys;
378
379 self.find_min()
380 .and_then(move |i| {
381 self.store
382 .map
383 .get_index_mut2(unsafe { *self.store.heap.get_unchecked(i.0) }.0)
384 })
385 .map(|(k, v)| (k, &*v))
386 }
387}
388
389impl<I, P, H> DoublePriorityQueue<I, P, H>
390where
391 P: Ord,
392 H: BuildHasher,
393{
394 /// Returns the couple (item, priority) with the greatest
395 /// priority in the queue, or None if it is empty.
396 ///
397 /// The item is a mutable reference, but it's a logic error to modify it
398 /// in a way that change the result of `Hash` or `Eq`.
399 ///
400 /// The priority cannot be modified with a call to this function.
401 /// To modify the priority use [`push`](DoublePriorityQueue::push),
402 /// [`change_priority`](DoublePriorityQueue::change_priority) or
403 /// [`change_priority_by`](DoublePriorityQueue::change_priority_by).
404 ///
405 /// Computes in **O(1)** time
406 pub fn peek_max_mut(&mut self) -> Option<(&mut I, &P)> {
407 use indexmap::map::MutableKeys;
408 self.find_max()
409 .and_then(move |i| {
410 self.store
411 .map
412 .get_index_mut2(unsafe { *self.store.heap.get_unchecked(i.0) }.0)
413 })
414 .map(|(k, v)| (k, &*v))
415 }
416}
417
418impl<I, P, H> DoublePriorityQueue<I, P, H>
419where
420 P: Ord,
421 I: Hash + Eq,
422 H: BuildHasher,
423{
424 /// Removes the item with the lowest priority from
425 /// the priority queue if the predicate returns `true`.
426 ///
427 /// Returns the pair (item, priority), or None if the
428 /// queue is empty or the predicate returns `false`.
429 ///
430 /// The predicate receives mutable references to both the item and
431 /// the priority.
432 ///
433 /// It's a logical error to change the item in a way
434 /// that changes the result of `Hash` or `EQ`.
435 ///
436 /// The predicate can change the priority. If it returns true, the
437 /// returned couple will have the updated priority, otherwise, the
438 /// heap structural property will be restored.
439 ///
440 /// # Example
441 /// ```
442 /// # use priority_queue::DoublePriorityQueue;
443 /// let mut pq = DoublePriorityQueue::new();
444 /// pq.push("Apples", 5);
445 /// pq.push("Bananas", 10);
446 /// assert_eq!(pq.pop_min_if(|i, p| {
447 /// *p = 15;
448 /// false
449 /// }), None);
450 /// assert_eq!(pq.pop_min(), Some(("Bananas", 10)));
451 /// ```
452 pub fn pop_min_if<F>(&mut self, f: F) -> Option<(I, P)>
453 where
454 F: FnOnce(&mut I, &mut P) -> bool,
455 {
456 self.find_min().and_then(|i| {
457 let r = self.store.swap_remove_if(i, f);
458 self.heapify(i);
459 r
460 })
461 }
462
463 /// Removes the item with the greatest priority from
464 /// the priority queue if the predicate returns `true`.
465 ///
466 /// Returns the pair (item, priority), or None if the
467 /// queue is empty or the predicate returns `false`.
468 ///
469 /// The predicate receives mutable references to both the item and
470 /// the priority.
471 ///
472 /// It's a logical error to change the item in a way
473 /// that changes the result of `Hash` or `EQ`.
474 ///
475 /// The predicate can change the priority. If it returns true, the
476 /// returned couple will have the updated priority, otherwise, the
477 /// heap structural property will be restored.
478 ///
479 /// # Example
480 /// ```
481 /// # use priority_queue::DoublePriorityQueue;
482 /// let mut pq = DoublePriorityQueue::new();
483 /// pq.push("Apples", 5);
484 /// pq.push("Bananas", 10);
485 /// assert_eq!(pq.pop_max_if(|i, p| {
486 /// *p = 3;
487 /// false
488 /// }), None);
489 /// assert_eq!(pq.pop_max(), Some(("Apples", 5)));
490 /// ```
491 pub fn pop_max_if<F>(&mut self, f: F) -> Option<(I, P)>
492 where
493 F: FnOnce(&mut I, &mut P) -> bool,
494 {
495 self.find_max().and_then(|i| {
496 let r = self.store.swap_remove_if(i, f);
497 self.up_heapify(i);
498 r
499 })
500 }
501
502 /// Insert the item-priority pair into the queue.
503 ///
504 /// If an element equal to `item` is already in the queue, its priority
505 /// is updated and the old priority is returned in `Some`; otherwise,
506 /// `item` is inserted with `priority` and `None` is returned.
507 ///
508 /// # Example
509 /// ```
510 /// # use priority_queue::DoublePriorityQueue;
511 /// let mut pq = DoublePriorityQueue::new();
512 /// assert_eq!(pq.push("Apples", 5), None);
513 /// assert_eq!(pq.get_priority("Apples"), Some(&5));
514 /// assert_eq!(pq.push("Apples", 6), Some(5));
515 /// assert_eq!(pq.get_priority("Apples"), Some(&6));
516 /// assert_eq!(pq.push("Apples", 4), Some(6));
517 /// assert_eq!(pq.get_priority("Apples"), Some(&4));
518 /// ```
519 ///
520 /// Computes in **O(log(N))** time.
521 pub fn push(&mut self, item: I, priority: P) -> Option<P> {
522 use indexmap::map::Entry::*;
523 let mut pos = Position(0);
524 let mut oldp = None;
525
526 match self.store.map.entry(item) {
527 Occupied(mut e) => {
528 oldp = Some(replace(e.get_mut(), priority));
529 pos = unsafe { *self.store.qp.get_unchecked(e.index()) };
530 }
531 Vacant(e) => {
532 e.insert(priority);
533 }
534 }
535
536 if oldp.is_some() {
537 self.up_heapify(pos);
538 return oldp;
539 }
540 // get a reference to the priority
541 // copy the current size of the heap
542 let i = self.len();
543 // add the new element in the qp vector as the last in the heap
544 self.store.qp.push(Position(i));
545 self.store.heap.push(Index(i));
546 self.bubble_up(Position(i), Index(i));
547 self.store.size += 1;
548 None
549 }
550
551 /// Increase the priority of an existing item in the queue, or
552 /// insert it if not present.
553 ///
554 /// If an element equal to `item` is already in the queue with a
555 /// lower priority, its priority is increased to the new one
556 /// without replacing the element and the old priority is returned
557 /// in `Some`.
558 ///
559 /// If an element equal to `item` is already in the queue with an
560 /// equal or higher priority, its priority is not changed and the
561 /// `priority` argument is returned in `Some`.
562 ///
563 /// If no element equal to `item` is already in the queue, the new
564 /// element is inserted and `None` is returned.
565 ///
566 /// # Example
567 /// ```
568 /// # use priority_queue::DoublePriorityQueue;
569 /// let mut pq = DoublePriorityQueue::new();
570 /// assert_eq!(pq.push_increase("Apples", 5), None);
571 /// assert_eq!(pq.get_priority("Apples"), Some(&5));
572 /// assert_eq!(pq.push_increase("Apples", 6), Some(5));
573 /// assert_eq!(pq.get_priority("Apples"), Some(&6));
574 /// // Already present with higher priority, so requested (lower)
575 /// // priority is returned.
576 /// assert_eq!(pq.push_increase("Apples", 4), Some(4));
577 /// assert_eq!(pq.get_priority("Apples"), Some(&6));
578 /// ```
579 ///
580 /// Computes in **O(log(N))** time.
581 pub fn push_increase(&mut self, item: I, priority: P) -> Option<P> {
582 if self.get_priority(&item).is_none_or(|p| priority > *p) {
583 self.push(item, priority)
584 } else {
585 Some(priority)
586 }
587 }
588
589 /// Decrease the priority of an existing item in the queue, or
590 /// insert it if not present.
591 ///
592 /// If an element equal to `item` is already in the queue with a
593 /// higher priority, its priority is decreased to the new one
594 /// without replacing the element and the old priority is returned
595 /// in `Some`.
596 ///
597 /// If an element equal to `item` is already in the queue with an
598 /// equal or lower priority, its priority is not changed and the
599 /// `priority` argument is returned in `Some`.
600 ///
601 /// If no element equal to `item` is already in the queue, the new
602 /// element is inserted and `None` is returned.
603 ///
604 /// # Example
605 /// ```
606 /// # use priority_queue::DoublePriorityQueue;
607 /// let mut pq = DoublePriorityQueue::new();
608 /// assert_eq!(pq.push_decrease("Apples", 5), None);
609 /// assert_eq!(pq.get_priority("Apples"), Some(&5));
610 /// assert_eq!(pq.push_decrease("Apples", 4), Some(5));
611 /// assert_eq!(pq.get_priority("Apples"), Some(&4));
612 /// // Already present with lower priority, so requested (higher)
613 /// // priority is returned.
614 /// assert_eq!(pq.push_decrease("Apples", 6), Some(6));
615 /// assert_eq!(pq.get_priority("Apples"), Some(&4));
616 /// ```
617 ///
618 /// Computes in **O(log(N))** time.
619 pub fn push_decrease(&mut self, item: I, priority: P) -> Option<P> {
620 if self.get_priority(&item).is_none_or(|p| priority < *p) {
621 self.push(item, priority)
622 } else {
623 Some(priority)
624 }
625 }
626
627 /// Change the priority of an Item returning the old value of priority,
628 /// or `None` if the item wasn't in the queue.
629 ///
630 /// The argument `item` is only used for lookup, and is not used to overwrite the item's data
631 /// in the priority queue.
632 ///
633 /// # Example
634 /// ```
635 /// # use priority_queue::DoublePriorityQueue;
636 /// let mut pq = DoublePriorityQueue::new();
637 /// assert_eq!(pq.change_priority("Apples", 5), None);
638 /// assert_eq!(pq.get_priority("Apples"), None);
639 /// assert_eq!(pq.push("Apples", 6), None);
640 /// assert_eq!(pq.get_priority("Apples"), Some(&6));
641 /// assert_eq!(pq.change_priority("Apples", 4), Some(6));
642 /// assert_eq!(pq.get_priority("Apples"), Some(&4));
643 /// ```
644 ///
645 /// The item is found in **O(1)** thanks to the hash table.
646 /// The operation is performed in **O(log(N))** time.
647 pub fn change_priority<Q>(&mut self, item: &Q, new_priority: P) -> Option<P>
648 where
649 I: Borrow<Q>,
650 Q: Eq + Hash + ?Sized,
651 {
652 self.store
653 .change_priority(item, new_priority)
654 .map(|(r, pos)| {
655 self.up_heapify(pos);
656 r
657 })
658 }
659
660 /// Change the priority of an Item using the provided function.
661 /// Return a boolean value where `true` means the item was in the queue and update was successful
662 ///
663 /// The argument `item` is only used for lookup, and is not used to overwrite the item's data
664 /// in the priority queue.
665 ///
666 /// The item is found in **O(1)** thanks to the hash table.
667 /// The operation is performed in **O(log(N))** time (worst case).
668 pub fn change_priority_by<Q, F>(&mut self, item: &Q, priority_setter: F) -> bool
669 where
670 I: Borrow<Q>,
671 Q: Eq + Hash + ?Sized,
672 F: FnOnce(&mut P),
673 {
674 self.store
675 .change_priority_by(item, priority_setter)
676 .map(|pos| {
677 self.up_heapify(pos);
678 })
679 .is_some()
680 }
681
682 /// Get the priority of an item, or `None`, if the item is not in the queue
683 pub fn get_priority<Q>(&self, item: &Q) -> Option<&P>
684 where
685 I: Borrow<Q>,
686 Q: Eq + Hash + ?Sized,
687 {
688 self.store.get_priority(item)
689 }
690
691 /// Get the couple (item, priority) of an arbitrary element, as reference
692 /// or `None` if the item is not in the queue.
693 pub fn get<Q>(&self, item: &Q) -> Option<(&I, &P)>
694 where
695 I: Borrow<Q>,
696 Q: Eq + Hash + ?Sized,
697 {
698 self.store.get(item)
699 }
700
701 /// Get the couple (item, priority) of an arbitrary element, or `None`
702 /// if the item was not in the queue.
703 ///
704 /// The item is a mutable reference, but it's a logic error to modify it
705 /// in a way that change the result of `Hash` or `Eq`.
706 ///
707 /// The priority cannot be modified with a call to this function.
708 /// To modify the priority use use [`push`](DoublePriorityQueue::push),
709 /// [`change_priority`](DoublePriorityQueue::change_priority) or
710 /// [`change_priority_by`](DoublePriorityQueue::change_priority_by).
711 pub fn get_mut<Q>(&mut self, item: &Q) -> Option<(&mut I, &P)>
712 where
713 I: Borrow<Q>,
714 Q: Eq + Hash + ?Sized,
715 {
716 self.store.get_mut(item)
717 }
718
719 /// Remove an arbitrary element from the priority queue.
720 /// Returns the (item, priority) couple or None if the item
721 /// is not found in the queue.
722 ///
723 /// The operation is performed in **O(log(N))** time (worst case).
724 pub fn remove<Q>(&mut self, item: &Q) -> Option<(I, P)>
725 where
726 I: Borrow<Q>,
727 Q: Eq + Hash + ?Sized,
728 {
729 self.store.remove(item).map(|(item, priority, pos)| {
730 if pos.0 < self.len() {
731 self.up_heapify(pos);
732 }
733
734 (item, priority)
735 })
736 }
737
738 /// Returns the items not ordered
739 pub fn into_vec(self) -> Vec<I> {
740 self.store.into_vec()
741 }
742
743 /// Drops all items from the priority queue
744 pub fn clear(&mut self) {
745 self.store.clear();
746 }
747
748 /// Move all items of the `other` queue to `self`
749 /// ignoring the items Eq to elements already in `self`
750 /// At the end, `other` will be empty.
751 ///
752 /// **Note** that at the end, the priority of the duplicated elements
753 /// inside `self` may be the one of the elements in `other`,
754 /// if `other` is longer than `self`
755 pub fn append(&mut self, other: &mut Self) {
756 self.store.append(&mut other.store);
757 self.heap_build();
758 }
759}
760
761impl<I, P, H> DoublePriorityQueue<I, P, H> {
762 /// Returns the index of the min element
763 fn find_min(&self) -> Option<Position> {
764 match self.len() {
765 0 => None,
766 _ => Some(Position(0)),
767 }
768 }
769}
770
771impl<I, P, H> DoublePriorityQueue<I, P, H>
772where
773 P: Ord,
774{
775 /**************************************************************************/
776 /* internal functions */
777
778 fn heapify(&mut self, i: Position) {
779 if self.len() <= 1 {
780 return;
781 }
782 if level(i) % 2 == 0 {
783 self.heapify_min(i)
784 } else {
785 self.heapify_max(i)
786 }
787 }
788
789 fn heapify_min(&mut self, mut i: Position) {
790 while i <= parent(Position(self.len() - 1)) {
791 let m = i;
792
793 let l = left(i);
794 let r = right(i);
795 // Minimum of childs and grandchilds
796 i = *[l, r, left(l), right(l), left(r), right(r)]
797 .iter()
798 .map_while(|i| self.store.heap.get(i.0).map(|index| (i, index)))
799 .min_by_key(|(_, index)| {
800 self.store
801 .map
802 .get_index(index.0)
803 .map(|(_, priority)| priority)
804 .unwrap()
805 })
806 .unwrap()
807 .0;
808
809 if unsafe {
810 self.store.get_priority_from_position(i) < self.store.get_priority_from_position(m)
811 } {
812 self.store.swap(i, m);
813 if i > r {
814 // i is a grandchild of m
815 let p = parent(i);
816 if unsafe {
817 self.store.get_priority_from_position(i)
818 > self.store.get_priority_from_position(p)
819 } {
820 self.store.swap(i, p);
821 }
822 } else {
823 break;
824 }
825 } else {
826 break;
827 }
828 }
829 }
830
831 fn heapify_max(&mut self, mut i: Position) {
832 while i <= parent(Position(self.len() - 1)) {
833 let m = i;
834
835 let l = left(i);
836 let r = right(i);
837 // Minimum of childs and grandchilds
838 i = *[l, r, left(l), right(l), left(r), right(r)]
839 .iter()
840 .map_while(|i| self.store.heap.get(i.0).map(|index| (i, index)))
841 .max_by_key(|(_, index)| {
842 self.store
843 .map
844 .get_index(index.0)
845 .map(|(_, priority)| priority)
846 .unwrap()
847 })
848 .unwrap()
849 .0;
850
851 if unsafe {
852 self.store.get_priority_from_position(i) > self.store.get_priority_from_position(m)
853 } {
854 self.store.swap(i, m);
855 if i > r {
856 // i is a grandchild of m
857 let p = parent(i);
858 if unsafe {
859 self.store.get_priority_from_position(i)
860 < self.store.get_priority_from_position(p)
861 } {
862 self.store.swap(i, p);
863 }
864 } else {
865 break;
866 }
867 } else {
868 break;
869 }
870 }
871 }
872
873 fn bubble_up(&mut self, mut position: Position, map_position: Index) -> Position {
874 let priority = self.store.map.get_index(map_position.0).unwrap().1;
875 if position.0 > 0 {
876 let parent = parent(position);
877 let parent_priority = unsafe { self.store.get_priority_from_position(parent) };
878 let parent_index = unsafe { *self.store.heap.get_unchecked(parent.0) };
879 position = match (level(position) % 2 == 0, parent_priority < priority) {
880 // on a min level and greater then parent
881 (true, true) => {
882 unsafe {
883 *self.store.heap.get_unchecked_mut(position.0) = parent_index;
884 *self.store.qp.get_unchecked_mut(parent_index.0) = position;
885 }
886 self.bubble_up_max(parent, map_position)
887 }
888 // on a min level and less then parent
889 (true, false) => self.bubble_up_min(position, map_position),
890 // on a max level and greater then parent
891 (false, true) => self.bubble_up_max(position, map_position),
892 // on a max level and less then parent
893 (false, false) => {
894 unsafe {
895 *self.store.heap.get_unchecked_mut(position.0) = parent_index;
896 *self.store.qp.get_unchecked_mut(parent_index.0) = position;
897 }
898 self.bubble_up_min(parent, map_position)
899 }
900 }
901 }
902
903 unsafe {
904 // put the new element into the heap and
905 // update the qp translation table and the size
906 *self.store.heap.get_unchecked_mut(position.0) = map_position;
907 *self.store.qp.get_unchecked_mut(map_position.0) = position;
908 }
909 position
910 }
911
912 fn bubble_up_min(&mut self, mut position: Position, map_position: Index) -> Position {
913 let priority = self.store.map.get_index(map_position.0).unwrap().1;
914 let mut grand_parent = Position(0);
915 while if position.0 > 0 && parent(position).0 > 0 {
916 grand_parent = parent(parent(position));
917 (unsafe { self.store.get_priority_from_position(grand_parent) }) > priority
918 } else {
919 false
920 } {
921 unsafe {
922 let grand_parent_index = *self.store.heap.get_unchecked(grand_parent.0);
923 *self.store.heap.get_unchecked_mut(position.0) = grand_parent_index;
924 *self.store.qp.get_unchecked_mut(grand_parent_index.0) = position;
925 }
926 position = grand_parent;
927 }
928 position
929 }
930
931 fn bubble_up_max(&mut self, mut position: Position, map_position: Index) -> Position {
932 let priority = self.store.map.get_index(map_position.0).unwrap().1;
933 let mut grand_parent = Position(0);
934 while if position.0 > 0 && parent(position).0 > 0 {
935 grand_parent = parent(parent(position));
936 (unsafe { self.store.get_priority_from_position(grand_parent) }) < priority
937 } else {
938 false
939 } {
940 unsafe {
941 let grand_parent_index = *self.store.heap.get_unchecked(grand_parent.0);
942 *self.store.heap.get_unchecked_mut(position.0) = grand_parent_index;
943 *self.store.qp.get_unchecked_mut(grand_parent_index.0) = position;
944 }
945 position = grand_parent;
946 }
947 position
948 }
949
950 fn up_heapify(&mut self, i: Position) {
951 let tmp = unsafe { *self.store.heap.get_unchecked(i.0) };
952 let pos = self.bubble_up(i, tmp);
953 if i != pos {
954 self.heapify(i)
955 }
956 self.heapify(pos);
957 }
958
959 /// Internal function that transform the `heap`
960 /// vector in a heap with its properties
961 ///
962 /// Computes in **O(N)**
963 pub(crate) fn heap_build(&mut self) {
964 if self.is_empty() {
965 return;
966 }
967 for i in (0..=parent(Position(self.len())).0).rev() {
968 self.heapify(Position(i));
969 }
970 }
971
972 /// Returns the index of the max element
973 fn find_max(&self) -> Option<Position> {
974 match self.len() {
975 0 => None,
976 1 => Some(Position(0)),
977 2 => Some(Position(1)),
978 _ => Some(
979 *[Position(1), Position(2)]
980 .iter()
981 .max_by_key(|i| unsafe { self.store.get_priority_from_position(**i) })
982 .unwrap(),
983 ),
984 }
985 }
986}
987
988//FIXME: fails when the vector contains repeated items
989// FIXED: repeated items ignored
990impl<I, P, H> From<Vec<(I, P)>> for DoublePriorityQueue<I, P, H>
991where
992 I: Hash + Eq,
993 P: Ord,
994 H: BuildHasher + Default,
995{
996 fn from(vec: Vec<(I, P)>) -> Self {
997 let store = Store::from(vec);
998 let mut pq = DoublePriorityQueue { store };
999 pq.heap_build();
1000 pq
1001 }
1002}
1003
1004use crate::PriorityQueue;
1005
1006impl<I, P, H> From<PriorityQueue<I, P, H>> for DoublePriorityQueue<I, P, H>
1007where
1008 I: Hash + Eq,
1009 P: Ord,
1010 H: BuildHasher,
1011{
1012 fn from(pq: PriorityQueue<I, P, H>) -> Self {
1013 let store = pq.store;
1014 let mut this = Self { store };
1015 this.heap_build();
1016 this
1017 }
1018}
1019
1020//FIXME: fails when the iterator contains repeated items
1021// FIXED: the item inside the pq is updated
1022// so there are two functions with different behaviours.
1023impl<I, P, H> FromIterator<(I, P)> for DoublePriorityQueue<I, P, H>
1024where
1025 I: Hash + Eq,
1026 P: Ord,
1027 H: BuildHasher + Default,
1028{
1029 fn from_iter<IT>(iter: IT) -> Self
1030 where
1031 IT: IntoIterator<Item = (I, P)>,
1032 {
1033 let store = Store::from_iter(iter);
1034 let mut pq = DoublePriorityQueue { store };
1035 pq.heap_build();
1036 pq
1037 }
1038}
1039
1040impl<I, P, H> IntoIterator for DoublePriorityQueue<I, P, H>
1041where
1042 I: Hash + Eq,
1043 P: Ord,
1044 H: BuildHasher,
1045{
1046 type Item = (I, P);
1047 type IntoIter = IntoIter<I, P>;
1048 fn into_iter(self) -> IntoIter<I, P> {
1049 self.store.into_iter()
1050 }
1051}
1052
1053impl<'a, I, P, H> IntoIterator for &'a DoublePriorityQueue<I, P, H>
1054where
1055 I: Hash + Eq,
1056 P: Ord,
1057 H: BuildHasher,
1058{
1059 type Item = (&'a I, &'a P);
1060 type IntoIter = Iter<'a, I, P>;
1061 fn into_iter(self) -> Iter<'a, I, P> {
1062 self.store.iter()
1063 }
1064}
1065
1066impl<'a, I, P, H> IntoIterator for &'a mut DoublePriorityQueue<I, P, H>
1067where
1068 I: Hash + Eq,
1069 P: Ord,
1070 H: BuildHasher,
1071{
1072 type Item = (&'a mut I, &'a mut P);
1073 type IntoIter = IterMut<'a, I, P, H>;
1074 fn into_iter(self) -> IterMut<'a, I, P, H> {
1075 IterMut::new(self)
1076 }
1077}
1078
1079impl<I, P, H> Extend<(I, P)> for DoublePriorityQueue<I, P, H>
1080where
1081 I: Hash + Eq,
1082 P: Ord,
1083 H: BuildHasher,
1084{
1085 fn extend<T: IntoIterator<Item = (I, P)>>(&mut self, iter: T) {
1086 let iter = iter.into_iter();
1087 let (min, max) = iter.size_hint();
1088 let rebuild = if let Some(max) = max {
1089 self.reserve(max);
1090 better_to_rebuild(self.len(), max)
1091 } else if min != 0 {
1092 self.reserve(min);
1093 better_to_rebuild(self.len(), min)
1094 } else {
1095 false
1096 };
1097 if rebuild {
1098 self.store.extend(iter);
1099 self.heap_build();
1100 } else {
1101 for (item, priority) in iter {
1102 self.push(item, priority);
1103 }
1104 }
1105 }
1106}
1107
1108use std::fmt;
1109
1110impl<I, P, H> fmt::Debug for DoublePriorityQueue<I, P, H>
1111where
1112 I: Hash + Eq + fmt::Debug,
1113 P: Ord + fmt::Debug,
1114{
1115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1116 self.store.fmt(f)
1117 }
1118}
1119
1120use std::cmp::PartialEq;
1121
1122impl<I, P1, H1, P2, H2> PartialEq<DoublePriorityQueue<I, P2, H2>> for DoublePriorityQueue<I, P1, H1>
1123where
1124 I: Hash + Eq,
1125 P1: Ord,
1126 P1: PartialEq<P2>,
1127 Option<P1>: PartialEq<Option<P2>>,
1128 P2: Ord,
1129 H1: BuildHasher,
1130 H2: BuildHasher,
1131{
1132 fn eq(&self, other: &DoublePriorityQueue<I, P2, H2>) -> bool {
1133 self.store == other.store
1134 }
1135}
1136
1137/// Compute the index of the left child of an item from its index
1138#[inline(always)]
1139const fn left(i: Position) -> Position {
1140 Position((i.0 * 2) + 1)
1141}
1142/// Compute the index of the right child of an item from its index
1143#[inline(always)]
1144const fn right(i: Position) -> Position {
1145 Position((i.0 * 2) + 2)
1146}
1147/// Compute the index of the parent element in the heap from its index
1148#[inline(always)]
1149const fn parent(i: Position) -> Position {
1150 Position((i.0 - 1) / 2)
1151}
1152
1153// Compute the level of a node from its index
1154#[inline(always)]
1155const fn level(i: Position) -> usize {
1156 log2_fast(i.0 + 1)
1157}
1158
1159#[inline(always)]
1160const fn log2_fast(x: usize) -> usize {
1161 (usize::BITS - x.leading_zeros() - 1) as usize
1162}
1163
1164// `rebuild` takes O(len1 + len2) operations
1165// and about 2 * (len1 + len2) comparisons in the worst case
1166// while `extend` takes O(len2 * log_2(len1)) operations
1167// and about 1 * len2 * log_2(len1) comparisons in the worst case,
1168// assuming len1 >= len2.
1169fn better_to_rebuild(len1: usize, len2: usize) -> bool {
1170 // log(1) == 0, so the inequation always falsy
1171 // log(0) is inapplicable and produces panic
1172 if len1 <= 1 {
1173 return false;
1174 }
1175
1176 2 * (len1 + len2) < len2 * log2_fast(len1)
1177}
1178
1179#[cfg(feature = "serde")]
1180#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
1181mod serde {
1182 use std::cmp::{Eq, Ord};
1183 use std::hash::{BuildHasher, Hash};
1184
1185 use serde::de::{Deserialize, Deserializer};
1186 use serde::ser::{Serialize, Serializer};
1187
1188 use super::DoublePriorityQueue;
1189 use crate::store::Store;
1190
1191 impl<I, P, H> Serialize for DoublePriorityQueue<I, P, H>
1192 where
1193 I: Hash + Eq + Serialize,
1194 P: Ord + Serialize,
1195 H: BuildHasher,
1196 {
1197 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1198 where
1199 S: Serializer,
1200 {
1201 self.store.serialize(serializer)
1202 }
1203 }
1204
1205 impl<'de, I, P, H> Deserialize<'de> for DoublePriorityQueue<I, P, H>
1206 where
1207 I: Hash + Eq + Deserialize<'de>,
1208 P: Ord + Deserialize<'de>,
1209 H: BuildHasher + Default,
1210 {
1211 fn deserialize<D>(deserializer: D) -> Result<DoublePriorityQueue<I, P, H>, D::Error>
1212 where
1213 D: Deserializer<'de>,
1214 {
1215 Store::deserialize(deserializer).map(|store| {
1216 let mut pq = DoublePriorityQueue { store };
1217 pq.heap_build();
1218 pq
1219 })
1220 }
1221 }
1222}