said/version/
format.rs

1use std::str::FromStr;
2
3use rmp_serde as serde_mgpk;
4use serde::{Deserialize, Serialize};
5
6use super::error::Error;
7
8#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Copy)]
9pub enum SerializationFormats {
10    JSON,
11    MGPK,
12    CBOR,
13}
14
15impl SerializationFormats {
16    pub fn encode<T: Serialize>(&self, message: &T) -> Result<Vec<u8>, Error> {
17        match self {
18            Self::JSON => serde_json::to_vec(message).map_err(|_| Error::JsonDeserError),
19            Self::CBOR => serde_cbor::to_vec(message).map_err(|_| Error::CborDeserError),
20            Self::MGPK => serde_mgpk::to_vec(message).map_err(|_| Error::MsgPackDeserError),
21        }
22    }
23
24    pub fn to_str(&self) -> String {
25        match self {
26            Self::JSON => "JSON",
27            Self::CBOR => "CBOR",
28            Self::MGPK => "MGPK",
29        }
30        .to_string()
31    }
32}
33
34impl FromStr for SerializationFormats {
35    type Err = Error;
36    fn from_str(s: &str) -> Result<Self, Self::Err> {
37        match s {
38            "JSON" => Ok(SerializationFormats::JSON),
39            "MGPK" => Ok(SerializationFormats::MGPK),
40            "CBOR" => Ok(SerializationFormats::CBOR),
41            _ => Err(Error::DeserializeError("Unknown format".into())),
42        }
43    }
44}