foundation_ur/collections/
vec.rs

1// SPDX-FileCopyrightText: © 2023 Foundation Devices, Inc. <hello@foundationdevices.com>
2// SPDX-FileCopyrightText: © 2020 Dominik Spicher <dominikspicher@gmail.com>
3// SPDX-License-Identifier: MIT
4
5use core::ops::{Deref, DerefMut};
6
7/// Error that can occur when reserving memory on a [`Vec`].
8#[derive(Debug)]
9pub struct TryReserveError;
10
11/// A vector collection.
12pub trait Vec<T>:
13    AsMut<[T]>
14    + AsRef<[T]>
15    + Default
16    + Deref<Target = [T]>
17    + DerefMut<Target = [T]>
18    + Extend<T>
19    + FromIterator<T>
20{
21    /// Clear the collection.
22    fn clear(&mut self);
23
24    /// Returns the capacity of the collection.
25    fn capacity(&self) -> usize;
26
27    /// Reserve additional capacity for the collection.
28    fn reserve(&mut self, capacity: usize);
29
30    /// Resize the collection to the new length using `value` as the default
31    /// value for new elements.
32    fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), TryReserveError>
33    where
34        T: Clone;
35
36    /// Push a new element to the back of the collection.
37    fn try_push(&mut self, value: T) -> Result<(), TryReserveError>;
38
39    /// Pop an element from the back of the collection.
40    fn pop(&mut self) -> Option<T>;
41
42    /// Remove an element from the collection using it's index.
43    fn remove(&mut self, index: usize) -> T;
44
45    /// Retain elements.
46    fn retain_mut<F>(&mut self, f: F)
47    where
48        F: FnMut(&mut T) -> bool;
49
50    /// Try extending the vector from an existing slice.
51    fn try_extend_from_slice(&mut self, slice: &[T]) -> Result<(), TryReserveError>
52    where
53        T: Clone;
54}
55
56#[cfg(feature = "alloc")]
57impl<T> Vec<T> for alloc::vec::Vec<T> {
58    fn clear(&mut self) {
59        alloc::vec::Vec::clear(self)
60    }
61
62    fn capacity(&self) -> usize {
63        alloc::vec::Vec::capacity(self)
64    }
65
66    fn reserve(&mut self, capacity: usize) {
67        alloc::vec::Vec::reserve(self, capacity)
68    }
69
70    fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), TryReserveError>
71    where
72        T: Clone,
73    {
74        if new_len > self.len() {
75            let additional = new_len - self.len();
76            if alloc::vec::Vec::try_reserve(self, additional).is_err() {
77                return Err(TryReserveError);
78            }
79        }
80
81        alloc::vec::Vec::resize(self, new_len, value);
82        Ok(())
83    }
84
85    fn try_push(&mut self, value: T) -> Result<(), TryReserveError> {
86        alloc::vec::Vec::push(self, value);
87        Ok(())
88    }
89
90    fn pop(&mut self) -> Option<T> {
91        alloc::vec::Vec::pop(self)
92    }
93
94    fn remove(&mut self, index: usize) -> T {
95        alloc::vec::Vec::remove(self, index)
96    }
97
98    fn retain_mut<F>(&mut self, f: F)
99    where
100        F: FnMut(&mut T) -> bool,
101    {
102        alloc::vec::Vec::retain_mut(self, f)
103    }
104
105    fn try_extend_from_slice(&mut self, slice: &[T]) -> Result<(), TryReserveError>
106    where
107        T: Clone,
108    {
109        if alloc::vec::Vec::try_reserve(self, slice.len()).is_err() {
110            return Err(TryReserveError);
111        }
112
113        alloc::vec::Vec::extend_from_slice(self, slice);
114
115        Ok(())
116    }
117}
118
119impl<T, const N: usize> Vec<T> for heapless::Vec<T, N> {
120    fn clear(&mut self) {
121        heapless::Vec::clear(self)
122    }
123
124    fn capacity(&self) -> usize {
125        heapless::Vec::capacity(self)
126    }
127
128    fn reserve(&mut self, capacity: usize) {
129        let remaining_capacity = heapless::Vec::capacity(self) - (self as &[_]).len();
130        if remaining_capacity < capacity {
131            panic!(
132                "can't reserve more capacity, remaining {} and need {}",
133                remaining_capacity,
134                capacity - remaining_capacity
135            );
136        }
137    }
138
139    fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), TryReserveError>
140    where
141        T: Clone,
142    {
143        heapless::Vec::resize(self, new_len, value).map_err(|_| TryReserveError)
144    }
145
146    fn try_push(&mut self, value: T) -> Result<(), TryReserveError> {
147        heapless::Vec::push(self, value).map_err(|_| TryReserveError)
148    }
149
150    fn pop(&mut self) -> Option<T> {
151        heapless::Vec::pop(self)
152    }
153
154    fn remove(&mut self, index: usize) -> T {
155        heapless::Vec::remove(self, index)
156    }
157
158    fn retain_mut<F>(&mut self, f: F)
159    where
160        F: FnMut(&mut T) -> bool,
161    {
162        heapless::Vec::retain_mut(self, f)
163    }
164
165    fn try_extend_from_slice(&mut self, slice: &[T]) -> Result<(), TryReserveError>
166    where
167        T: Clone,
168    {
169        heapless::Vec::extend_from_slice(self, slice).map_err(|_| TryReserveError)
170    }
171}