Skip to main content

osom_lib_strings/immutable/serde/
direct_string.rs

1use core::marker::PhantomData;
2
3use osom_lib_alloc::traits::Allocator;
4use serde::{
5    Deserialize, Serialize,
6    de::{self, Visitor},
7};
8
9use crate::immutable::ImmutableString;
10
11impl<TAllocator: Allocator> Serialize for ImmutableString<TAllocator> {
12    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
13    where
14        S: serde::Serializer,
15    {
16        self.as_str().serialize(serializer)
17    }
18}
19
20struct ImmutableStringVisitor<TAllocator> {
21    _phantom: PhantomData<TAllocator>,
22}
23
24impl<TAllocator> ImmutableStringVisitor<TAllocator> {
25    #[inline(always)]
26    pub const fn new() -> Self {
27        Self { _phantom: PhantomData }
28    }
29}
30
31impl<TAllocator: Allocator + Default> Visitor<'_> for ImmutableStringVisitor<TAllocator> {
32    type Value = ImmutableString<TAllocator>;
33
34    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
35        formatter.write_str("a string")
36    }
37
38    #[cfg(feature = "std")]
39    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
40    where
41        E: de::Error,
42    {
43        let imm = ImmutableString::from_str_slice(&v).map_err(de::Error::custom)?;
44        Ok(imm)
45    }
46
47    fn visit_borrowed_str<E>(self, v: &str) -> Result<Self::Value, E>
48    where
49        E: de::Error,
50    {
51        let imm = ImmutableString::from_str_slice(v).map_err(de::Error::custom)?;
52        Ok(imm)
53    }
54
55    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
56    where
57        E: de::Error,
58    {
59        let imm = ImmutableString::from_str_slice(v).map_err(de::Error::custom)?;
60        Ok(imm)
61    }
62}
63
64impl<'de, TAllocator: Allocator + Default> Deserialize<'de> for ImmutableString<TAllocator> {
65    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
66    where
67        D: serde::Deserializer<'de>,
68    {
69        deserializer.deserialize_str(ImmutableStringVisitor::new())
70    }
71}