ic_storage/adapter/heap.rs
1//! Governed heap collection implementation.
2use super::{Memory, Storable};
3use crate::substrate::{self, DefaultMemoryImpl};
4use ic_memory::RuntimeMemory;
5
6/// Governed upstream `MinHeap`; initialization and failures follow upstream contracts.
7pub struct StableMinHeap<T: Storable + Ord, M: Memory = DefaultMemoryImpl> {
8 inner: substrate::MinHeap<T, RuntimeMemory<M>>,
9}
10impl<T: Storable + Ord, M: Memory> StableMinHeap<T, M> {
11 /// Create a new collection, replacing any prior collection in the selected memory.
12 /// This is destructive even when a valid collection already exists.
13 ///
14 /// # Panics
15 /// Panics on insufficient memory or codec/backing failure.
16 pub fn new(memory: RuntimeMemory<M>) -> Self {
17 Self {
18 inner: substrate::MinHeap::new(memory),
19 }
20 }
21 /// Open a valid retained collection, or create one in zero-page memory.
22 ///
23 /// # Panics
24 /// Panics for foreign magic, unsupported layout, incompatible element bounds,
25 /// insufficient memory or codec/backing failure. Foreign memory is not reset.
26 pub fn init(memory: RuntimeMemory<M>) -> Self {
27 Self {
28 inner: substrate::MinHeap::init(memory),
29 }
30 }
31 /// Delegates to upstream `MinHeap::push` with the governed allocation.
32 pub fn push(&mut self, item: &T) {
33 self.inner.push(item);
34 }
35 /// Delegates to upstream `MinHeap::pop` with the governed allocation.
36 pub fn pop(&mut self) -> Option<T> {
37 self.inner.pop()
38 }
39 /// Delegates to upstream `MinHeap::peek` with the governed allocation.
40 pub fn peek(&self) -> Option<T> {
41 self.inner.peek()
42 }
43 /// Delegates to upstream `MinHeap::len` with the governed allocation.
44 pub fn len(&self) -> u64 {
45 self.inner.len()
46 }
47 /// Delegates to upstream `MinHeap::is_empty` with the governed allocation.
48 pub fn is_empty(&self) -> bool {
49 self.inner.is_empty()
50 }
51 /// Delegates to upstream `MinHeap::iter` with the governed allocation.
52 pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
53 self.inner.iter()
54 }
55}