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
use super::message::Message;

use serde::{de::DeserializeOwned, Serialize};

#[cfg(feature = "serde-json")]
use serde_json::{from_str as deserialize, to_string as serialize};

impl<TData> Message<TData>
where
    TData: DeserializeOwned + Serialize,
{
    #[cfg(not(feature = "serde-json"))]
    pub fn serialize(&self) -> Result<String, crate::Error> {
        let err = "Serialization feature not select".to_string();
        Err(crate::Error::Serialization(err))
    }

    #[cfg(not(feature = "serde-json"))]
    pub fn deserialize(_text: &str) -> Result<Self, crate::Error> {
        let error = "Serialization feature not select".to_string();
        let data = "".to_string();
        Err(crate::Error::Deserialization { error, data })
    }

    /// Сериализация сообщений в json
    #[cfg(feature = "serde-json")]
    pub fn serialize(&self) -> Result<String, crate::Error> {
        match serialize::<Self>(self) {
            Ok(value) => Ok(value),
            Err(error) => {
                let error = error.to_string();
                Err(crate::Error::Serialization(error))
            }
        }
    }

    /// Десериализация сообщений из json
    #[cfg(feature = "serde-json")]
    pub fn deserialize(text: &str) -> Result<Self, crate::Error> {
        match deserialize::<Self>(text) {
            Ok(value) => Ok(value),
            Err(error) => {
                let error = error.to_string();
                let data = text.to_string();
                Err(crate::Error::Deserialization { error, data })
            }
        }
    }
}