Type Definition dary_heap::SenaryHeap

source ·
pub type SenaryHeap<T> = DaryHeap<T, 6>;
Expand description

A senary heap (d = 6).

Implementations§

source§

impl<T: Ord, const D: usize> DaryHeap<T, D>

source

pub fn new() -> DaryHeap<T, D>

Creates an empty DaryHeap as a max-heap.

Examples

Basic usage:

use dary_heap::QuaternaryHeap;
let mut heap = QuaternaryHeap::new();
heap.push(4);
source

pub fn with_capacity(capacity: usize) -> DaryHeap<T, D>

Creates an empty DaryHeap with at least the specific capacity.

The d-ary heap will be able to hold at least capacity elements without reallocating. This method is allowed to allocate for more elements than capacity. If capacity is 0, the d-ary heap will not allocate.

Examples

Basic usage:

use dary_heap::QuaternaryHeap;
let mut heap = QuaternaryHeap::with_capacity(10);
heap.push(4);
source

pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, D>>

Returns a mutable reference to the greatest item in the d-ary heap, or None if it is empty.

Note: If the PeekMut value is leaked, some heap elements might get leaked along with it, but the remaining elements will remain a valid heap.

Examples

Basic usage:

use dary_heap::TernaryHeap;
let mut heap = TernaryHeap::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

If the item is modified then the worst case time complexity is O(log(n)), otherwise it’s O(1).

source

pub fn pop(&mut self) -> Option<T>

Removes the greatest item from the d-ary heap and returns it, or None if it is empty.

Examples

Basic usage:

use dary_heap::BinaryHeap;
let mut heap = BinaryHeap::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)).

source

pub fn push(&mut self, item: T)

Pushes an item onto the d-ary heap.

Examples

Basic usage:

use dary_heap::QuaternaryHeap;
let mut heap = QuaternaryHeap::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). The worst case occurs when capacity is exhausted and needs a resize. The resize cost has been amortized in the previous figures.

source

pub fn into_sorted_vec(self) -> Vec<T>

Consumes the DaryHeap and returns a vector in sorted (ascending) order.

Examples

Basic usage:

use dary_heap::OctonaryHeap;

let mut heap = OctonaryHeap::from([1, 2, 4, 5, 7]);
heap.push(6);
heap.push(3);

let vec = heap.into_sorted_vec();
assert_eq!(vec, [1, 2, 3, 4, 5, 6, 7]);
source

pub fn append(&mut self, other: &mut Self)

Moves all the elements of other into self, leaving other empty.

Examples

Basic usage:

use dary_heap::OctonaryHeap;

let mut a = OctonaryHeap::from([-10, 1, 2, 3, 3]);
let mut b = OctonaryHeap::from([-20, 5, 43]);

a.append(&mut b);

assert_eq!(a.into_sorted_vec(), [-20, -10, 1, 2, 3, 3, 5, 43]);
assert!(b.is_empty());
source

pub fn drain_sorted(&mut self) -> DrainSorted<'_, T, D>

Available on crate feature unstable only.

Clears the d-ary heap, returning an iterator over the removed elements in heap order. If the iterator is dropped before being fully consumed, it drops the remaining elements in heap order.

The returned iterator keeps a mutable borrow on the heap to optimize its implementation.

Note:

  • .drain_sorted() is O(n * log(n)); much slower than .drain(). You should use the latter for most cases.
Examples

Basic usage:

use dary_heap::TernaryHeap;

let mut heap = TernaryHeap::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);
source

pub fn retain<F>(&mut self, f: F)where F: FnMut(&T) -> bool,

Retains only the elements specified by the predicate.

In other words, remove all elements e for which f(&e) returns false. The elements are visited in unsorted (and unspecified) order.

Examples

Basic usage:

use dary_heap::OctonaryHeap;

let mut heap = OctonaryHeap::from([-10, -5, 1, 2, 4, 13]);

heap.retain(|x| x % 2 == 0); // only keep even numbers

assert_eq!(heap.into_sorted_vec(), [-10, 2, 4])
source§

impl<T, const D: usize> DaryHeap<T, D>

source

pub fn iter(&self) -> Iter<'_, T>

Returns an iterator visiting all values in the underlying vector, in arbitrary order.

Examples

Basic usage:

use dary_heap::TernaryHeap;
let heap = TernaryHeap::from([1, 2, 3, 4]);

// Print 1, 2, 3, 4 in arbitrary order
for x in heap.iter() {
    println!("{x}");
}
source

pub fn into_iter_sorted(self) -> IntoIterSorted<T, D>

Available on crate feature unstable only.

Returns an iterator which retrieves elements in heap order. This method consumes the original heap.

Examples

Basic usage:

use dary_heap::QuaternaryHeap;
let heap = QuaternaryHeap::from([1, 2, 3, 4, 5]);

assert_eq!(heap.into_iter_sorted().take(2).collect::<Vec<_>>(), [5, 4]);
source

pub fn peek(&self) -> Option<&T>

Returns the greatest item in the d-ary heap, or None if it is empty.

Examples

Basic usage:

use dary_heap::BinaryHeap;
let mut heap = BinaryHeap::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.

source

pub fn capacity(&self) -> usize

Returns the number of elements the d-ary heap can hold without reallocating.

Examples

Basic usage:

use dary_heap::OctonaryHeap;
let mut heap = OctonaryHeap::with_capacity(100);
assert!(heap.capacity() >= 100);
heap.push(4);
source

pub fn reserve_exact(&mut self, additional: usize)

Reserves the minimum capacity for at least additional elements more than the current length. Unlike reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling reserve_exact, capacity will be greater than or equal to self.len() + additional. Does nothing if the capacity is already sufficient.

Panics

Panics if the new capacity overflows usize.

Examples

Basic usage:

use dary_heap::OctonaryHeap;
let mut heap = OctonaryHeap::new();
heap.reserve_exact(100);
assert!(heap.capacity() >= 100);
heap.push(4);
source

pub fn reserve(&mut self, additional: usize)

Reserves capacity for at least additional elements more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After calling reserve, capacity will be greater than or equal to self.len() + additional. Does nothing if capacity is already sufficient.

Panics

Panics if the new capacity overflows usize.

Examples

Basic usage:

use dary_heap::BinaryHeap;
let mut heap = BinaryHeap::new();
heap.reserve(100);
assert!(heap.capacity() >= 100);
heap.push(4);
source

pub fn try_reserve_exact( &mut self, additional: usize ) -> Result<(), TryReserveError>

Available on crate feature extra only.

Tries to reserve the minimum capacity for at least additional elements more than the current length. Unlike try_reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling try_reserve_exact, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). Does nothing if the capacity is already sufficient.

Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer try_reserve if future insertions are expected.

Errors

If the capacity overflows, or the allocator reports a failure, then an error is returned.

Examples
use dary_heap::BinaryHeap;
use std::collections::TryReserveError;

fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
    let mut heap = BinaryHeap::new();

    // Pre-reserve the memory, exiting if we can't
    heap.try_reserve_exact(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    heap.extend(data.iter());

    Ok(heap.pop())
}
source

pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>

Available on crate feature extra only.

Tries to reserve capacity for at least additional elements more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After calling try_reserve, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs.

Errors

If the capacity overflows, or the allocator reports a failure, then an error is returned.

Examples
use dary_heap::QuaternaryHeap;
use std::collections::TryReserveError;

fn find_max_slow(data: &[u32]) -> Result<Option<u32>, TryReserveError> {
    let mut heap = QuaternaryHeap::new();

    // Pre-reserve the memory, exiting if we can't
    heap.try_reserve(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    heap.extend(data.iter());

    Ok(heap.pop())
}
source

pub fn shrink_to_fit(&mut self)

Discards as much additional capacity as possible.

Examples

Basic usage:

use dary_heap::TernaryHeap;
let mut heap: TernaryHeap<i32> = TernaryHeap::with_capacity(100);

assert!(heap.capacity() >= 100);
heap.shrink_to_fit();
assert!(heap.capacity() == 0);
source

pub fn shrink_to(&mut self, min_capacity: usize)

Available on crate feature extra only.

Discards capacity with a lower bound.

The capacity will remain at least as large as both the length and the supplied value.

If the current capacity is less than the lower limit, this is a no-op.

Examples
use dary_heap::TernaryHeap;
let mut heap: TernaryHeap<i32> = TernaryHeap::with_capacity(100);

assert!(heap.capacity() >= 100);
heap.shrink_to(10);
assert!(heap.capacity() >= 10);
source

pub fn as_slice(&self) -> &[T]

Available on crate feature unstable only.

Returns a slice of all values in the underlying vector, in arbitrary order.

Examples

Basic usage:

use dary_heap::OctonaryHeap;
use std::io::{self, Write};

let heap = OctonaryHeap::from([1, 2, 3, 4, 5, 6, 7]);

io::sink().write(heap.as_slice()).unwrap();
source

pub fn into_vec(self) -> Vec<T>

Consumes the DaryHeap and returns the underlying vector in arbitrary order.

Examples

Basic usage:

use dary_heap::QuaternaryHeap;
let heap = QuaternaryHeap::from([1, 2, 3, 4, 5, 6, 7]);
let vec = heap.into_vec();

// Will print in some order
for x in vec {
    println!("{x}");
}
source

pub fn len(&self) -> usize

Returns the length of the d-ary heap.

Examples

Basic usage:

use dary_heap::BinaryHeap;
let heap = BinaryHeap::from([1, 3]);

assert_eq!(heap.len(), 2);
source

pub fn is_empty(&self) -> bool

Checks if the d-ary heap is empty.

Examples

Basic usage:

use dary_heap::BinaryHeap;
let mut heap = BinaryHeap::new();

assert!(heap.is_empty());

heap.push(3);
heap.push(5);
heap.push(1);

assert!(!heap.is_empty());
source

pub fn drain(&mut self) -> Drain<'_, T>

Clears the d-ary heap, returning an iterator over the removed elements in arbitrary order. If the iterator is dropped before being fully consumed, it drops the remaining elements in arbitrary order.

The returned iterator keeps a mutable borrow on the heap to optimize its implementation.

Examples

Basic usage:

use dary_heap::QuaternaryHeap;
let mut heap = QuaternaryHeap::from([1, 3]);

assert!(!heap.is_empty());

for x in heap.drain() {
    println!("{x}");
}

assert!(heap.is_empty());
source

pub fn clear(&mut self)

Drops all items from the d-ary heap.

Examples

Basic usage:

use dary_heap::TernaryHeap;
let mut heap = TernaryHeap::from([1, 3]);

assert!(!heap.is_empty());

heap.clear();

assert!(heap.is_empty());

Trait Implementations§

source§

impl<T: Clone, const D: usize> Clone for DaryHeap<T, D>

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T: Debug, const D: usize> Debug for DaryHeap<T, D>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T: Ord, const D: usize> Default for DaryHeap<T, D>

source§

fn default() -> DaryHeap<T, D>

Creates an empty DaryHeap<T, D>.

source§

impl<'de, T: Ord + Deserialize<'de>, const A: usize> Deserialize<'de> for DaryHeap<T, A>

source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl<'a, T: 'a + Ord + Copy, const D: usize> Extend<&'a T> for DaryHeap<T, D>

source§

fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: &'a T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T: Ord, const D: usize> Extend<T> for DaryHeap<T, D>

source§

fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl<T: Ord, const D: usize, const N: usize> From<[T; N]> for DaryHeap<T, D>

source§

fn from(arr: [T; N]) -> Self

use dary_heap::TernaryHeap;

let mut h1 = TernaryHeap::from([1, 4, 2, 3]);
let mut h2: TernaryHeap<_> = [1, 4, 2, 3].into();
while let Some((a, b)) = h1.pop().zip(h2.pop()) {
    assert_eq!(a, b);
}
source§

impl<T: Ord, const D: usize> From<Vec<T, Global>> for DaryHeap<T, D>

source§

fn from(vec: Vec<T>) -> DaryHeap<T, D>

Converts a Vec<T> into a DaryHeap<T, D>.

This conversion happens in-place, and has O(n) time complexity.

source§

impl<T: Ord, const D: usize> FromIterator<T> for DaryHeap<T, D>

source§

fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> DaryHeap<T, D>

Creates a value from an iterator. Read more
source§

impl<T, const D: usize> IntoIterator for DaryHeap<T, D>

source§

fn into_iter(self) -> IntoIter<T>

Creates a consuming iterator, that is, one that moves each value out of the d-ary heap in arbitrary order. The d-ary heap cannot be used after calling this.

Examples

Basic usage:

use dary_heap::BinaryHeap;
let heap = BinaryHeap::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

The type of the elements being iterated over.
§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
source§

impl<T: Serialize, const D: usize> Serialize for DaryHeap<T, D>

source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<T, const D: usize> RefUnwindSafe for DaryHeap<T, D>where T: RefUnwindSafe,

§

impl<T, const D: usize> Send for DaryHeap<T, D>where T: Send,

§

impl<T, const D: usize> Sync for DaryHeap<T, D>where T: Sync,

§

impl<T, const D: usize> Unpin for DaryHeap<T, D>where T: Unpin,

§

impl<T, const D: usize> UnwindSafe for DaryHeap<T, D>where T: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,