serde_big_array/
array.rs

1use crate::const_generics::PartiallyInitialized;
2use crate::BigArray;
3use core::ops::{Deref, DerefMut, Index, IndexMut};
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5
6/// An array newtype usable for nested structures
7///
8/// In most cases, using the [`BigArray`] trait
9/// is more convenient, so you should use that one.
10///
11/// In nesting scenarios however, the trick of using
12/// `#[serde(with = ...)]` comes to its limits. For
13/// these cases, we offer the `Array` struct.
14///
15/// [`BigArray`]: crate::BigArray
16///
17/// ```Rust
18/// # use serde_derive::{Serialize, Deserialize};
19/// #[derive(Serialize, Deserialize)]
20/// struct S {
21///     arr: Box<Array<u8, 64>>,
22/// }
23/// ```
24#[repr(transparent)]
25#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone, Debug)]
26pub struct Array<T, const N: usize>(pub [T; N]);
27
28impl<'de, T: Deserialize<'de>, const N: usize> Deserialize<'de> for Array<T, N> {
29    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
30    where
31        D: Deserializer<'de>,
32    {
33        Ok(Self(<[T; N] as BigArray<T>>::deserialize(deserializer)?))
34    }
35}
36
37impl<T: Default, const N: usize> Default for Array<T, N> {
38    fn default() -> Self {
39        // TODO use array::from_fn once the MSRV allows stuff from 1.63.0
40        let arr = {
41            let mut arr = PartiallyInitialized::<T, N>::new();
42            unsafe {
43                {
44                    let p = arr.0.as_mut().unwrap();
45                    for i in 0..N {
46                        let p = (p.as_mut_ptr() as *mut T).wrapping_add(i);
47                        core::ptr::write(p, Default::default());
48                        arr.1 += 1;
49                    }
50                }
51                let initialized = arr.0.take().unwrap().assume_init();
52                initialized
53            }
54        };
55        Self(arr)
56    }
57}
58
59impl<T: Serialize, const N: usize> Serialize for Array<T, N> {
60    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
61    where
62        S: Serializer,
63    {
64        <[T; N] as BigArray<T>>::serialize(&self.0, serializer)
65    }
66}
67
68impl<T, const N: usize> Deref for Array<T, N> {
69    type Target = [T; N];
70
71    fn deref(&self) -> &Self::Target {
72        &self.0
73    }
74}
75
76impl<T, const N: usize> DerefMut for Array<T, N> {
77    fn deref_mut(&mut self) -> &mut Self::Target {
78        &mut self.0
79    }
80}
81
82impl<T, I, const N: usize> Index<I> for Array<T, N>
83where
84    [T]: Index<I>,
85{
86    type Output = <[T] as Index<I>>::Output;
87
88    #[inline]
89    fn index(&self, index: I) -> &Self::Output {
90        Index::index(&self.0 as &[T], index)
91    }
92}
93
94impl<T, I, const N: usize> IndexMut<I> for Array<T, N>
95where
96    [T]: IndexMut<I>,
97{
98    #[inline]
99    fn index_mut(&mut self, index: I) -> &mut Self::Output {
100        IndexMut::index_mut(&mut self.0 as &mut [T], index)
101    }
102}