Skip to main content

ic_storage/adapter/
heap.rs

1//! Governed heap collection implementation.
2use super::{Memory, Storable};
3use crate::RuntimeMemory;
4use crate::{DefaultMemoryImpl, substrate};
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 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    /// Delegates to upstream `MinHeap::push` with the governed allocation.
46    pub fn push(&mut self, item: &T) {
47        self.inner.push(item);
48    }
49    /// Delegates to upstream `MinHeap::pop` with the governed allocation.
50    pub fn pop(&mut self) -> Option<T> {
51        self.inner.pop()
52    }
53    /// Delegates to upstream `MinHeap::peek` with the governed allocation.
54    #[must_use]
55    pub fn peek(&self) -> Option<T> {
56        self.inner.peek()
57    }
58    /// Delegates to upstream `MinHeap::len` with the governed allocation.
59    #[must_use]
60    pub fn len(&self) -> u64 {
61        self.inner.len()
62    }
63    /// Delegates to upstream `MinHeap::is_empty` with the governed allocation.
64    #[must_use]
65    pub fn is_empty(&self) -> bool {
66        self.inner.is_empty()
67    }
68    /// Delegates to upstream `MinHeap::iter` with the governed allocation.
69    pub fn iter(&self) -> impl Iterator<Item = T> + '_ {
70        self.inner.iter()
71    }
72}