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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use crate::error;
use std::io::Read;

use serde::de::DeserializeOwned;
use serde::Serialize;

#[cfg(feature = "ron_enc")]
pub use self::ron::Ron;

#[cfg(feature = "yaml_enc")]
pub use self::yaml::Yaml;

#[cfg(feature = "bin_enc")]
pub use self::bincode::Bincode;

/// A trait to bundle serializer and deserializer in a simple struct
///
/// It should preferably be an struct: one that does not have any members.
///
/// # Example
///
/// For an imaginary serde compatible encoding scheme 'Frobnar', an example
/// implementation can look like this:
///
/// ```rust
/// extern crate daybreak;
/// extern crate thiserror;
/// extern crate serde;
/// #[macro_use]
///
/// use serde::de::Deserialize;
/// use serde::Serialize;
/// use std::io::Read;
///
/// use daybreak::deser::DeSerializer;
/// use daybreak::error;
///
/// #[derive(Clone, Debug, thiserror::Error)]
/// #[error("A frobnarizer could not splagrle.")]
/// struct FrobnarError;
///
/// fn to_frobnar<T: Serialize>(input: &T) -> Vec<u8> {
///     unimplemented!(); // implementation not specified
/// }
///
/// fn from_frobnar<'r, T: Deserialize<'r> + 'r, R: Read>(input: &R) -> Result<T, FrobnarError> {
///     unimplemented!(); // implementation not specified
/// }
///
/// #[derive(Debug, Default, Clone)]
/// struct Frobnar;
///
/// impl<T: Serialize> DeSerializer<T> for Frobnar
/// where
///     for<'de> T: Deserialize<'de>,
/// {
///     fn serialize(&self, val: &T) -> daybreak::DeSerResult<Vec<u8>> {
///         Ok(to_frobnar(val))
///     }
///
///     fn deserialize<R: Read>(&self, s: R) -> daybreak::DeSerResult<T> {
///         Ok(from_frobnar(&s).map_err(|e| error::DeSerError::Other(e.into()))?)
///     }
/// }
///
/// fn main() {}
/// ```
///
/// **Important**: You can only return custom errors if the `other_errors` feature is enabled
pub trait DeSerializer<T: Serialize + DeserializeOwned>:
    std::default::Default + Send + Sync + Clone
{
    /// Serializes a given value to a [`String`].
    fn serialize(&self, val: &T) -> error::DeSerResult<Vec<u8>>;
    /// Deserializes a [`String`] to a value.
    fn deserialize<R: Read>(&self, s: R) -> error::DeSerResult<T>;
}

#[cfg(feature = "ron_enc")]
mod ron {
    use std::io::Read;

    use serde::de::DeserializeOwned;
    use serde::Serialize;

    use ron::de::from_reader as from_ron_string;
    use ron::ser::to_string_pretty as to_ron_string;
    use ron::ser::PrettyConfig;

    use crate::deser::DeSerializer;
    use crate::error;

    /// The Struct that allows you to use `ron` the Rusty Object Notation.
    #[derive(Debug, Default, Clone)]
    pub struct Ron;

    impl<T: Serialize + DeserializeOwned> DeSerializer<T> for Ron {
        fn serialize(&self, val: &T) -> error::DeSerResult<Vec<u8>> {
            Ok(to_ron_string(val, PrettyConfig::default()).map(String::into_bytes)?)
        }
        fn deserialize<R: Read>(&self, s: R) -> error::DeSerResult<T> {
            Ok(from_ron_string(s).map_err(|e| e.code)?)
        }
    }
}

#[cfg(feature = "yaml_enc")]
mod yaml {
    use std::io::Read;

    use serde::de::DeserializeOwned;
    use serde::Serialize;
    use serde_yaml::{from_reader as from_yaml_string, to_string as to_yaml_string};

    use crate::deser::DeSerializer;
    use crate::error;

    /// The struct that allows you to use yaml.
    #[derive(Debug, Default, Clone)]
    pub struct Yaml;

    impl<T: Serialize + DeserializeOwned> DeSerializer<T> for Yaml {
        fn serialize(&self, val: &T) -> error::DeSerResult<Vec<u8>> {
            Ok(to_yaml_string(val).map(String::into_bytes)?)
        }
        fn deserialize<R: Read>(&self, s: R) -> error::DeSerResult<T> {
            Ok(from_yaml_string(s)?)
        }
    }
}

#[cfg(feature = "bin_enc")]
mod bincode {
    use std::io::Read;

    use bincode::{deserialize_from, serialize};
    use serde::de::DeserializeOwned;
    use serde::Serialize;

    use crate::deser::DeSerializer;
    use crate::error;

    /// The struct that allows you to use bincode
    #[derive(Debug, Default, Clone)]
    pub struct Bincode;

    impl<T: Serialize + DeserializeOwned> DeSerializer<T> for Bincode {
        fn serialize(&self, val: &T) -> error::DeSerResult<Vec<u8>> {
            Ok(serialize(val)?)
        }
        fn deserialize<R: Read>(&self, s: R) -> error::DeSerResult<T> {
            Ok(deserialize_from(s)?)
        }
    }
}