Struct staticvec::StaticHeap
source · [−]pub struct StaticHeap<T, const N: usize> { /* private fields */ }
Expand description
A priority queue implemented as a binary heap, built around an instance of StaticVec<T, N>
.
StaticHeap
, as well as the associated iterator and helper structs for it are direct
adaptations of the ones found in the std::collections::binary_heap
module (including
most of the documentation, at least for the functions that exist in both implementations).
It is a logic error for an item to be modified in such a way that the
item’s ordering relative to any other item, as determined by the Ord
trait, changes while it is in the heap. This is normally only possible
through Cell
, RefCell
, global state, I/O, or unsafe code.
Examples
use staticvec::StaticHeap;
let mut heap = StaticHeap::<i32, 4>::new();
// We can use peek to look at the next item in the heap. In this case,
// there's no items in there yet so we get None.
assert_eq!(heap.peek(), None);
// Let's add some scores...
heap.push(1);
heap.push(5);
heap.push(2);
// Now peek shows the most important item in the heap.
assert_eq!(heap.peek(), Some(&5));
// We can check the length of a heap.
assert_eq!(heap.len(), 3);
// We can iterate over the items in the heap, although they are returned in
// a random order.
for x in &heap {
println!("{}", x);
}
// If we instead pop these scores, they should come back in order.
assert_eq!(heap.pop(), Some(5));
assert_eq!(heap.pop(), Some(2));
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.pop(), None);
// We can clear the heap of any remaining items.
heap.clear();
// The heap should now be empty.
assert!(heap.is_empty())
Min-heap
Either core::cmp::Reverse
or a custom Ord
implementation can be used to
make StaticHeap
a min-heap. This makes heap.pop()
return the smallest
value instead of the greatest one.
use staticvec::StaticHeap;
use core::cmp::Reverse;
// Wrap the values in `Reverse`.
let mut heap = StaticHeap::from([Reverse(1), Reverse(5), Reverse(2)]);
// If we pop these scores now, they should come back in the reverse order.
assert_eq!(heap.pop(), Some(Reverse(1)));
assert_eq!(heap.pop(), Some(Reverse(2)));
assert_eq!(heap.pop(), Some(Reverse(5)));
assert_eq!(heap.pop(), None);
Time complexity
The value for push
is an expected cost; the method documentation gives a
more detailed analysis.
Implementations
Creates an empty StaticHeap as a max-heap.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 2>::new();
heap.push(4);
Returns a mutable reference to the greatest item in the StaticHeap, or
None
if it is empty.
Note: If the StaticHeapPeekMut
value is leaked, the heap may be in an
inconsistent state.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 4>::new();
assert!(heap.peek_mut().is_none());
heap.push(1);
heap.push(5);
heap.push(2);
{
let mut val = heap.peek_mut().unwrap();
*val = 0;
}
assert_eq!(heap.peek(), Some(&2));
Time complexity
Cost is O(1) in the worst case.
Pops a value from the end of the StaticHeap and returns it directly without asserting that the StaticHeap’s current length is greater than 0.
Safety
It is up to the caller to ensure that the StaticHeap contains at least one element prior to using this function. Failure to do so will result in reading from uninitialized memory.
Examples
Basic usage:
let mut heap = StaticHeap::from([1, 3]);
unsafe {
assert_eq!(heap.pop_unchecked(), 3);
assert_eq!(heap.pop_unchecked(), 1);
}
Time complexity
The worst case cost of pop_unchecked
on a heap containing n elements is O(log n).
Removes the greatest item from the StaticHeap and returns it, or None
if it
is empty.
Examples
Basic usage:
let mut heap = StaticHeap::from([1, 3]);
assert_eq!(heap.pop(), Some(3));
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.pop(), None);
Time complexity
The worst case cost of pop
on a heap containing n elements is O(log n).
Pushes a value onto the StaticHeap without asserting that
its current length is less than self.capacity()
.
Safety
It is up to the caller to ensure that the length of the StaticHeap
prior to using this function is less than self.capacity()
.
Failure to do so will result in writing to an out-of-bounds memory region.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 3>::new();
unsafe {
heap.push_unchecked(3);
heap.push_unchecked(5);
heap.push_unchecked(1);
}
assert_eq!(heap.len(), 3);
assert_eq!(heap.peek(), Some(&5));
Time complexity
The expected cost of push_unchecked
, averaged over every possible ordering of
the elements being pushed, and over a sufficiently large number of
pushes, is O(1). This is the most meaningful cost metric when pushing
elements that are not already in any sorted pattern.
The time complexity degrades if elements are pushed in predominantly ascending order. In the worst case, elements are pushed in ascending sorted order and the amortized cost per push is O(log n) against a heap containing n elements.
The worst case cost of a single call to push_unchecked
is O(n).
Pushes an item onto the StaticHeap, panicking if the underlying StaticVec instance is already at maximum capacity.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 5>::new();
heap.push(3);
heap.push(5);
heap.push(1);
assert_eq!(heap.len(), 3);
assert_eq!(heap.peek(), Some(&5));
Time complexity
The expected cost of push
, averaged over every possible ordering of
the elements being pushed, and over a sufficiently large number of
pushes, is O(1). This is the most meaningful cost metric when pushing
elements that are not already in any sorted pattern.
The time complexity degrades if elements are pushed in predominantly ascending order. In the worst case, elements are pushed in ascending sorted order and the amortized cost per push is O(log n) against a heap containing n elements.
The worst case cost of a single call to push
is O(n).
Consumes the StaticHeap and returns a StaticVec in sorted (ascending) order.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 8>::from([1, 2, 4, 5, 7]);
heap.push(6);
heap.push(3);
let vec = heap.into_sorted_staticvec();
assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
Appends self.remaining_capacity()
(or as many as available) items from other
to self
.
The appended items (if any) will no longer exist in other
afterwards (which is to say,
other
will be left empty.)
The N2
parameter does not need to be provided explicitly, and can be inferred directly from
the constant N2
constraint of other
(which may or may not be the same as the N
constraint of self
.)
Examples
Basic usage:
// We give the two heaps arbitrary capacities for the sake of the example.
let mut a = StaticHeap::<i32, 9>::from([-10, 1, 2, 3, 3]);
let mut b = StaticHeap::<i32, 18>::from([-20, 5, 43]);
a.append(&mut b);
assert_eq!(a.into_sorted_staticvec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
assert!(b.is_empty());
pub const fn drain_sorted(&mut self) -> StaticHeapDrainSorted<'_, T, N>ⓘNotable traits for StaticHeapDrainSorted<'_, T, N>impl<T: Ord, const N: usize> Iterator for StaticHeapDrainSorted<'_, T, N> type Item = T;
pub const fn drain_sorted(&mut self) -> StaticHeapDrainSorted<'_, T, N>ⓘNotable traits for StaticHeapDrainSorted<'_, T, N>impl<T: Ord, const N: usize> Iterator for StaticHeapDrainSorted<'_, T, N> type Item = T;
impl<T: Ord, const N: usize> Iterator for StaticHeapDrainSorted<'_, T, N> type Item = T;
Returns an iterator which retrieves elements in heap order. The retrieved elements are removed from the original heap. The remaining elements will be removed on drop in heap order.
Note:
drain_sorted()
is O(n log n); much slower thandrain()
. You should use the latter for most cases.
Examples
Basic usage:
let mut heap = StaticHeap::from([1, 2, 3, 4, 5]);
assert_eq!(heap.len(), 5);
drop(heap.drain_sorted()); // removes all elements in heap order
assert_eq!(heap.len(), 0);
pub const fn iter(&self) -> StaticVecIterConst<'_, T, N>ⓘNotable traits for StaticVecIterConst<'a, T, N>impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterConst<'a, T, N> type Item = &'a T;
pub const fn iter(&self) -> StaticVecIterConst<'_, T, N>ⓘNotable traits for StaticVecIterConst<'a, T, N>impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterConst<'a, T, N> type Item = &'a T;
impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterConst<'a, T, N> type Item = &'a T;
Returns an iterator visiting all values in the StaticHeap’s underlying StaticVec, in arbitrary order.
Examples
Basic usage:
let heap = StaticHeap::from(staticvec![1, 2, 3, 4]);
// Print 1, 2, 3, 4 in arbitrary order
for x in heap.iter() {
println!("{}", x);
}
pub const fn iter_mut(&mut self) -> StaticVecIterMut<'_, T, N>ⓘNotable traits for StaticVecIterMut<'a, T, N>impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterMut<'a, T, N> type Item = &'a mut T;
pub const fn iter_mut(&mut self) -> StaticVecIterMut<'_, T, N>ⓘNotable traits for StaticVecIterMut<'a, T, N>impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterMut<'a, T, N> type Item = &'a mut T;
impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterMut<'a, T, N> type Item = &'a mut T;
Returns a mutable iterator visiting all values in the StaticHeap’s underlying StaticVec, in arbitrary order.
Note: Mutating the elements in a StaticHeap may cause it to become unbalanced.
Examples
Basic usage:
let mut heap = StaticHeap::from([1, 2, 3, 4]);
for i in heap.iter_mut() {
*i *= 2;
}
// Prints "[2, 4, 6, 8]", but in arbitrary order
println!("{:?}", heap);
pub const fn into_iter_sorted(self) -> StaticHeapIntoIterSorted<T, N>ⓘNotable traits for StaticHeapIntoIterSorted<T, N>impl<T: Ord, const N: usize> Iterator for StaticHeapIntoIterSorted<T, N> type Item = T;
pub const fn into_iter_sorted(self) -> StaticHeapIntoIterSorted<T, N>ⓘNotable traits for StaticHeapIntoIterSorted<T, N>impl<T: Ord, const N: usize> Iterator for StaticHeapIntoIterSorted<T, N> type Item = T;
impl<T: Ord, const N: usize> Iterator for StaticHeapIntoIterSorted<T, N> type Item = T;
Returns an iterator which retrieves elements in heap order. This method consumes the original StaticHeap.
Examples
Basic usage:
let heap = StaticHeap::from([1, 2, 3, 4, 5]);
assert_eq!(
heap.into_iter_sorted().take(2).collect::<StaticVec<_, 3>>(), staticvec![5, 4]
);
Returns the greatest item in the StaticHeap, or None
if it is empty.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 7>::new();
assert_eq!(heap.peek(), None);
heap.push(1);
heap.push(5);
heap.push(2);
assert_eq!(heap.peek(), Some(&5));
Time complexity
Cost is O(1) in the worst case.
Returns the maximum number of elements the StaticHeap can hold.
This is always equivalent to its constant generic N
parameter.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 100>::new();
assert!(heap.capacity() >= 100);
heap.push(4);
Returns the remaining capacity (which is to say, self.capacity() - self.len()
) of the
StaticHeap.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 100>::new();
heap.push(1);
assert_eq!(heap.remaining_capacity(), 99);
Returns the total size of the inhabited part of the StaticHeap (which may be zero if it has a
length of zero or contains ZSTs) in bytes. Specifically, the return value of this function
amounts to a calculation of size_of::<T>() * self.length
.
Examples
Basic usage:
let x = StaticHeap::<u8, 8>::from([1, 2, 3, 4, 5, 6, 7, 8]);
assert_eq!(x.size_in_bytes(), 8);
let y = StaticHeap::<u16, 8>::from([1, 2, 3, 4, 5, 6, 7, 8]);
assert_eq!(y.size_in_bytes(), 16);
let z = StaticHeap::<u32, 8>::from([1, 2, 3, 4, 5, 6, 7, 8]);
assert_eq!(z.size_in_bytes(), 32);
let w = StaticHeap::<u64, 8>::from([1, 2, 3, 4, 5, 6, 7, 8]);
assert_eq!(w.size_in_bytes(), 64);
Consumes the StaticHeap and returns the underlying StaticVec in arbitrary order.
Examples
Basic usage:
let heap = StaticHeap::from(staticvec![1, 2, 3, 4, 5, 6, 7]);
let vec = heap.into_staticvec();
// Will print in some order
for x in &vec {
println!("{}", x);
}
Returns the length of the StaticHeap.
Examples
Basic usage:
let heap = StaticHeap::from(staticvec![1, 3]);
assert_eq!(heap.len(), 2);
Returns true if the current length of the StaticHeap is 0.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 28>::new();
assert!(heap.is_empty());
Returns true if the current length of the StaticHeap is greater than 0.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 2>::new();
heap.push(1);
assert!(heap.is_not_empty());
Returns true if the current length of the StaticHeap is equal to its capacity.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 4>::new();
heap.push(3);
heap.push(5);
heap.push(1);
heap.push(2);
assert!(heap.is_full());
Returns true if the current length of the StaticHeap is less than its capacity.
Examples
Basic usage:
let mut heap = StaticHeap::<i32, 4>::new();
heap.push(3);
heap.push(5);
heap.push(1);
assert!(heap.is_not_full());
pub fn drain(&mut self) -> StaticVecDrain<'_, T, N>ⓘNotable traits for StaticVecDrain<'a, T, N>impl<'a, T: 'a, const N: usize> Iterator for StaticVecDrain<'a, T, N> type Item = T;
pub fn drain(&mut self) -> StaticVecDrain<'_, T, N>ⓘNotable traits for StaticVecDrain<'a, T, N>impl<'a, T: 'a, const N: usize> Iterator for StaticVecDrain<'a, T, N> type Item = T;
impl<'a, T: 'a, const N: usize> Iterator for StaticVecDrain<'a, T, N> type Item = T;
Clears the StaticHeap, returning an iterator over the removed elements.
The elements are removed in arbitrary order.
Examples
Basic usage:
let mut heap = StaticHeap::from(staticvec![1, 3]);
assert!(heap.is_not_empty());
for x in heap.drain() {
println!("{}", x);
}
assert!(heap.is_empty());
Trait Implementations
Creates an empty StaticHeap<T, N>
.
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
Extends a collection with the contents of an iterator. Read more
extend_one
)Extends a collection with exactly one element.
extend_one
)Reserves capacity in a collection for the given number of additional elements. Read more
Extends a collection with the contents of an iterator. Read more
extend_one
)Extends a collection with exactly one element.
extend_one
)Reserves capacity in a collection for the given number of additional elements. Read more
Converts a [T; N]
into a StaticHeap<T, N>
.
This conversion happens in-place, and has O(n)
time complexity.
Converts a [T; N1]
into a StaticHeap<T, N2>
.
This conversion happens in-place, and has O(n)
time complexity.
Converts a StaticVec<T, N>
into a StaticHeap<T, N>
.
This conversion happens in-place, and has O(n)
time complexity.
Converts a StaticVec<T, N1>
into a StaticHeap<T, N2>
.
This conversion happens in-place, and has O(n)
time complexity.
Creates a value from an iterator. Read more
Creates a value from an iterator. Read more
fn into_iter(self) -> StaticVecIntoIter<T, N>ⓘNotable traits for StaticVecIntoIter<T, N>impl<T, const N: usize> Iterator for StaticVecIntoIter<T, N> type Item = T;
fn into_iter(self) -> StaticVecIntoIter<T, N>ⓘNotable traits for StaticVecIntoIter<T, N>impl<T, const N: usize> Iterator for StaticVecIntoIter<T, N> type Item = T;
impl<T, const N: usize> Iterator for StaticVecIntoIter<T, N> type Item = T;
Creates a consuming iterator, that is, one that moves each value out of the binary heap in arbitrary order. The binary heap cannot be used after calling this.
Examples
Basic usage:
let heap = StaticHeap::from([1, 2, 3, 4]);
// Print 1, 2, 3, 4 in arbitrary order
for x in heap.into_iter() {
// x has type i32, not &i32
println!("{}", x);
}
type Item = T
type Item = T
The type of the elements being iterated over.
type IntoIter = StaticVecIntoIter<T, N>
type IntoIter = StaticVecIntoIter<T, N>
Which kind of iterator are we turning this into?
type IntoIter = StaticVecIterConst<'a, T, N>
type IntoIter = StaticVecIterConst<'a, T, N>
Which kind of iterator are we turning this into?
fn into_iter(self) -> StaticVecIterConst<'a, T, N>ⓘNotable traits for StaticVecIterConst<'a, T, N>impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterConst<'a, T, N> type Item = &'a T;
fn into_iter(self) -> StaticVecIterConst<'a, T, N>ⓘNotable traits for StaticVecIterConst<'a, T, N>impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterConst<'a, T, N> type Item = &'a T;
impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterConst<'a, T, N> type Item = &'a T;
Creates an iterator from a value. Read more
type IntoIter = StaticVecIterMut<'a, T, N>
type IntoIter = StaticVecIterMut<'a, T, N>
Which kind of iterator are we turning this into?
fn into_iter(self) -> StaticVecIterMut<'a, T, N>ⓘNotable traits for StaticVecIterMut<'a, T, N>impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterMut<'a, T, N> type Item = &'a mut T;
fn into_iter(self) -> StaticVecIterMut<'a, T, N>ⓘNotable traits for StaticVecIterMut<'a, T, N>impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterMut<'a, T, N> type Item = &'a mut T;
impl<'a, T: 'a, const N: usize> Iterator for StaticVecIterMut<'a, T, N> type Item = &'a mut T;
Creates an iterator from a value. Read more
Auto Trait Implementations
impl<T, const N: usize> RefUnwindSafe for StaticHeap<T, N> where
T: RefUnwindSafe,
impl<T, const N: usize> Send for StaticHeap<T, N> where
T: Send,
impl<T, const N: usize> Sync for StaticHeap<T, N> where
T: Sync,
impl<T, const N: usize> Unpin for StaticHeap<T, N> where
T: Unpin,
impl<T, const N: usize> UnwindSafe for StaticHeap<T, N> where
T: UnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more