Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / third_party / betocore / np_adv / src / array_vec.rs

array_vec.rs218 lines · 7.4 KiBRaw
1// Copyright 2023 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Provides an [`ArrayVecOption`] wrapper implementation over [`ArrayVec`],
16//! which stores all the elements in an `Option` in order to satisfy
17//! `ArrayVec`'s requirement that the elements must implement `Default`.
18
19use tinyvec::{ArrayVec, ArrayVecIterator};
20#[cfg(any(test, feature = "alloc"))]
21extern crate alloc;
22#[cfg(any(test, feature = "alloc"))]
23use alloc::vec::Vec;
24
25/// A wrapper of [`ArrayVec`] that stores it values as [`Option`], in order to
26/// satisfy `ArrayVec`'s requirement that the elements must implement `Default`.
27/// The implementation guarantees that any items in the wrapped `ArrayVec`
28/// within `0..len` is `Some`, and therefore will not panic when unwrapped.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct ArrayVecOption<A, const N: usize>(ArrayVec<[Option<A>; N]>);
31
32// Cannot derive due to https://github.com/rust-lang/rust/issues/74462
33impl<A, const N: usize> Default for ArrayVecOption<A, N> {
34 fn default() -> Self {
35 Self(Default::default())
36 }
37}
38
39/// Iterator type returned by `ArrayVecOption.iter()`, which can be used as
40/// `impl Iterator<Item = &A>`
41pub type ArrayVecOptionRefIter<'a, A> =
42 core::iter::Map<core::slice::Iter<'a, Option<A>>, fn(&'a Option<A>) -> &'a A>;
43
44/// Iterator type returned by `ArrayVecOption.into_iter()`, which can be used as
45/// `impl Iterator<Item = A>`
46pub type ArrayVecOptionIntoIter<A, const N: usize> =
47 core::iter::Map<ArrayVecIterator<[Option<A>; N]>, fn(Option<A>) -> A>;
48
49impl<A, const N: usize> ArrayVecOption<A, N> {
50 /// Returns an iterator over this vec.
51 pub fn iter(&self) -> ArrayVecOptionRefIter<'_, A> {
52 self.0
53 .iter()
54 .map(|v| v.as_ref().expect("ArrayVecOption value before .len() should not be None"))
55 }
56
57 /// The length of the vec (in elements).
58 pub fn len(&self) -> usize {
59 self.0.len()
60 }
61
62 /// Checks if the length is 0.
63 pub fn is_empty(&self) -> bool {
64 self.0.is_empty()
65 }
66
67 /// Returns the first element of the vec, or `None` if it is empty.
68 pub fn first(&self) -> Option<&A> {
69 self.iter().next()
70 }
71
72 /// Place an element onto the end of the vec.
73 ///
74 /// # Panics
75 /// * If the length of the vec would overflow the capacity.
76 pub fn push(&mut self, value: A) {
77 self.0.push(Some(value))
78 }
79
80 /// Tries to place an element onto the end of the vec.
81 /// Returns back the element if the capacity is exhausted,
82 /// otherwise returns None.
83 pub fn try_push(&mut self, value: A) -> Option<A> {
84 self.0.try_push(Some(value)).unwrap_or_else(|| None)
85 }
86
87 /// Returns a reference to an element at the given index.
88 pub fn get(&self, index: usize) -> Option<&A> {
89 self.0.get(index).and_then(|opt| opt.as_ref())
90 }
91
92 /// Sorts the slice with a key extraction function, but might not preserve
93 /// the order of equal elements.
94 ///
95 /// This sort is unstable (i.e., may reorder equal elements), in-place
96 /// (i.e., does not allocate), and *O*(*m* \* *n* \* log(*n*)) worst-case,
97 /// where the key function is *O*(*m*).
98 pub fn sort_unstable_by_key<K: Ord>(&mut self, f: impl Fn(&A) -> K) {
99 self.0.sort_unstable_by_key(|a| {
100 f(a.as_ref().expect("Iterated values in ArrayVecOption should never be None"))
101 })
102 }
103
104 /// Remove an element, swapping the end of the vec into its place.
105 pub fn swap_remove(&mut self, index: usize) -> A {
106 self.0.swap_remove(index).expect("since index is is bounds, the value at index will always be Some which is safe to unwrap")
107 }
108
109 /// Converts this vector into a regular `Vec`, unwrapping all of the
110 /// `Option` in the process.
111 #[cfg(any(test, feature = "alloc"))]
112 pub fn into_vec(self) -> Vec<A> {
113 self.into_iter().collect()
114 }
115}
116
117impl<A, const N: usize> IntoIterator for ArrayVecOption<A, N> {
118 type Item = A;
119 type IntoIter = ArrayVecOptionIntoIter<A, N>;
120 fn into_iter(self) -> Self::IntoIter {
121 self.0
122 .into_iter()
123 .map(|v| v.expect("ArrayVecOption value before .len() should not be None"))
124 }
125}
126
127// Implement `FromIterator` to enable `iter.collect::<ArrayVecOption<_>>()`
128impl<A, const N: usize> FromIterator<A> for ArrayVecOption<A, N> {
129 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
130 Self(iter.into_iter().map(Some).collect())
131 }
132}
133
134impl<A, const N: usize> core::ops::Index<usize> for ArrayVecOption<A, N> {
135 type Output = A;
136 fn index(&self, index: usize) -> &Self::Output {
137 self.0[index].as_ref().expect("This panics if provided index is out of bounds")
138 }
139}
140
141impl<A, const N: usize> core::ops::IndexMut<usize> for ArrayVecOption<A, N> {
142 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
143 self.0[index].as_mut().expect("This panics if provided index is out of bounds")
144 }
145}
146
147#[cfg(test)]
148mod test {
149 extern crate std;
150 use super::ArrayVecOption;
151 use std::vec;
152
153 #[test]
154 fn test_default_array_vec() {
155 let vec = ArrayVecOption::<u32, 5>::default();
156 assert_eq!(0, vec.len());
157 assert_eq!(None, vec.iter().next());
158 assert!(vec.is_empty());
159 assert_eq!(None, vec.first());
160 assert_eq!(None, vec.get(0));
161 assert_eq!(vec![0_u32; 0], vec.into_vec());
162 }
163
164 #[test]
165 fn test_array_vec_with_contents() {
166 let mut vec = ArrayVecOption::<u32, 5>::default();
167 vec.push(1);
168 vec.push(2);
169 vec.push(3);
170 vec.push(4);
171 vec.push(5);
172 assert_eq!(5, vec.len());
173 let mut iter = vec.iter();
174 assert_eq!(Some(&1_u32), iter.next());
175 assert_eq!(Some(&2_u32), iter.next());
176 assert_eq!(Some(&3_u32), iter.next());
177 assert_eq!(Some(&4_u32), iter.next());
178 assert_eq!(Some(&5_u32), iter.next());
179 assert_eq!(None, iter.next());
180 assert!(!vec.is_empty());
181 assert_eq!(Some(&1_u32), vec.first());
182 assert_eq!(Some(&5_u32), vec.get(4));
183 assert_eq!(vec![1_u32, 2, 3, 4, 5], vec.clone().into_vec());
184
185 let _ = vec.swap_remove(2);
186 assert_eq!(vec![1_u32, 2, 5, 4], vec.clone().into_vec());
187 }
188
189 #[test]
190 #[should_panic]
191 fn test_array_vec_push_overflow() {
192 let mut vec = ArrayVecOption::<u32, 5>::default();
193 vec.push(1);
194 vec.push(2);
195 vec.push(3);
196 vec.push(4);
197 vec.push(5);
198 vec.push(6);
199 }
200
201 #[test]
202 fn test_sort() {
203 let mut vec = ArrayVecOption::<u32, 5>::default();
204 vec.push(3);
205 vec.push(1);
206 vec.push(4);
207 vec.push(1);
208 vec.push(2);
209 vec.sort_unstable_by_key(|k| *k);
210 assert_eq!(vec![1_u32, 1, 2, 3, 4], vec.clone().into_vec());
211 }
212
213 #[test]
214 fn test_collect() {
215 let vec: ArrayVecOption<u32, 5> = [5_u32, 4, 3, 2, 1].into_iter().collect();
216 assert_eq!(vec![5_u32, 4, 3, 2, 1], vec.clone().into_vec());
217 }
218}