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