ombre: Add `array` module

2243b507f7a59c7705947295d74306d0bfd4b9cd
Implements a fixed size `Vec`-like collection.
Alexis Sellier committed ago 1 parent 884cec5e
ombre/src/array.rs added +355 -0
1 +
//! A fixed-capacity array implementation with runtime length tracking.
2 +
use std::error::Error;
3 +
use std::fmt;
4 +
use std::mem::MaybeUninit;
5 +
6 +
/// Error type for [`Array`] operations.
7 +
#[derive(Debug, Clone, PartialEq, Eq)]
8 +
pub enum ArrayError {
9 +
    /// Returned when attempting to add elements to a full array.
10 +
    CapacityExceeded(usize),
11 +
}
12 +
13 +
impl fmt::Display for ArrayError {
14 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15 +
        match self {
16 +
            ArrayError::CapacityExceeded(cap) => write!(f, "array capacity ({cap}) exceeded"),
17 +
        }
18 +
    }
19 +
}
20 +
impl Error for ArrayError {}
21 +
22 +
/// A fixed-capacity array that tracks its length at runtime.
23 +
///
24 +
/// The array is backed by uninitialized memory and manages initialization
25 +
/// safely through [`MaybeUninit`].
26 +
#[derive(Debug)]
27 +
pub struct Array<T, const N: usize> {
28 +
    data: [MaybeUninit<T>; N],
29 +
    len: usize,
30 +
}
31 +
32 +
impl<T, const N: usize> Default for Array<T, N> {
33 +
    fn default() -> Self {
34 +
        Self::new()
35 +
    }
36 +
}
37 +
38 +
impl<T, const N: usize> Array<T, N> {
39 +
    /// Creates a new empty array with fixed capacity N.
40 +
    ///
41 +
    /// The array is initialized with uninitialized memory, but this is
42 +
    /// safely wrapped in [`MaybeUninit`].
43 +
    pub fn new() -> Self {
44 +
        Self {
45 +
            data: unsafe { MaybeUninit::uninit().assume_init() },
46 +
            len: 0,
47 +
        }
48 +
    }
49 +
50 +
    /// Appends an element to the end of the array.
51 +
    ///
52 +
    /// Returns an error if the array is already at capacity.
53 +
    ///
54 +
    /// ```
55 +
    /// use ombre::prelude::Array;
56 +
    ///
57 +
    /// let mut array: Array<i32, 2> = Array::new();
58 +
    ///
59 +
    /// assert!(array.push(1).is_ok());
60 +
    /// assert!(array.push(2).is_ok());
61 +
    /// assert!(array.push(3).is_err()); // Array is full.
62 +
    /// ```
63 +
    pub fn push(&mut self, value: T) -> Result<(), ArrayError> {
64 +
        if self.len >= N {
65 +
            return Err(ArrayError::CapacityExceeded(N));
66 +
        }
67 +
        self.data[self.len].write(value);
68 +
        self.len += 1;
69 +
70 +
        Ok(())
71 +
    }
72 +
73 +
    /// Removes and returns the last element from the array.
74 +
    ///
75 +
    /// Returns `None` if the array is empty.
76 +
    pub fn pop(&mut self) -> Option<T> {
77 +
        if self.len == 0 {
78 +
            return None;
79 +
        }
80 +
        self.len -= 1;
81 +
        Some(unsafe { self.data[self.len].assume_init_read() })
82 +
    }
83 +
84 +
    /// Removes all elements from the array.
85 +
    ///
86 +
    /// This will drop all contained elements.
87 +
    pub fn clear(&mut self) {
88 +
        while self.pop().is_some() {}
89 +
    }
90 +
91 +
    /// Returns the number of elements in the array.
92 +
    pub fn len(&self) -> usize {
93 +
        self.len
94 +
    }
95 +
96 +
    /// Returns `true` if the array contains no elements.
97 +
    pub fn is_empty(&self) -> bool {
98 +
        self.len == 0
99 +
    }
100 +
101 +
    /// Returns the total capacity of the array (N).
102 +
    pub fn capacity(&self) -> usize {
103 +
        N
104 +
    }
105 +
106 +
    /// Returns a slice containing the entire array.
107 +
    ///
108 +
    /// # Safety
109 +
    ///
110 +
    /// This operation is safe because we maintain the invariant that
111 +
    /// all elements up to `len` are properly initialized.
112 +
    pub fn as_slice(&self) -> &[T] {
113 +
        unsafe { std::slice::from_raw_parts(self.data.as_ptr() as *const T, self.len) }
114 +
    }
115 +
116 +
    /// Returns a mutable slice containing the entire array.
117 +
    ///
118 +
    /// # Safety
119 +
    ///
120 +
    /// This operation is safe because we maintain the invariant that
121 +
    /// all elements up to `len` are properly initialized.
122 +
    pub fn as_mut_slice(&mut self) -> &mut [T] {
123 +
        unsafe { std::slice::from_raw_parts_mut(self.data.as_mut_ptr() as *mut T, self.len) }
124 +
    }
125 +
126 +
    /// Removes an element from the array and returns it, replacing it with the last element.
127 +
    ///
128 +
    /// This operation is O(1) as it does not preserve ordering.
129 +
    ///
130 +
    /// # Panics
131 +
    ///
132 +
    /// Panics if `index` is out of bounds.
133 +
    pub fn swap_remove(&mut self, index: usize) -> T {
134 +
        assert!(index < self.len, "Array::swap_remove: index out of bounds");
135 +
136 +
        self.len -= 1;
137 +
        unsafe {
138 +
            if index == self.len {
139 +
                self.data[index].assume_init_read()
140 +
            } else {
141 +
                let out = self.data[index].assume_init_read();
142 +
                self.data[index].write(self.data[self.len].assume_init_read());
143 +
                out
144 +
            }
145 +
        }
146 +
    }
147 +
148 +
    /// Shortens the array, keeping the first `len` elements and dropping the rest.
149 +
    ///
150 +
    /// If `len` is greater than the current length, this has no effect.
151 +
    pub fn truncate(&mut self, len: usize) {
152 +
        while self.len > len {
153 +
            self.pop();
154 +
        }
155 +
    }
156 +
157 +
    /// Extends the array with the contents of an iterator.
158 +
    ///
159 +
    /// Returns an error if the iterator would cause the array to exceed its capacity.
160 +
    pub fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) -> Result<(), ArrayError> {
161 +
        for item in iter {
162 +
            self.push(item)?;
163 +
        }
164 +
        Ok(())
165 +
    }
166 +
}
167 +
168 +
impl<T, const N: usize> Drop for Array<T, N> {
169 +
    fn drop(&mut self) {
170 +
        for i in 0..self.len {
171 +
            unsafe { self.data[i].assume_init_drop() };
172 +
        }
173 +
    }
174 +
}
175 +
176 +
impl<T, const N: usize> std::ops::Index<usize> for Array<T, N> {
177 +
    type Output = T;
178 +
179 +
    fn index(&self, index: usize) -> &Self::Output {
180 +
        assert!(index < self.len, "Array::index: index out of bounds");
181 +
        unsafe { &*self.data[index].as_ptr() }
182 +
    }
183 +
}
184 +
185 +
impl<T, const N: usize> std::ops::IndexMut<usize> for Array<T, N> {
186 +
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
187 +
        assert!(index < self.len, "Array::index_mut: index out of bounds");
188 +
        unsafe { &mut *self.data[index].as_mut_ptr() }
189 +
    }
190 +
}
191 +
192 +
impl<T, const N: usize> Array<T, N> {
193 +
    /// Returns an iterator over references to the elements of the array.
194 +
    pub fn iter(&self) -> std::slice::Iter<'_, T> {
195 +
        self.as_slice().iter()
196 +
    }
197 +
198 +
    /// Returns an iterator over mutable references to the elements of the array.
199 +
    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> {
200 +
        self.as_mut_slice().iter_mut()
201 +
    }
202 +
}
203 +
204 +
impl<T, const N: usize> IntoIterator for Array<T, N> {
205 +
    type Item = T;
206 +
    type IntoIter = IntoIter<T, N>;
207 +
208 +
    fn into_iter(self) -> Self::IntoIter {
209 +
        IntoIter {
210 +
            vec: self,
211 +
            index: 0,
212 +
        }
213 +
    }
214 +
}
215 +
216 +
pub struct IntoIter<T, const N: usize> {
217 +
    vec: Array<T, N>,
218 +
    index: usize,
219 +
}
220 +
221 +
impl<T, const N: usize> Iterator for IntoIter<T, N> {
222 +
    type Item = T;
223 +
224 +
    fn next(&mut self) -> Option<Self::Item> {
225 +
        if self.index >= self.vec.len {
226 +
            return None;
227 +
        }
228 +
        let index = self.index;
229 +
        self.index += 1;
230 +
231 +
        // SAFETY: Safe because index is less than len.
232 +
        Some(unsafe { self.vec.data[index].assume_init_read() })
233 +
    }
234 +
235 +
    fn size_hint(&self) -> (usize, Option<usize>) {
236 +
        let remaining = self.vec.len - self.index;
237 +
        (remaining, Some(remaining))
238 +
    }
239 +
}
240 +
241 +
#[cfg(test)]
242 +
#[allow(clippy::unwrap_used)]
243 +
mod tests {
244 +
    use super::*;
245 +
246 +
    #[test]
247 +
    fn test_new() {
248 +
        let array: Array<i32, 5> = Array::new();
249 +
        assert_eq!(array.len(), 0);
250 +
        assert_eq!(array.capacity(), 5);
251 +
        assert!(array.is_empty());
252 +
    }
253 +
254 +
    #[test]
255 +
    fn test_len() {
256 +
        let mut array: Array<i32, 5> = Array::new();
257 +
        array.push(1).unwrap();
258 +
        array.push(2).unwrap();
259 +
        array.push(3).unwrap();
260 +
261 +
        assert_eq!(array.len(), 3);
262 +
        assert_eq!(array.is_empty(), false);
263 +
    }
264 +
265 +
    #[test]
266 +
    fn test_push_pop() {
267 +
        let mut array: Array<i32, 3> = Array::new();
268 +
269 +
        assert!(array.push(1).is_ok());
270 +
        assert!(array.push(2).is_ok());
271 +
        assert!(array.push(3).is_ok());
272 +
        assert_eq!(array.push(4), Err(ArrayError::CapacityExceeded(3)));
273 +
274 +
        assert_eq!(array.pop(), Some(3));
275 +
        assert_eq!(array.pop(), Some(2));
276 +
        assert_eq!(array.pop(), Some(1));
277 +
        assert_eq!(array.pop(), None);
278 +
        assert_eq!(array.len(), 0);
279 +
    }
280 +
281 +
    #[test]
282 +
    fn test_indexing() {
283 +
        let mut array: Array<i32, 3> = Array::new();
284 +
        array.push(10).unwrap();
285 +
        array.push(20).unwrap();
286 +
        array.push(30).unwrap();
287 +
288 +
        assert_eq!(array[0], 10);
289 +
        assert_eq!(array[1], 20);
290 +
        assert_eq!(array[2], 30);
291 +
292 +
        array[1] = 25;
293 +
        assert_eq!(array[1], 25);
294 +
    }
295 +
296 +
    #[test]
297 +
    #[should_panic(expected = "Array::index: index out of bounds")]
298 +
    fn test_index_out_of_bounds() {
299 +
        let mut array: Array<i32, 2> = Array::new();
300 +
        array.push(1).unwrap();
301 +
        let _value = array[1]; // This should panic.
302 +
    }
303 +
304 +
    #[test]
305 +
    fn test_clear() {
306 +
        let mut array: Array<i32, 3> = Array::new();
307 +
308 +
        array.push(1).unwrap();
309 +
        array.push(2).unwrap();
310 +
        array.clear();
311 +
312 +
        assert_eq!(array.len(), 0);
313 +
        assert!(array.is_empty());
314 +
    }
315 +
316 +
    #[test]
317 +
    fn test_swap_remove() {
318 +
        let mut array: Array<i32, 4> = Array::new();
319 +
        array.extend([1, 2, 3, 4]).unwrap();
320 +
321 +
        let removed = array.swap_remove(1);
322 +
        assert_eq!(removed, 2);
323 +
        assert_eq!(array.as_slice(), &[1, 4, 3]);
324 +
    }
325 +
326 +
    #[test]
327 +
    fn test_iterator() {
328 +
        let mut array: Array<i32, 3> = Array::new();
329 +
        array.extend([1, 2, 3]).unwrap();
330 +
331 +
        let mut iter = array.into_iter();
332 +
        assert_eq!(iter.next(), Some(1));
333 +
        assert_eq!(iter.next(), Some(2));
334 +
        assert_eq!(iter.next(), Some(3));
335 +
        assert_eq!(iter.next(), None);
336 +
    }
337 +
338 +
    #[test]
339 +
    fn test_drop() {
340 +
        use std::rc::Rc;
341 +
342 +
        let mut array: Array<Rc<i32>, 2> = Array::new();
343 +
        let value = Rc::new(42);
344 +
345 +
        array.push(value.clone()).unwrap();
346 +
        array.push(value.clone()).unwrap();
347 +
        assert_eq!(Rc::strong_count(&value), 3);
348 +
349 +
        array.pop();
350 +
        assert_eq!(Rc::strong_count(&value), 2);
351 +
352 +
        drop(array);
353 +
        assert_eq!(Rc::strong_count(&value), 1);
354 +
    }
355 +
}
ombre/src/lib.rs +2 -0
6 6
#![warn(clippy::unwrap_used)]
7 7
8 8
#[cfg(feature = "draw")]
9 9
extern crate self as ombre;
10 10
11 +
pub mod array;
11 12
pub mod bench;
12 13
pub mod bytes;
13 14
pub mod collections;
14 15
#[cfg(feature = "draw")]
15 16
pub mod draw;
33 34
pub use gfx::color;
34 35
pub use glow;
35 36
36 37
/// Crate prelude.
37 38
pub mod prelude {
39 +
    pub use super::array::Array;
38 40
    pub use super::bytes;
39 41
    pub use super::gfx;
40 42
    pub use super::gfx::*;
41 43
    pub use super::math::{
42 44
        coord::*, Point2D, Rect, Size, Transform3D, Vector2D, Vector3D, Zero as _,