collections/traits.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
22/// Trait implemented by all collection types.
23///
24/// # Collection contract
25///
26/// `item_count()` returns the number of values of `Item` held by the
27/// collection. For UTF-8 strings this counts `char`s and is O(n); it is O(1)
28/// for other collections. `is_empty()` is O(1) for every implementation.
29/// `push()` appends to sequences and linked lists, adds to a `BinaryHeap`,
30/// inserts into sets and maps, and appends a `char` to strings. Duplicate set
31/// values do not increase the item count; inserting an existing map key
32/// replaces its value.
33///
34/// `push()` is infallible: growable collections abort or panic when the
35/// allocation fails, and fixed-capacity collections panic when they are full.
36/// Use [`CollectionCapacity::try_push`] to get the item back instead.
37///
38/// No length method is defined by this trait, so a concrete type's inherent
39/// `len()` remains unambiguous. Use [`CollectionBytes`] when the byte length is
40/// needed.
41///
42/// ```compile_fail,E0599
43/// use collections::CollectionBase;
44///
45/// fn length<C: CollectionBase>(collection: &C) -> usize {
46/// collection.len()
47/// }
48/// ```
49pub trait CollectionBase {
50 /// Item type contained within the collection.
51 type Item;
52
53 /// Returns the number of `Item`s in the collection.
54 ///
55 /// This is O(n) for UTF-8 strings, where it counts `char`s, and O(1) for
56 /// all other collection types.
57 fn item_count(&self) -> usize;
58
59 /// Detects whether a collection is empty. This is O(1) for every
60 /// implementation.
61 #[inline]
62 fn is_empty(&self) -> bool {
63 self.item_count() == 0
64 }
65
66 /// Appends or inserts an element into the collection.
67 ///
68 /// # Panics
69 ///
70 /// Panics if a fixed-capacity collection is full. Growable collections
71 /// panic or abort if the required memory cannot be allocated.
72 fn push(&mut self, elem: Self::Item);
73
74 /// Removes all elements from the collection.
75 fn clear(&mut self);
76}
77
78/// Trait for contiguous byte collections.
79///
80/// It is implemented for UTF-8 strings and byte buffers, but not for general
81/// collections whose items happen to be bytes.
82///
83/// ```compile_fail,E0277
84/// use collections::CollectionBytes;
85///
86/// fn bytes<C: CollectionBytes>(collection: &C) -> usize {
87/// collection.byte_len()
88/// }
89///
90/// let values = vec![1_u32, 2];
91/// bytes(&values);
92/// ```
93pub trait CollectionBytes: CollectionBase {
94 /// Returns the number of bytes stored in the collection. This is O(1).
95 fn byte_len(&self) -> usize;
96
97 /// Returns the number of bytes added by pushing `item`.
98 fn item_byte_len(item: &Self::Item) -> usize;
99}
100
101/// Trait implemented by collections with a default constructor and iterator
102/// support.
103///
104/// `with_capacity()` reserves space for the requested number of items for
105/// sequences, heaps, sets and maps, or bytes for strings. `BTreeSet`,
106/// `BTreeMap` and `LinkedList` cannot reserve capacity and ignore the argument,
107/// as do fixed-capacity collections, whose capacity is a part of the type.
108///
109/// An empty collection is created with `Default::default()`.
110pub trait Collection:
111 CollectionBase + Default + FromIterator<Self::Item> + Extend<Self::Item>
112{
113 /// Creates a new collection with the requested capacity where supported.
114 ///
115 /// The capacity must not come from an untrusted source: growable
116 /// collections panic or abort if it cannot be allocated. Create an empty
117 /// collection and use [`CollectionCapacity::try_reserve`] instead.
118 fn with_capacity(capacity: usize) -> Self;
119}
120
121/// Trait implemented by collections that support custom allocators.
122///
123/// Unlike [`Collection`], this trait does not require `FromIterator`, since
124/// allocator-aware collections cannot always be constructed by `collect()`.
125pub trait CollectionAlloc: CollectionBase + Extend<Self::Item> + Sized {
126 /// Allocator used by the collection.
127 type Allocator;
128
129 /// Creates a new collection with the requested capacity and allocator.
130 fn with_capacity_in(capacity: usize, allocator: Self::Allocator) -> Self;
131
132 /// Creates an empty collection with the given allocator.
133 fn new_in(allocator: Self::Allocator) -> Self {
134 Self::with_capacity_in(0, allocator)
135 }
136
137 /// Returns a reference to the collection's allocator.
138 fn allocator(&self) -> &Self::Allocator;
139}
140
141/// Trait implemented by collections that can reserve storage capacity.
142///
143/// Capacity and reservation amounts use the collection's native storage unit:
144/// bytes for strings and items for other collections. A string with a capacity
145/// of `n` may therefore hold fewer than `n` `char`s.
146///
147/// Fixed-capacity collections never allocate: their capacity is constant, and
148/// a reservation only checks that the requested room is left.
149///
150/// # Untrusted sizes
151///
152/// [`Collection::with_capacity`], [`CollectionAlloc::with_capacity_in`] and
153/// [`reserve`](Self::reserve) panic or abort the process when the requested
154/// memory cannot be allocated, which makes a size taken from untrusted input a
155/// denial-of-service vector. Use [`try_reserve`](Self::try_reserve) and
156/// [`try_push`](Self::try_push) for such sizes and data.
157pub trait CollectionCapacity: CollectionBase {
158 /// Error returned when a reservation cannot be satisfied.
159 type ReserveError;
160
161 /// Returns the current capacity in the collection's native storage unit.
162 fn capacity(&self) -> usize;
163
164 /// Reserves space for at least `additional` more storage units.
165 ///
166 /// # Panics
167 ///
168 /// Panics or aborts if the allocation fails or the new capacity overflows.
169 /// Panics if a fixed-capacity collection has less room left.
170 fn reserve(&mut self, additional: usize);
171
172 /// Attempts to reserve space for at least `additional` more storage units
173 /// without panicking or aborting on failure.
174 fn try_reserve(&mut self, additional: usize) -> Result<(), Self::ReserveError>;
175
176 /// Attempts to append or insert an item without panicking or aborting when
177 /// there is no room for it.
178 ///
179 /// Returns the item if the required capacity cannot be reserved. Inserting
180 /// an already present set value or map key into a full fixed-capacity
181 /// collection succeeds, since it needs no room.
182 fn try_push(&mut self, elem: Self::Item) -> Result<(), Self::Item> {
183 if self.try_reserve(1).is_err() {
184 return Err(elem);
185 }
186 self.push(elem);
187 Ok(())
188 }
189}
190
191/// Trait implemented by key-value maps.
192pub trait CollectionMap: CollectionBase<Item = (Self::Key, Self::Value)> {
193 /// Key type for the collection.
194 type Key;
195 /// Value type for the collection.
196 type Value;
197
198 /// Checks whether a given key is contained in the collection.
199 fn contains_key(&self, key: &Self::Key) -> bool;
200
201 /// Gets a value of the collection.
202 fn get(&self, key: &Self::Key) -> Option<&Self::Value>;
203
204 /// Gets a mutable value of the collection.
205 fn get_mut(&mut self, key: &Self::Key) -> Option<&mut Self::Value>;
206
207 /// Returns iterator over keys and values.
208 fn iter(&self) -> impl Iterator<Item = (&Self::Key, &Self::Value)>;
209
210 /// Returns an iterator over the keys.
211 fn keys(&self) -> impl Iterator<Item = &Self::Key> {
212 self.iter().map(|(key, _)| key)
213 }
214
215 /// Returns an iterator over the values.
216 fn values(&self) -> impl Iterator<Item = &Self::Value> {
217 self.iter().map(|(_, value)| value)
218 }
219
220 /// Returns iterator over keys and mutable values.
221 fn iter_mut(&mut self) -> impl Iterator<Item = (&Self::Key, &mut Self::Value)>;
222
223 /// Constructs iterator over mutable values.
224 fn values_mut(&mut self) -> impl Iterator<Item = &mut Self::Value>;
225
226 /// Inserts a new value under a key. Returns previous value if a value under
227 /// the key was already present in the collection.
228 fn insert(&mut self, key: Self::Key, value: Self::Value) -> Option<Self::Value>;
229
230 /// Removes a value stored under a given key, returning an owned value if
231 /// it was in the collection.
232 fn remove(&mut self, key: &Self::Key) -> Option<Self::Value>;
233
234 /// Retains only the elements specified by the predicate.
235 ///
236 /// In other words, remove all pairs `(k, v)` for which `f(&k, &mut v)`
237 /// returns `false`. The elements are visited in unsorted (and
238 /// unspecified) order.
239 fn retain(&mut self, f: impl FnMut(&Self::Key, &mut Self::Value) -> bool);
240}
241
242/// Trait implemented by set collections.
243pub trait CollectionSet: CollectionBase {
244 /// Checks whether an equal item is present in the set.
245 fn contains(&self, item: &Self::Item) -> bool;
246
247 /// Returns a reference to the stored item equal to the given item.
248 fn get(&self, item: &Self::Item) -> Option<&Self::Item>;
249
250 /// Returns an iterator over the set's items.
251 fn iter(&self) -> impl Iterator<Item = &Self::Item>;
252
253 /// Inserts an item, returning whether the set did not already contain it.
254 fn insert(&mut self, item: Self::Item) -> bool;
255
256 /// Inserts an item or replaces an equal one, returning the previous item if
257 /// any.
258 fn replace(&mut self, item: Self::Item) -> Option<Self::Item>;
259
260 /// Removes an equal item, returning whether it was present.
261 fn remove(&mut self, item: &Self::Item) -> bool;
262
263 /// Removes an equal item and returns the stored item if present.
264 fn take(&mut self, item: &Self::Item) -> Option<Self::Item>;
265
266 /// Retains only the items specified by the predicate.
267 fn retain(&mut self, f: impl FnMut(&Self::Item) -> bool);
268}
269
270/// Trait implemented by maps that expose an in-place entry API.
271pub trait CollectionEntry: CollectionMap {
272 /// Native entry type used for in-place map operations.
273 type Entry<'a>: MapEntry<'a, Key = Self::Key, Value = Self::Value>
274 where
275 Self: 'a;
276
277 /// Gets the given key's corresponding entry in the map for in-place
278 /// manipulation.
279 fn entry(&mut self, key: Self::Key) -> Self::Entry<'_>;
280}
281
282/// Common interface over the native entry types of maps.
283pub trait MapEntry<'a>: Sized {
284 /// Key type stored in the map.
285 type Key;
286 /// Value type stored in the map.
287 type Value: 'a;
288
289 /// Returns the key associated with this entry.
290 fn key(&self) -> &Self::Key;
291
292 /// Inserts the provided value if the entry is vacant, then returns it.
293 fn or_insert(self, default: Self::Value) -> &'a mut Self::Value;
294
295 /// Inserts a value produced by `default` if the entry is vacant.
296 fn or_insert_with<F: FnOnce() -> Self::Value>(self, default: F) -> &'a mut Self::Value;
297
298 /// Inserts the default value if the entry is vacant.
299 fn or_default(self) -> &'a mut Self::Value
300 where
301 Self::Value: Default;
302
303 /// Applies `f` to the value if the entry is occupied.
304 fn and_modify<F: FnOnce(&mut Self::Value)>(self, f: F) -> Self;
305}