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