Skip to main content

collections/
fixed.rs

1// SPDX-License-Identifier: Apache-2.0
2//
3// Written in 2022-2026 by Dr. Maxim Orlovsky <orlovsky@ubideco.org>
4//
5// Copyright 2022-2026 Laboratories for Ubiquitous and Deterministic Computing,
6// Institute for Distributed and Cognitive Computing (InDCS), Switzerland.
7// All rights reserved.
8//
9// Copyright (C) 2022-2026 Dr Maxim Orlovsky.
10// All rights reserved.
11//
12// Licensed under the Apache License, Version 2.0 (the "License"); you may not
13// use this file except in compliance with the License. You may obtain a copy of
14// the License at <http://www.apache.org/licenses/LICENSE-2.0>
15//
16// Unless required by applicable law or agreed to in writing, software
17// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
19// License for the specific language governing permissions and limitations under
20// the License.
21
22use core::hash::{BuildHasher, Hash};
23
24use heapless::binary_heap::Kind;
25use heapless::{
26    BinaryHeap, CapacityError, Deque, IndexMap, IndexSet, LenType, LinearMap, String, Vec,
27    index_map,
28};
29
30use super::{
31    Collection, CollectionBase, CollectionBytes, CollectionCapacity, CollectionEntry,
32    CollectionMap, MapEntry,
33};
34
35/// Reports an infallible insertion into a full fixed-capacity collection.
36#[cold]
37#[inline(never)]
38#[track_caller]
39fn capacity_exceeded() -> ! {
40    panic!("fixed-capacity collection is full")
41}
42
43/// Checks whether `additional` more storage units fit into the capacity.
44fn check_room(len: usize, capacity: usize, additional: usize) -> Result<(), CapacityError> {
45    match len.checked_add(additional) {
46        Some(required) if required <= capacity => Ok(()),
47        _ => Err(CapacityError::default()),
48    }
49}
50
51impl<T, LenT: LenType, const N: usize> CollectionBase for Vec<T, N, LenT> {
52    type Item = T;
53
54    fn item_count(&self) -> usize {
55        self.as_slice().len()
56    }
57
58    #[track_caller]
59    fn push(&mut self, elem: Self::Item) {
60        if Vec::push(self, elem).is_err() {
61            capacity_exceeded()
62        }
63    }
64
65    fn clear(&mut self) {
66        Vec::clear(self)
67    }
68}
69
70impl<LenT: LenType, const N: usize> CollectionBytes for Vec<u8, N, LenT> {
71    fn byte_len(&self) -> usize {
72        self.as_slice().len()
73    }
74
75    fn item_byte_len(_item: &Self::Item) -> usize {
76        1
77    }
78}
79
80impl<T, LenT: LenType, const N: usize> Collection for Vec<T, N, LenT> {
81    /// The capacity is fixed by the type, so this argument is ignored.
82    fn with_capacity(_capacity: usize) -> Self {
83        Vec::new()
84    }
85}
86
87impl<T, LenT: LenType, const N: usize> CollectionCapacity for Vec<T, N, LenT> {
88    type ReserveError = CapacityError;
89
90    fn capacity(&self) -> usize {
91        Vec::capacity(self)
92    }
93
94    #[track_caller]
95    fn reserve(&mut self, additional: usize) {
96        if check_room(self.as_slice().len(), Vec::capacity(self), additional).is_err() {
97            capacity_exceeded()
98        }
99    }
100
101    fn try_reserve(&mut self, additional: usize) -> Result<(), Self::ReserveError> {
102        check_room(self.as_slice().len(), Vec::capacity(self), additional)
103    }
104
105    fn try_push(&mut self, elem: Self::Item) -> Result<(), Self::Item> {
106        Vec::push(self, elem)
107    }
108}
109
110impl<LenT: LenType, const N: usize> CollectionBase for String<N, LenT> {
111    type Item = char;
112
113    fn item_count(&self) -> usize {
114        self.as_str().chars().count()
115    }
116
117    fn is_empty(&self) -> bool {
118        self.as_str().is_empty()
119    }
120
121    #[track_caller]
122    fn push(&mut self, elem: Self::Item) {
123        if String::push(self, elem).is_err() {
124            capacity_exceeded()
125        }
126    }
127
128    fn clear(&mut self) {
129        String::clear(self)
130    }
131}
132
133impl<LenT: LenType, const N: usize> CollectionBytes for String<N, LenT> {
134    fn byte_len(&self) -> usize {
135        self.as_str().len()
136    }
137
138    fn item_byte_len(item: &Self::Item) -> usize {
139        item.len_utf8()
140    }
141}
142
143impl<LenT: LenType, const N: usize> CollectionCapacity for String<N, LenT> {
144    type ReserveError = CapacityError;
145
146    fn capacity(&self) -> usize {
147        String::capacity(self)
148    }
149
150    #[track_caller]
151    fn reserve(&mut self, additional: usize) {
152        if check_room(self.as_str().len(), String::capacity(self), additional).is_err() {
153            capacity_exceeded()
154        }
155    }
156
157    fn try_reserve(&mut self, additional: usize) -> Result<(), Self::ReserveError> {
158        check_room(self.as_str().len(), String::capacity(self), additional)
159    }
160
161    fn try_push(&mut self, elem: Self::Item) -> Result<(), Self::Item> {
162        String::push(self, elem).map_err(|_| elem)
163    }
164}
165
166impl<T, const N: usize> CollectionBase for Deque<T, N> {
167    type Item = T;
168
169    fn item_count(&self) -> usize {
170        Deque::len(self)
171    }
172
173    #[track_caller]
174    fn push(&mut self, elem: Self::Item) {
175        if Deque::push_back(self, elem).is_err() {
176            capacity_exceeded()
177        }
178    }
179
180    fn clear(&mut self) {
181        Deque::clear(self)
182    }
183}
184
185impl<T, const N: usize> CollectionCapacity for Deque<T, N> {
186    type ReserveError = CapacityError;
187
188    fn capacity(&self) -> usize {
189        Deque::capacity(self)
190    }
191
192    #[track_caller]
193    fn reserve(&mut self, additional: usize) {
194        if check_room(Deque::len(self), Deque::capacity(self), additional).is_err() {
195            capacity_exceeded()
196        }
197    }
198
199    fn try_reserve(&mut self, additional: usize) -> Result<(), Self::ReserveError> {
200        check_room(Deque::len(self), Deque::capacity(self), additional)
201    }
202
203    fn try_push(&mut self, elem: Self::Item) -> Result<(), Self::Item> {
204        Deque::push_back(self, elem)
205    }
206}
207
208impl<T: Ord, K: Kind, const N: usize> CollectionBase for BinaryHeap<T, K, N> {
209    type Item = T;
210
211    fn item_count(&self) -> usize {
212        BinaryHeap::len(self)
213    }
214
215    #[track_caller]
216    fn push(&mut self, elem: Self::Item) {
217        if BinaryHeap::push(self, elem).is_err() {
218            capacity_exceeded()
219        }
220    }
221
222    fn clear(&mut self) {
223        BinaryHeap::clear(self)
224    }
225}
226
227impl<T: Ord, K: Kind, const N: usize> CollectionCapacity for BinaryHeap<T, K, N> {
228    type ReserveError = CapacityError;
229
230    fn capacity(&self) -> usize {
231        BinaryHeap::capacity(self)
232    }
233
234    #[track_caller]
235    fn reserve(&mut self, additional: usize) {
236        if check_room(
237            BinaryHeap::len(self),
238            BinaryHeap::capacity(self),
239            additional,
240        )
241        .is_err()
242        {
243            capacity_exceeded()
244        }
245    }
246
247    fn try_reserve(&mut self, additional: usize) -> Result<(), Self::ReserveError> {
248        check_room(
249            BinaryHeap::len(self),
250            BinaryHeap::capacity(self),
251            additional,
252        )
253    }
254
255    fn try_push(&mut self, elem: Self::Item) -> Result<(), Self::Item> {
256        BinaryHeap::push(self, elem)
257    }
258}
259
260impl<T: Eq + Hash, S: BuildHasher, const N: usize> CollectionBase for IndexSet<T, S, N> {
261    type Item = T;
262
263    fn item_count(&self) -> usize {
264        IndexSet::len(self)
265    }
266
267    #[track_caller]
268    fn push(&mut self, elem: Self::Item) {
269        if IndexSet::insert(self, elem).is_err() {
270            capacity_exceeded()
271        }
272    }
273
274    fn clear(&mut self) {
275        IndexSet::clear(self)
276    }
277}
278
279impl<T: Eq + Hash, S: BuildHasher + Default, const N: usize> Collection for IndexSet<T, S, N> {
280    /// The capacity is fixed by the type, so this argument is ignored.
281    fn with_capacity(_capacity: usize) -> Self {
282        IndexSet::default()
283    }
284}
285
286impl<T: Eq + Hash, S: BuildHasher, const N: usize> CollectionCapacity for IndexSet<T, S, N> {
287    type ReserveError = CapacityError;
288
289    fn capacity(&self) -> usize {
290        IndexSet::capacity(self)
291    }
292
293    #[track_caller]
294    fn reserve(&mut self, additional: usize) {
295        if check_room(IndexSet::len(self), IndexSet::capacity(self), additional).is_err() {
296            capacity_exceeded()
297        }
298    }
299
300    fn try_reserve(&mut self, additional: usize) -> Result<(), Self::ReserveError> {
301        check_room(IndexSet::len(self), IndexSet::capacity(self), additional)
302    }
303
304    fn try_push(&mut self, elem: Self::Item) -> Result<(), Self::Item> {
305        IndexSet::insert(self, elem).map(|_| ())
306    }
307}
308
309impl<K: Eq + Hash, V, S: BuildHasher, const N: usize> CollectionBase for IndexMap<K, V, S, N> {
310    type Item = (K, V);
311
312    fn item_count(&self) -> usize {
313        IndexMap::len(self)
314    }
315
316    #[track_caller]
317    fn push(&mut self, elem: Self::Item) {
318        if IndexMap::insert(self, elem.0, elem.1).is_err() {
319            capacity_exceeded()
320        }
321    }
322
323    fn clear(&mut self) {
324        IndexMap::clear(self)
325    }
326}
327
328impl<K: Eq + Hash, V, S: BuildHasher + Default, const N: usize> Collection
329    for IndexMap<K, V, S, N>
330{
331    /// The capacity is fixed by the type, so this argument is ignored.
332    fn with_capacity(_capacity: usize) -> Self {
333        IndexMap::default()
334    }
335}
336
337impl<K: Eq + Hash, V, S: BuildHasher, const N: usize> CollectionCapacity for IndexMap<K, V, S, N> {
338    type ReserveError = CapacityError;
339
340    fn capacity(&self) -> usize {
341        IndexMap::capacity(self)
342    }
343
344    #[track_caller]
345    fn reserve(&mut self, additional: usize) {
346        if check_room(IndexMap::len(self), IndexMap::capacity(self), additional).is_err() {
347            capacity_exceeded()
348        }
349    }
350
351    fn try_reserve(&mut self, additional: usize) -> Result<(), Self::ReserveError> {
352        check_room(IndexMap::len(self), IndexMap::capacity(self), additional)
353    }
354
355    fn try_push(&mut self, elem: Self::Item) -> Result<(), Self::Item> {
356        IndexMap::insert(self, elem.0, elem.1).map(|_| ())
357    }
358}
359
360impl<K: Eq + Hash, V, S: BuildHasher, const N: usize> CollectionMap for IndexMap<K, V, S, N> {
361    type Key = K;
362    type Value = V;
363
364    fn contains_key(&self, key: &Self::Key) -> bool {
365        IndexMap::contains_key(self, key)
366    }
367
368    fn get(&self, key: &Self::Key) -> Option<&Self::Value> {
369        IndexMap::get(self, key)
370    }
371
372    fn get_mut(&mut self, key: &Self::Key) -> Option<&mut Self::Value> {
373        IndexMap::get_mut(self, key)
374    }
375
376    fn iter(&self) -> impl Iterator<Item = (&Self::Key, &Self::Value)> {
377        IndexMap::iter(self)
378    }
379
380    fn keys(&self) -> impl Iterator<Item = &Self::Key> {
381        IndexMap::keys(self)
382    }
383
384    fn values(&self) -> impl Iterator<Item = &Self::Value> {
385        IndexMap::values(self)
386    }
387
388    fn iter_mut(&mut self) -> impl Iterator<Item = (&Self::Key, &mut Self::Value)> {
389        IndexMap::iter_mut(self)
390    }
391
392    fn values_mut(&mut self) -> impl Iterator<Item = &mut Self::Value> {
393        IndexMap::values_mut(self)
394    }
395
396    #[track_caller]
397    fn insert(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value> {
398        match IndexMap::insert(self, key, value) {
399            Ok(previous) => previous,
400            Err(_) => capacity_exceeded(),
401        }
402    }
403
404    fn remove(&mut self, key: &Self::Key) -> Option<Self::Value> {
405        IndexMap::remove(self, key)
406    }
407
408    fn retain(&mut self, f: impl FnMut(&K, &mut V) -> bool) {
409        IndexMap::retain(self, f)
410    }
411}
412
413impl<K: Eq + Hash, V, S: BuildHasher, const N: usize> CollectionEntry for IndexMap<K, V, S, N> {
414    type Entry<'a>
415        = index_map::Entry<'a, K, V, N>
416    where
417        K: 'a,
418        V: 'a,
419        S: 'a;
420
421    fn entry(&mut self, key: Self::Key) -> Self::Entry<'_> {
422        IndexMap::entry(self, key)
423    }
424}
425
426impl<'a, K: Eq + Hash + 'a, V: 'a, const N: usize> MapEntry<'a> for index_map::Entry<'a, K, V, N> {
427    type Key = K;
428    type Value = V;
429
430    fn key(&self) -> &Self::Key {
431        index_map::Entry::key(self)
432    }
433
434    #[track_caller]
435    fn or_insert(self, default: Self::Value) -> &'a mut Self::Value {
436        match index_map::Entry::or_insert(self, default) {
437            Ok(value) => value,
438            Err(_) => capacity_exceeded(),
439        }
440    }
441
442    #[track_caller]
443    fn or_insert_with<F: FnOnce() -> Self::Value>(self, default: F) -> &'a mut Self::Value {
444        match index_map::Entry::or_insert_with(self, default) {
445            Ok(value) => value,
446            Err(_) => capacity_exceeded(),
447        }
448    }
449
450    #[track_caller]
451    fn or_default(self) -> &'a mut Self::Value
452    where
453        Self::Value: Default,
454    {
455        match index_map::Entry::or_default(self) {
456            Ok(value) => value,
457            Err(_) => capacity_exceeded(),
458        }
459    }
460
461    fn and_modify<F: FnOnce(&mut Self::Value)>(self, f: F) -> Self {
462        index_map::Entry::and_modify(self, f)
463    }
464}
465
466impl<K: Eq, V, const N: usize> CollectionBase for LinearMap<K, V, N> {
467    type Item = (K, V);
468
469    fn item_count(&self) -> usize {
470        LinearMap::len(self)
471    }
472
473    #[track_caller]
474    fn push(&mut self, elem: Self::Item) {
475        if LinearMap::insert(self, elem.0, elem.1).is_err() {
476            capacity_exceeded()
477        }
478    }
479
480    fn clear(&mut self) {
481        LinearMap::clear(self)
482    }
483}
484
485impl<K: Eq, V, const N: usize> CollectionCapacity for LinearMap<K, V, N> {
486    type ReserveError = CapacityError;
487
488    fn capacity(&self) -> usize {
489        LinearMap::capacity(self)
490    }
491
492    #[track_caller]
493    fn reserve(&mut self, additional: usize) {
494        if check_room(LinearMap::len(self), LinearMap::capacity(self), additional).is_err() {
495            capacity_exceeded()
496        }
497    }
498
499    fn try_reserve(&mut self, additional: usize) -> Result<(), Self::ReserveError> {
500        check_room(LinearMap::len(self), LinearMap::capacity(self), additional)
501    }
502
503    fn try_push(&mut self, elem: Self::Item) -> Result<(), Self::Item> {
504        LinearMap::insert(self, elem.0, elem.1).map(|_| ())
505    }
506}
507
508impl<K: Eq, V, const N: usize> CollectionMap for LinearMap<K, V, N> {
509    type Key = K;
510    type Value = V;
511
512    fn contains_key(&self, key: &Self::Key) -> bool {
513        LinearMap::contains_key(self, key)
514    }
515
516    fn get(&self, key: &Self::Key) -> Option<&Self::Value> {
517        LinearMap::get(self, key)
518    }
519
520    fn get_mut(&mut self, key: &Self::Key) -> Option<&mut Self::Value> {
521        LinearMap::get_mut(self, key)
522    }
523
524    fn iter(&self) -> impl Iterator<Item = (&Self::Key, &Self::Value)> {
525        LinearMap::iter(self)
526    }
527
528    fn keys(&self) -> impl Iterator<Item = &Self::Key> {
529        LinearMap::keys(self)
530    }
531
532    fn values(&self) -> impl Iterator<Item = &Self::Value> {
533        LinearMap::values(self)
534    }
535
536    fn iter_mut(&mut self) -> impl Iterator<Item = (&Self::Key, &mut Self::Value)> {
537        LinearMap::iter_mut(self)
538    }
539
540    fn values_mut(&mut self) -> impl Iterator<Item = &mut Self::Value> {
541        LinearMap::values_mut(self)
542    }
543
544    #[track_caller]
545    fn insert(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value> {
546        match LinearMap::insert(self, key, value) {
547            Ok(previous) => previous,
548            Err(_) => capacity_exceeded(),
549        }
550    }
551
552    fn remove(&mut self, key: &Self::Key) -> Option<Self::Value> {
553        LinearMap::remove(self, key)
554    }
555
556    fn retain(&mut self, f: impl FnMut(&K, &mut V) -> bool) {
557        LinearMap::retain(self, f)
558    }
559}