ic_storage/adapter/heap.rs
1//! Governed heap collection implementation.
2use super::{Memory, Storable};
3use crate::{DefaultMemoryImpl, RuntimeMemory, substrate};
4
5///
6/// StableMinHeap
7/// Governed upstream `MinHeap`; initialization and failures follow upstream contracts.
8///
9
10pub struct StableMinHeap<T: Storable + Ord, M: Memory = DefaultMemoryImpl> {
11 inner: substrate::MinHeap<T, RuntimeMemory<M>>,
12}
13
14impl<T: Storable + Ord, M: Memory> StableMinHeap<T, M> {
15 /// Create a collection only in zero-page memory.
16 ///
17 /// # Panics
18 /// Refuses nonempty memory before writing. Growth and codec failures retain
19 /// upstream behavior.
20 #[must_use]
21 pub fn create(memory: RuntimeMemory<M>) -> Self {
22 assert_eq!(memory.size(), 0, "collection memory is not empty");
23
24 Self::reset(memory)
25 }
26
27 /// Deliberately replace any contents in this admitted allocation.
28 ///
29 /// # Panics
30 /// Growth and codec failures retain upstream behavior.
31 #[must_use]
32 pub fn reset(memory: RuntimeMemory<M>) -> Self {
33 Self {
34 inner: substrate::MinHeap::new(memory),
35 }
36 }
37
38 /// Load retained collection state without initializing a replacement.
39 ///
40 /// # Panics
41 /// Refuses empty or foreign memory and incompatible layouts/bounds without
42 /// writing. Record decoding and backing failures retain upstream behavior.
43 #[must_use]
44 pub fn load(memory: RuntimeMemory<M>) -> Self {
45 assert!(memory.size() > 0, "collection memory is empty");
46
47 Self {
48 inner: substrate::MinHeap::init(memory),
49 }
50 }
51
52 /// Delegates to upstream `MinHeap::push` with the governed allocation.
53 pub fn push(&mut self, item: &T) {
54 self.inner.push(item);
55 }
56
57 /// Delegates to upstream `MinHeap::pop` with the governed allocation.
58 pub fn pop(&mut self) -> Option<T> {
59 self.inner.pop()
60 }
61
62 /// Delegates to upstream `MinHeap::peek` with the governed allocation.
63 #[must_use]
64 pub fn peek(&self) -> Option<T> {
65 self.inner.peek()
66 }
67
68 /// Delegates to upstream `MinHeap::len` with the governed allocation.
69 #[must_use]
70 pub fn len(&self) -> u64 {
71 self.inner.len()
72 }
73
74 /// Delegates to upstream `MinHeap::is_empty` with the governed allocation.
75 #[must_use]
76 pub fn is_empty(&self) -> bool {
77 self.inner.is_empty()
78 }
79
80 /// Delegates to upstream `MinHeap::iter` with the governed allocation.
81 pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
82 self.inner.iter()
83 }
84}