1pub trait Format<T>: Sized {
8 type Error: std::error::Error + Send + Sync + 'static;
9
10 fn to_bytes(value: &T) -> Result<Vec<u8>, Self::Error>;
16
17 fn from_bytes(data: Vec<u8>) -> Result<T, Self::Error>;
23}
24
25#[cfg(feature = "json-format")]
26pub use self::json::Json;
27
28#[cfg(feature = "bincode-format")]
29pub use self::bincode::Bincode;
30
31
32#[cfg(feature = "json-format")]
33mod json {
34 use serde::{de::DeserializeOwned, Serialize};
35
36 use super::Format;
37
38 #[cfg_attr(docsrs, doc(cfg(feature = "json-format")))]
39 #[derive(Debug, std::default::Default)]
41 pub struct Json;
42
43 impl<T: DeserializeOwned + Serialize> Format<T> for Json {
44 type Error = serde_json::Error;
45
46 fn to_bytes(value: &T) -> Result<Vec<u8>, Self::Error> {
47 Ok(serde_json::to_vec_pretty(value)?)
48 }
49 fn from_bytes(data: Vec<u8>) -> Result<T, serde_json::Error> {
50 Ok(serde_json::from_slice(&data)?)
51 }
52 }
53}
54
55#[cfg(feature = "bincode-format")]
56mod bincode {
57 use serde::{de::DeserializeOwned, Serialize};
58
59 use super::Format;
60
61 #[cfg_attr(docsrs, doc(cfg(feature = "bincode-format")))]
62 #[derive(Debug, std::default::Default)]
64 pub struct Bincode;
65
66 impl<T: Serialize + DeserializeOwned> Format<T> for Bincode {
67 type Error = bincode::Error;
68
69 fn to_bytes(value: &T) -> Result<Vec<u8>, Self::Error> {
70 Ok(bincode::serialize(value)?)
71 }
72 fn from_bytes(data: Vec<u8>) -> Result<T, Self::Error> {
73 Ok(bincode::deserialize(&data)?)
74 }
75 }
76}