|
| 1 | +//! Emulates a fixed size array but with the length set at runtime. |
| 2 | +//! |
| 3 | +//! The length of the list cannot be changed once it is set. |
| 4 | +
|
| 5 | +use std::fmt; |
| 6 | +use std::fmt::Debug; |
| 7 | + |
| 8 | +#[derive(Clone)] |
| 9 | +pub struct RuntimeFixedVector<T> { |
| 10 | + vec: Vec<T>, |
| 11 | + len: usize, |
| 12 | +} |
| 13 | + |
| 14 | +impl<T: Debug> Debug for RuntimeFixedVector<T> { |
| 15 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 16 | + write!(f, "{:?} (len={})", self.vec, self.len) |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +impl<T: Clone + Default> RuntimeFixedVector<T> { |
| 21 | + pub fn new(vec: Vec<T>) -> Self { |
| 22 | + let len = vec.len(); |
| 23 | + Self { vec, len } |
| 24 | + } |
| 25 | + |
| 26 | + pub fn to_vec(&self) -> Vec<T> { |
| 27 | + self.vec.clone() |
| 28 | + } |
| 29 | + |
| 30 | + pub fn as_slice(&self) -> &[T] { |
| 31 | + self.vec.as_slice() |
| 32 | + } |
| 33 | + |
| 34 | + #[allow(clippy::len_without_is_empty)] |
| 35 | + pub fn len(&self) -> usize { |
| 36 | + self.len |
| 37 | + } |
| 38 | + |
| 39 | + pub fn into_vec(self) -> Vec<T> { |
| 40 | + self.vec |
| 41 | + } |
| 42 | + |
| 43 | + pub fn default(max_len: usize) -> Self { |
| 44 | + Self { |
| 45 | + vec: vec![T::default(); max_len], |
| 46 | + len: max_len, |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + pub fn take(&mut self) -> Self { |
| 51 | + let new = std::mem::take(&mut self.vec); |
| 52 | + *self = Self::new(vec![T::default(); self.len]); |
| 53 | + Self { |
| 54 | + vec: new, |
| 55 | + len: self.len, |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +impl<T> std::ops::Deref for RuntimeFixedVector<T> { |
| 61 | + type Target = [T]; |
| 62 | + |
| 63 | + fn deref(&self) -> &[T] { |
| 64 | + &self.vec[..] |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +impl<T> std::ops::DerefMut for RuntimeFixedVector<T> { |
| 69 | + fn deref_mut(&mut self) -> &mut [T] { |
| 70 | + &mut self.vec[..] |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +impl<T> IntoIterator for RuntimeFixedVector<T> { |
| 75 | + type Item = T; |
| 76 | + type IntoIter = std::vec::IntoIter<T>; |
| 77 | + |
| 78 | + fn into_iter(self) -> Self::IntoIter { |
| 79 | + self.vec.into_iter() |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +impl<'a, T> IntoIterator for &'a RuntimeFixedVector<T> { |
| 84 | + type Item = &'a T; |
| 85 | + type IntoIter = std::slice::Iter<'a, T>; |
| 86 | + |
| 87 | + fn into_iter(self) -> Self::IntoIter { |
| 88 | + self.vec.iter() |
| 89 | + } |
| 90 | +} |
0 commit comments