mop_structs/vec/
vec_array.rs

1use crate::prelude::{
2  Array, DynDenseSto, DynDenseStoMut, DynDenseStoRef, StDenseStoMut, StDenseStoRef,
3};
4use core::{
5  borrow::{Borrow, BorrowMut},
6  fmt,
7  iter::{FromIterator, IntoIterator},
8  mem::uninitialized,
9  ops::{Deref, DerefMut},
10  ptr::{copy_nonoverlapping, write},
11  slice::{Iter, IterMut},
12};
13#[cfg(feature = "serde1")]
14use serde::{Deserialize, Deserializer, Serialize, Serializer};
15
16/// A structure just like [`Vec`](Vec), the difference is the inner storage
17/// provided by an array.
18#[derive(Clone, Copy, Default, Eq, Hash, PartialEq, PartialOrd)]
19pub struct VecArray<A> {
20  array: A,
21  len: usize,
22}
23
24impl<A> VecArray<A>
25where
26  A: Array,
27{
28  /// Creates a new [`VecArray`](VecArray) from a provided array and length.
29  ///
30  /// # Arguments
31  ///
32  /// * `array` - The array storage
33  ///
34  /// # Examples
35  ///
36  /// ```rust
37  /// use mop_structs::vec::VecArray;
38  /// let _ = VecArray::new([1, 2, 3, 4, 5], 2);
39  /// ```
40  pub fn new(array: A, len: usize) -> Self {
41    VecArray { array, len }
42  }
43
44  #[cfg(feature = "rand")]
45  pub fn new_rnd<F, R>(len: usize, rng: &mut R, mut cb: F) -> Self
46  where
47    F: FnMut(&mut R, usize) -> A::Item,
48    R: mop_common_deps::rand::Rng,
49  {
50    let mut this = Self::with_capacity();
51    assert!(len <= this.capacity());
52    (0..len).for_each(|idx| unsafe { this.push_unsafe(cb(rng, idx)) });
53    this
54  }
55
56  /// Creates a new [`VecArray`](VecArray) from a provided array.
57  /// Then length of `Self` will be the length of `array`.
58  ///
59  /// # Examples
60  ///
61  /// ```rust
62  /// use mop_structs::vec::VecArray;
63  /// let _ = VecArray::with_array([0; 10]);
64  /// ```
65  pub fn with_array(array: A) -> Self {
66    VecArray {
67      array,
68      len: A::SIZE,
69    }
70  }
71
72  /// Creates a new empty [`VecArray`](VecArray) from an array type.
73  ///
74  /// # Examples
75  ///
76  /// ```rust
77  /// use mop_structs::vec::VecArray;
78  /// let _ = VecArray::<[i32; 10]>::with_capacity();
79  /// ```
80  pub fn with_capacity() -> Self {
81    VecArray {
82      array: unsafe { uninitialized() },
83      len: 0,
84    }
85  }
86
87  pub fn array(&self) -> &A {
88    &self.array
89  }
90
91  pub fn len(&self) -> usize {
92    self.len
93  }
94
95  pub fn try_push(&mut self, item: A::Item) -> bool {
96    if self.len < self.capacity() {
97      unsafe { self.push_unsafe(item) };
98      true
99    } else {
100      false
101    }
102  }
103
104  unsafe fn push_unsafe(&mut self, item: A::Item) {
105    write(self.offset_array_ptr(self.len), item);
106    self.len += 1;
107  }
108
109  unsafe fn offset_array_ptr(&mut self, count: usize) -> *mut A::Item {
110    self.array.as_mut_slice().as_mut_ptr().add(count)
111  }
112}
113
114impl<A> StDenseStoRef for VecArray<A>
115where
116  A: Array,
117{
118  type Item = A::Item;
119
120  /// # Examples
121  ///
122  /// ```rust
123  /// use mop_structs::{
124  ///     doc_tests::vec_array,
125  ///     prelude::*,
126  /// };
127  /// assert_eq!(&vec_array(), &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
128  /// ```
129  fn as_slice(&self) -> &[A::Item] {
130    let slice = self.array.as_slice();
131    &slice[0..self.len]
132  }
133}
134
135impl<A> StDenseStoMut for VecArray<A>
136where
137  A: Array,
138{
139  /// # Examples
140  ///
141  /// ```rust
142  /// use mop_structs::{
143  ///     doc_tests::vec_array,
144  ///     prelude::*,
145  /// };
146  /// assert_eq!(vec_array().as_mut_slice(), &mut [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
147  /// ```
148  fn as_mut_slice(&mut self) -> &mut [A::Item] {
149    let slice = self.array.as_mut_slice();
150    &mut slice[0..self.len]
151  }
152}
153
154impl<A> DynDenseStoRef for VecArray<A>
155where
156  A: Array,
157{
158  /// # Examples
159  ///
160  /// ```rust
161  /// use mop_structs::{
162  ///     doc_tests::vec_array,
163  ///     prelude::*,
164  /// };
165  /// assert_eq!(vec_array().capacity(), 16);
166  /// ```
167  fn capacity(&self) -> usize {
168    A::SIZE
169  }
170}
171
172impl<A> DynDenseStoMut for VecArray<A>
173where
174  A: Array,
175{
176  /// # Examples
177  ///
178  /// ```rust
179  /// use mop_structs::{
180  ///     doc_tests::vec_array,
181  ///     prelude::*,
182  /// };
183  /// let mut a = vec_array();
184  /// a.clear();
185  /// assert_eq!(&a, &[]);
186  /// ```
187  fn clear(&mut self) {
188    self.len = 0;
189  }
190
191  /// # Examples
192  ///
193  /// ```rust
194  /// use mop_structs::{
195  ///     doc_tests::vec_array,
196  ///     prelude::*,
197  /// };
198  /// let mut a = vec_array();
199  /// a.extend(&[1, 2]);
200  /// assert_eq!(&a, &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2]);
201  /// ```
202  fn extend(&mut self, other: &[Self::Item])
203  where
204    Self::Item: Copy,
205  {
206    let other_len = other.len();
207    assert!(self.len + other_len <= self.capacity());
208    unsafe {
209      copy_nonoverlapping(other.as_ptr(), self.offset_array_ptr(self.len), other_len);
210    }
211    self.len += other_len;
212  }
213
214  /// # Examples
215  ///
216  /// ```rust
217  /// use mop_structs::{
218  ///     doc_tests::vec_array,
219  ///     prelude::*,
220  /// };
221  /// let mut a = vec_array();
222  /// a.extend_from_clone(&[1, 2]);
223  /// assert_eq!(&a, &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2]);
224  /// ```
225  fn extend_from_clone(&mut self, other: &[Self::Item])
226  where
227    Self::Item: Clone,
228  {
229    let other_len = other.len();
230    assert!(self.len + other_len <= self.capacity());
231    other.iter().for_each(|x| unsafe {
232      write(self.offset_array_ptr(self.len), x.clone());
233      self.len += 1;
234    });
235  }
236
237  /// # Examples
238  ///
239  /// ```rust
240  /// use mop_structs::{
241  ///     doc_tests::vec_array,
242  ///     prelude::*,
243  /// };
244  /// let mut a = vec_array();
245  /// a.push(100);
246  /// assert_eq!(&a, &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100]);
247  /// ```
248  fn push(&mut self, item: A::Item) {
249    assert!(self.len < self.capacity());
250    unsafe { self.push_unsafe(item) };
251  }
252
253  /// # Examples
254  ///
255  /// ```rust
256  /// use mop_structs::{
257  ///     doc_tests::vec_array,
258  ///     prelude::*,
259  /// };
260  /// let mut a = vec_array();
261  /// a.swap(0, 2);
262  /// assert_eq!(&a, &[3, 2, 1, 4, 5, 6, 7, 8, 9, 10]);
263  /// ```
264  fn swap(&mut self, a: usize, b: usize) {
265    self.as_mut_slice().swap(a, b);
266  }
267
268  /// # Examples
269  ///
270  /// ```rust
271  /// use mop_structs::{
272  ///     doc_tests::vec_array,
273  ///     prelude::*,
274  /// };
275  /// let mut a = vec_array();
276  /// a.truncate(2);
277  /// assert_eq!(&a, &[1, 2]);
278  /// ```
279  fn truncate(&mut self, idx: usize) {
280    self.len = idx;
281  }
282}
283
284impl<A> DynDenseSto for VecArray<A>
285where
286  A: Array,
287{
288  fn new() -> Self {
289    VecArray::<A>::with_capacity()
290  }
291}
292
293impl<A> AsRef<[A::Item]> for VecArray<A>
294where
295  A: Array,
296{
297  fn as_ref(&self) -> &[A::Item] {
298    self
299  }
300}
301
302impl<A> AsMut<[A::Item]> for VecArray<A>
303where
304  A: Array,
305{
306  fn as_mut(&mut self) -> &mut [A::Item] {
307    self
308  }
309}
310
311impl<A> Borrow<[A::Item]> for VecArray<A>
312where
313  A: Array,
314{
315  fn borrow(&self) -> &[A::Item] {
316    self
317  }
318}
319
320impl<A> BorrowMut<[A::Item]> for VecArray<A>
321where
322  A: Array,
323{
324  fn borrow_mut(&mut self) -> &mut [A::Item] {
325    self
326  }
327}
328
329impl<A> Deref for VecArray<A>
330where
331  A: Array,
332{
333  type Target = [A::Item];
334  #[inline]
335  fn deref(&self) -> &[A::Item] {
336    self.as_slice()
337  }
338}
339
340impl<A> DerefMut for VecArray<A>
341where
342  A: Array,
343{
344  #[inline]
345  fn deref_mut(&mut self) -> &mut [A::Item] {
346    self.as_mut_slice()
347  }
348}
349
350impl<A> FromIterator<A::Item> for VecArray<A>
351where
352  A: Array,
353{
354  fn from_iter<I>(iter: I) -> Self
355  where
356    I: IntoIterator<Item = A::Item>,
357  {
358    let mut va = VecArray::with_capacity();
359    iter.into_iter().for_each(|x| va.push(x));
360    va
361  }
362}
363
364impl<'a, A> IntoIterator for &'a VecArray<A>
365where
366  A: Array,
367{
368  type Item = &'a A::Item;
369  type IntoIter = Iter<'a, A::Item>;
370  fn into_iter(self) -> Self::IntoIter {
371    self.iter()
372  }
373}
374
375impl<'a, A> IntoIterator for &'a mut VecArray<A>
376where
377  A: Array,
378{
379  type Item = &'a mut A::Item;
380  type IntoIter = IterMut<'a, A::Item>;
381  fn into_iter(self) -> Self::IntoIter {
382    self.iter_mut()
383  }
384}
385
386#[cfg(feature = "serde1")]
387impl<A> Serialize for VecArray<A>
388where
389  A: Array,
390  A::Item: Serialize,
391{
392  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
393  where
394    S: Serializer,
395  {
396    serializer.collect_seq(self)
397  }
398}
399
400#[cfg(feature = "serde1")]
401impl<'de, A> Deserialize<'de> for VecArray<A>
402where
403  A: Array,
404  A::Item: Deserialize<'de>,
405{
406  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
407  where
408    D: Deserializer<'de>,
409  {
410    use core::marker::PhantomData;
411    use serde::de::{Error, SeqAccess, Visitor};
412
413    struct VecArrayVisitor<'de, A>(PhantomData<(&'de (), A)>);
414
415    impl<'de, A> Visitor<'de> for VecArrayVisitor<'de, A>
416    where
417      A: Array,
418      A::Item: Deserialize<'de>,
419    {
420      type Value = VecArray<A>;
421
422      fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
423        write!(formatter, "an array with no more than {} items", A::SIZE)
424      }
425
426      fn visit_seq<SA>(self, mut seq: SA) -> Result<Self::Value, SA::Error>
427      where
428        SA: SeqAccess<'de>,
429      {
430        let mut values = VecArray::<A>::with_capacity();
431
432        while let Some(value) = seq.next_element()? {
433          if values.try_push(value) == false {
434            return Err(SA::Error::invalid_length(A::SIZE + 1, &self));
435          }
436        }
437
438        Ok(values)
439      }
440    }
441
442    deserializer.deserialize_seq(VecArrayVisitor::<A>(PhantomData))
443  }
444}
445
446impl<A> fmt::Debug for VecArray<A>
447where
448  A: Array,
449  A::Item: fmt::Debug,
450{
451  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
452    self.as_slice().fmt(f)
453  }
454}