rate_common/memory/
stackmapping.rs1use crate::memory::{Array, BoundedVector, HeapSpace, Offset};
4use rate_macros::HeapSpace;
5use std::{fmt::Debug, iter::IntoIterator, ops::Index, slice};
6
7#[derive(Debug, HeapSpace, Default)]
15pub struct StackMapping<Key: Offset + Copy + Debug, T: Copy + Debug> {
16 default_value: T,
18 array: Array<Key, T>,
20 vector: BoundedVector<Key>,
22}
23
24impl<Key: Offset + Copy + Debug, T: Copy + Debug> StackMapping<Key, T> {
25 pub fn with_array_value_size_stack_size(
34 array_value: T,
35 array_size: usize,
36 stack_size: usize,
37 ) -> StackMapping<Key, T> {
38 StackMapping {
39 default_value: array_value,
40 array: Array::new(array_value, array_size),
41 vector: BoundedVector::with_capacity(stack_size),
42 }
43 }
44 pub fn len(&self) -> usize {
46 self.vector.len()
47 }
48 pub fn is_empty(&self) -> bool {
50 self.vector.is_empty()
51 }
52 pub fn pop(&mut self) -> Option<Key> {
55 self.vector.pop().map(|key| {
56 self.array[key] = self.default_value;
57 key
58 })
59 }
60 pub fn peek(&self) -> Key {
64 self.vector[self.vector.len() - 1]
65 }
66 pub fn clear(&mut self) {
68 while !self.is_empty() {
69 self.pop();
70 }
71 }
72 pub fn stack_at(&self, offset: usize) -> Key {
74 self.vector[offset]
75 }
76 pub fn stack_at_mut(&mut self, offset: usize) -> &mut Key {
78 &mut self.vector[offset]
79 }
80 pub fn push(&mut self, key: Key, value: T) {
82 self.array[key] = value;
83 self.vector.push(key);
84 }
85 pub fn push_but_do_not_set(&mut self, key: Key) {
87 self.vector.push(key);
88 }
89 pub fn set_but_do_not_push(&mut self, key: Key, value: T) {
91 self.array[key] = value;
92 }
93 pub fn iter(&self) -> slice::Iter<Key> {
95 self.into_iter()
96 }
97}
98
99impl<Key: Offset + Copy + Debug, T: Copy + Debug> Index<Key> for StackMapping<Key, T> {
100 type Output = T;
101 fn index(&self, key: Key) -> &T {
102 &self.array[key]
103 }
104}
105
106impl<'a, Key: Offset + Copy + Debug, T: Copy + Debug> IntoIterator for &'a StackMapping<Key, T> {
107 type Item = &'a Key;
108 type IntoIter = slice::Iter<'a, Key>;
109 fn into_iter(self) -> Self::IntoIter {
110 self.vector.into_iter()
111 }
112}
113
114impl<Key: Ord + Offset + Copy + Debug, T: Copy + Debug> StackMapping<Key, T> {
115 pub fn sort_unstable(&mut self) {
117 self.vector.sort_unstable()
118 }
119}
120
121impl<Key: Offset + Copy + Debug, T: Copy + Debug> StackMapping<Key, T> {
122 pub fn sort_unstable_by_key<F, K>(&mut self, f: F)
124 where
125 F: FnMut(&Key) -> K,
126 K: Ord,
127 {
128 self.vector.sort_unstable_by_key(f)
129 }
130}