furiosa_visa_std/
array_vec.rs

1use std::ops::{Deref, DerefMut};
2
3use arrayvec::ArrayVec as ArrayVecInner;
4
5/// Compile-time check that N <= CAP.
6const fn check_capacity<const N: usize, const CAP: usize>() {
7    assert!(N <= CAP, "Array size exceeds capacity");
8}
9
10/// Wrapper around `arrayvec::ArrayVec` that allows initialization with arrays smaller than capacity.
11///
12/// # Example
13/// ```ignore
14/// let arr: ArrayVec<i32, 8> = ArrayVec::new([1, 2, 3]); // capacity 8, length 3
15/// ```
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct ArrayVec<T, const CAP: usize>(ArrayVecInner<T, CAP>);
18
19impl<T, const CAP: usize> Default for ArrayVec<T, CAP> {
20    fn default() -> Self {
21        Self(ArrayVecInner::new())
22    }
23}
24
25impl<T, const CAP: usize> ArrayVec<T, CAP> {
26    /// Creates a new ArrayVec from an array. The array size N can be smaller than capacity CAP.
27    /// Compile-time error if N > CAP.
28    pub fn new<const N: usize>(arr: [T; N]) -> Self {
29        check_capacity::<N, CAP>();
30        let mut inner = ArrayVecInner::new();
31        for item in arr {
32            inner.push(item);
33        }
34        Self(inner)
35    }
36
37    /// Creates an empty ArrayVec.
38    pub fn empty() -> Self {
39        Self(ArrayVecInner::new())
40    }
41}
42
43impl<T, const CAP: usize> Deref for ArrayVec<T, CAP> {
44    type Target = ArrayVecInner<T, CAP>;
45    fn deref(&self) -> &Self::Target {
46        &self.0
47    }
48}
49
50impl<T, const CAP: usize> DerefMut for ArrayVec<T, CAP> {
51    fn deref_mut(&mut self) -> &mut Self::Target {
52        &mut self.0
53    }
54}
55
56impl<T, const CAP: usize> IntoIterator for ArrayVec<T, CAP> {
57    type Item = T;
58    type IntoIter = arrayvec::IntoIter<T, CAP>;
59    fn into_iter(self) -> Self::IntoIter {
60        self.0.into_iter()
61    }
62}
63
64impl<'a, T, const CAP: usize> IntoIterator for &'a ArrayVec<T, CAP> {
65    type Item = &'a T;
66    type IntoIter = std::slice::Iter<'a, T>;
67    fn into_iter(self) -> Self::IntoIter {
68        self.0.iter()
69    }
70}
71
72impl<'a, T, const CAP: usize> IntoIterator for &'a mut ArrayVec<T, CAP> {
73    type Item = &'a mut T;
74    type IntoIter = std::slice::IterMut<'a, T>;
75    fn into_iter(self) -> Self::IntoIter {
76        self.0.iter_mut()
77    }
78}