Skip to main content

g_err/
serde.rs

1//! Contains serde implementations for [`GErr`].
2//!
3//! For default serialization, goes into string.
4//! No default deserialization.
5//!
6//! For JSON serde use `g_err::serde::json` for internal,
7//! and `g_err::serde::display_json` for public.
8//!
9use crate::gerr::{Config, GErr};
10use core::error::Error;
11use serde::Serialize;
12
13/// Serialize into string.
14impl<C: Config, D> serde::Serialize for GErr<C, D>
15where
16    C::Id: serde::Serialize,
17    D: serde::Serialize,
18    Self: Error + 'static,
19{
20    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
21    where
22        S: serde::Serializer,
23    {
24        serializer.serialize_str(self.to_string().as_str())
25    }
26}
27
28/// Serialize and deserialize into/from json for internal.
29///
30/// Attribute:
31///
32/// `#[serde(with = "g_err::serde::json")]`
33pub mod json {
34    use crate::json::JsonData;
35
36    use super::*;
37
38    /// Serialize GErr into JSON through [`JsonData`]
39    pub fn serialize<S, C: Config, D>(err: &GErr<C, D>, serializer: S) -> Result<S::Ok, S::Error>
40    where
41        S: serde::Serializer,
42        C::Id: core::fmt::Display + serde::Serialize,
43        D: core::fmt::Debug + serde::Serialize,
44        GErr<C, D>: Error + 'static,
45    {
46        err.json_data().serialize(serializer)
47    }
48
49    /// deserialize GErr from JSON through [`JsonData`]
50    pub fn deserialize<'de, De, C: Config, D>(deserializer: De) -> Result<GErr<C, D>, De::Error>
51    where
52        De: serde::Deserializer<'de>,
53        C::Id: for<'a> serde::Deserialize<'a>,
54        D: for<'a> serde::Deserialize<'a>,
55    {
56        <JsonData as serde::Deserialize>::deserialize(deserializer)?
57            .try_into()
58            .map_err(::serde::de::Error::custom)
59    }
60}
61
62/// Serialize into json for public.
63///
64/// Attribute:
65///
66/// `#[serde(serialize_with = "g_err::serde::display_json::serialize")]`
67pub mod display_json {
68    use super::*;
69
70    /// Serialize GErr into JSON through [`crate::json::DisplayJsonData`]
71    pub fn serialize<S, C: Config, D>(err: &GErr<C, D>, serializer: S) -> Result<S::Ok, S::Error>
72    where
73        S: serde::Serializer,
74        C::Id: core::fmt::Display + serde::Serialize,
75        D: core::fmt::Debug + serde::Serialize,
76        GErr<C, D>: Error + 'static,
77    {
78        err.display_json_data().serialize(serializer)
79    }
80}