daybreak/
deser.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4use crate::error;
5use std::io::Read;
6
7use serde::de::DeserializeOwned;
8use serde::Serialize;
9
10#[cfg(feature = "ron_enc")]
11pub use self::ron::Ron;
12
13#[cfg(feature = "yaml_enc")]
14pub use self::yaml::Yaml;
15
16#[cfg(feature = "bin_enc")]
17pub use self::bincode::Bincode;
18
19/// A trait to bundle serializer and deserializer in a simple struct
20///
21/// It should preferably be an struct: one that does not have any members.
22///
23/// # Example
24///
25/// For an imaginary serde compatible encoding scheme 'Frobnar', an example
26/// implementation can look like this:
27///
28/// ```rust
29/// extern crate daybreak;
30/// extern crate thiserror;
31/// extern crate serde;
32/// #[macro_use]
33///
34/// use serde::de::Deserialize;
35/// use serde::Serialize;
36/// use std::io::Read;
37///
38/// use daybreak::deser::DeSerializer;
39/// use daybreak::error;
40///
41/// #[derive(Clone, Debug, thiserror::Error)]
42/// #[error("A frobnarizer could not splagrle.")]
43/// struct FrobnarError;
44///
45/// fn to_frobnar<T: Serialize>(input: &T) -> Vec<u8> {
46///     unimplemented!(); // implementation not specified
47/// }
48///
49/// fn from_frobnar<'r, T: Deserialize<'r> + 'r, R: Read>(input: &R) -> Result<T, FrobnarError> {
50///     unimplemented!(); // implementation not specified
51/// }
52///
53/// #[derive(Debug, Default, Clone)]
54/// struct Frobnar;
55///
56/// impl<T: Serialize> DeSerializer<T> for Frobnar
57/// where
58///     for<'de> T: Deserialize<'de>,
59/// {
60///     fn serialize(&self, val: &T) -> daybreak::DeSerResult<Vec<u8>> {
61///         Ok(to_frobnar(val))
62///     }
63///
64///     fn deserialize<R: Read>(&self, s: R) -> daybreak::DeSerResult<T> {
65///         Ok(from_frobnar(&s).map_err(|e| error::DeSerError::Other(e.into()))?)
66///     }
67/// }
68///
69/// fn main() {}
70/// ```
71///
72/// **Important**: You can only return custom errors if the `other_errors` feature is enabled
73pub trait DeSerializer<T: Serialize + DeserializeOwned>:
74    std::default::Default + Send + Sync + Clone
75{
76    /// Serializes a given value to a [`String`].
77    fn serialize(&self, val: &T) -> error::DeSerResult<Vec<u8>>;
78    /// Deserializes a [`String`] to a value.
79    fn deserialize<R: Read>(&self, s: R) -> error::DeSerResult<T>;
80}
81
82#[cfg(feature = "ron_enc")]
83mod ron {
84    use std::io::Read;
85
86    use serde::de::DeserializeOwned;
87    use serde::Serialize;
88
89    use ron::de::from_reader as from_ron_string;
90    use ron::ser::to_string_pretty as to_ron_string;
91    use ron::ser::PrettyConfig;
92
93    use crate::deser::DeSerializer;
94    use crate::error;
95
96    /// The Struct that allows you to use `ron` the Rusty Object Notation.
97    #[derive(Debug, Default, Clone)]
98    pub struct Ron;
99
100    impl<T: Serialize + DeserializeOwned> DeSerializer<T> for Ron {
101        fn serialize(&self, val: &T) -> error::DeSerResult<Vec<u8>> {
102            Ok(to_ron_string(val, PrettyConfig::default()).map(String::into_bytes)?)
103        }
104        fn deserialize<R: Read>(&self, s: R) -> error::DeSerResult<T> {
105            Ok(from_ron_string(s).map_err(|e| e.code)?)
106        }
107    }
108}
109
110#[cfg(feature = "yaml_enc")]
111mod yaml {
112    use std::io::Read;
113
114    use serde::de::DeserializeOwned;
115    use serde::Serialize;
116    use serde_yaml::{from_reader as from_yaml_string, to_string as to_yaml_string};
117
118    use crate::deser::DeSerializer;
119    use crate::error;
120
121    /// The struct that allows you to use yaml.
122    #[derive(Debug, Default, Clone)]
123    pub struct Yaml;
124
125    impl<T: Serialize + DeserializeOwned> DeSerializer<T> for Yaml {
126        fn serialize(&self, val: &T) -> error::DeSerResult<Vec<u8>> {
127            Ok(to_yaml_string(val).map(String::into_bytes)?)
128        }
129        fn deserialize<R: Read>(&self, s: R) -> error::DeSerResult<T> {
130            Ok(from_yaml_string(s)?)
131        }
132    }
133}
134
135#[cfg(feature = "bin_enc")]
136mod bincode {
137    use std::io::Read;
138
139    use bincode::{deserialize_from, serialize};
140    use serde::de::DeserializeOwned;
141    use serde::Serialize;
142
143    use crate::deser::DeSerializer;
144    use crate::error;
145
146    /// The struct that allows you to use bincode
147    #[derive(Debug, Default, Clone)]
148    pub struct Bincode;
149
150    impl<T: Serialize + DeserializeOwned> DeSerializer<T> for Bincode {
151        fn serialize(&self, val: &T) -> error::DeSerResult<Vec<u8>> {
152            Ok(serialize(val)?)
153        }
154        fn deserialize<R: Read>(&self, s: R) -> error::DeSerResult<T> {
155            Ok(deserialize_from(s)?)
156        }
157    }
158}