devela/data/serde/utils/
array_wrapper.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// https://crates.io/crates/serde_arrays/0.1.0
//  MIT OR Apache-2.0
//  Travis Veazey
//
// TODO
// - make unsafe optional
// - review PRS: https://github.com/Kromey/serde_arrays/pull/6

use crate::{MaybeUninit, PhantomData};
use core::{fmt, mem};
use serde::{
    de::{self, Deserialize, Deserializer, SeqAccess, Visitor},
    ser::{Serialize, SerializeTuple, Serializer},
};
#[cfg(feature = "alloc")]
use {crate::Vec, serde::ser::SerializeSeq};

struct ArrayWrap<'a, T: Serialize, const N: usize> {
    item: &'a [T; N],
}
impl<T: Serialize, const N: usize> Serialize for ArrayWrap<'_, T, N> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        super::serialize(self.item, serializer)
    }
}

mod _private {
    /// Trait that allows to serialize arbitrary array types with `serde`.
    ///
    /// Out of the box, Serde supports [a lot of types](https://serde.rs/data-model.html#types),
    /// but unfortunately lacks support for arrays that use const generics.
    // TODO: improve docs?
    // TODO: is it possible to have the serialize and deserialize standalone functions as
    // auto-implemneted methods? I guess I'll have to rename this method then?
    pub trait SerializableArray<T: super::Serialize, const N: usize> {
        /// TODO
        fn serialize<S: super::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error>;
    }
}

/// Serialize const generic or arbitrarily-large arrays.
pub fn serialize<A, S, T, const N: usize>(data: &A, ser: S) -> Result<S::Ok, S::Error>
where
    A: _private::SerializableArray<T, N>,
    S: Serializer,
    T: Serialize,
{
    data.serialize(ser)
}

/// Deserialize const generic or arbitrarily-large arrays.
pub fn deserialize<'de, D, T, const N: usize>(deserialize: D) -> Result<[T; N], D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de>,
{
    deserialize.deserialize_tuple(N, ArrayVisitor(PhantomData))
}

impl<T: Serialize, const N: usize, const M: usize> _private::SerializableArray<T, N>
    for [[T; N]; M]
{
    fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        // Fixed-length structures, including arrays, are supported in Serde as tuples
        // See: https://serde.rs/impl-serialize.html#serializing-a-tuple
        let mut s = ser.serialize_tuple(N)?;
        for item in self {
            let wrapped = ArrayWrap { item };
            s.serialize_element(&wrapped)?;
        }
        s.end()
    }
}

#[cfg(feature = "alloc")]
#[cfg_attr(feature = "nightly_doc", doc(cfg(feature = "alloc")))]
impl<T: Serialize, const N: usize> _private::SerializableArray<T, N> for Vec<[T; N]> {
    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        let mut s = ser.serialize_seq(Some(self.len()))?;
        for item in self {
            let wrapped = ArrayWrap { item };
            s.serialize_element(&wrapped)?;
        }
        s.end()
    }
}
impl<T: Serialize, const N: usize> _private::SerializableArray<T, N> for [T; N] {
    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        serialize_as_tuple(self, ser)
    }
}

/// Serialize an array.
///
/// In Serde arrays (and other fixed-length structures) are supported as tuples
// See: https://serde.rs/impl-serialize.html#serializing-a-tuple
fn serialize_as_tuple<S, T, const N: usize>(data: &[T; N], ser: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
    T: Serialize,
{
    let mut s = ser.serialize_tuple(N)?;
    for item in data {
        s.serialize_element(item)?;
    }
    s.end()
}

/// A Serde Deserializer `Visitor` for [T; N] arrays.
struct ArrayVisitor<T, const N: usize>(PhantomData<T>);

impl<'de, T: Deserialize<'de>, const N: usize> Visitor<'de> for ArrayVisitor<T, N> {
    type Value = [T; N];

    /// Format a message stating we expect an array of size `N`.
    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "an array of size {}", N)
    }

    /// Process a sequence into an array.
    // TODO: make the unsafe sections feature-gated with "unsafe_array" feature
    // and provide safe alternatives if disabled, using core::array::from_fn (probably)
    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
        // SAFETY: a bunch of `MaybeUninit`s do not require initialization.
        let mut arr: [MaybeUninit<T>; N] = unsafe { MaybeUninit::uninit().assume_init() };

        // Iterate over the array and fill the elements with the ones obtained from `seq`.
        let mut place_iter = arr.iter_mut();
        let mut cnt_filled = 0;
        let err = loop {
            match (seq.next_element(), place_iter.next()) {
                (Ok(Some(val)), Some(place)) => *place = MaybeUninit::new(val),
                // no error, we're done
                (Ok(None), None) => break None,
                // error from serde, propagate it
                (Err(e), _) => break Some(e),
                // lengths do not match, report invalid_length
                (Ok(None), Some(_)) | (Ok(Some(_)), None) => {
                    break Some(de::Error::invalid_length(cnt_filled, &self))
                }
            }
            cnt_filled += 1;
        };
        if let Some(err) = err {
            if mem::needs_drop::<T>() {
                for elem in IntoIterator::into_iter(arr).take(cnt_filled) {
                    // SAFETY: cnt_filled elements are initialized.
                    unsafe {
                        elem.assume_init();
                    }
                }
            }
            return Err(err);
        }

        // SAFETY: everything is already initialized
        let ret = unsafe { mem::transmute_copy(&arr) };

        // #[allow(clippy::forget_non_drop, reason = "redundancy?")]
        // mem::forget(arr);

        Ok(ret)
    }
}