Skip to main content

osom_lib_arrays/serde_impl/
inline_dynamic_array.rs

1use core::marker::PhantomData;
2
3use serde::{
4    Deserialize, Serialize,
5    de::{self, Visitor},
6};
7
8use osom_lib_alloc::traits::Allocator;
9use osom_lib_primitives::length::Length;
10
11use crate::dynamic_array::InlineDynamicArray;
12use crate::traits::MutableArray;
13
14impl<const CAPACITY: usize, T: Serialize, TAllocator: Allocator> Serialize
15    for InlineDynamicArray<CAPACITY, T, TAllocator>
16{
17    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
18    where
19        S: serde::Serializer,
20    {
21        self.as_ref().serialize(serializer)
22    }
23}
24
25struct InlineDynamicArrayVisitor<const CAPACITY: usize, T, TAllocator> {
26    _phantom: PhantomData<(T, TAllocator)>,
27}
28
29impl<const CAPACITY: usize, T, TAllocator> InlineDynamicArrayVisitor<CAPACITY, T, TAllocator> {
30    #[inline(always)]
31    pub const fn new() -> Self {
32        Self { _phantom: PhantomData }
33    }
34}
35
36impl<'de, const CAPACITY: usize, T: Deserialize<'de>, TAllocator: Allocator + Default> Visitor<'de>
37    for InlineDynamicArrayVisitor<CAPACITY, T, TAllocator>
38{
39    type Value = InlineDynamicArray<CAPACITY, T, TAllocator>;
40
41    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
42        formatter.write_str("a sequence of deserializable values")
43    }
44
45    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
46    where
47        A: serde::de::SeqAccess<'de>,
48    {
49        let capacity = seq.size_hint().unwrap_or(0);
50        let capacity = Length::try_from_usize(capacity).map_err(de::Error::custom)?;
51        let mut result = Self::Value::with_capacity(capacity).map_err(de::Error::custom)?;
52        while let Some(item) = seq.next_element()? {
53            result.try_push(item).map_err(de::Error::custom)?;
54        }
55
56        Ok(result)
57    }
58}
59
60impl<'de, const CAPACITY: usize, T: Deserialize<'de>, TAllocator: Allocator + Default> Deserialize<'de>
61    for InlineDynamicArray<CAPACITY, T, TAllocator>
62{
63    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
64    where
65        D: serde::Deserializer<'de>,
66    {
67        deserializer.deserialize_seq(InlineDynamicArrayVisitor::new())
68    }
69}