wjp/
serializer.rs

1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
2use std::hash::Hash;
3use std::isize;
4use std::str::FromStr;
5
6use crate::deserialize::Deserialize;
7use crate::error::ParseError;
8use crate::values::Values;
9
10/// Trait for Serializing Rust Structs into JSON
11pub trait Serialize {
12    /// This method is used to serialize your struct into a Values Object representing a JSON hierarchy
13    ///
14    /// Example:
15    ///
16    /// ```rust
17    /// //Example Struct to show how this library works
18    /// use wjp::{map, Serialize, Values};
19    /// #[derive(Debug)]
20    /// struct Example {
21    ///     code: f32,
22    ///     messages: Vec<String>,
23    ///     opt: Option<bool>,
24    /// }
25    ///
26    /// // Implementing the Serialize Trait allows you to call the .json() method on your struct
27    /// impl Serialize for Example {
28    ///     fn serialize(&self) -> Values {
29    ///         // The map!() macro is a helper to create a hashmap from the given values
30    ///         Values::Struct(map!(
31    ///             // Many Data Structures and Types already have Serialize implemented
32    ///             ("code", &self.code),
33    ///             ("messages", &self.messages),
34    ///             ("opt", &self.opt)
35    ///         ))
36    ///     }
37    /// }
38    /// let example = Example {
39    ///     code: 123.0,
40    ///     messages: vec!["Important".to_string(), "Message".to_string()],
41    ///     opt: None,
42    /// };   
43    /// // After implementing these two traits you can call the .json() method to serialize your struct
44    /// let json = example.json();
45    /// println!("{}", json);
46    /// ```
47    fn serialize(&self) -> Values;
48    /// This method has a default impl and it is not advised on writing your own impl for your structs
49    fn json(&self) -> String {
50        self.serialize().to_string()
51    }
52}
53
54impl<S: Serialize> Serialize for Option<S> {
55    fn serialize(&self) -> Values {
56        match self {
57            None => Values::Null,
58            Some(s) => s.serialize(),
59        }
60    }
61}
62
63impl<R: Serialize, E: Serialize> Serialize for Result<R, E> {
64    fn serialize(&self) -> Values {
65        match self {
66            Err(e) => e.serialize(),
67            Ok(r) => r.serialize(),
68        }
69    }
70}
71
72impl<T: Serialize> Serialize for Vec<T> {
73    fn serialize(&self) -> Values {
74        Values::Array(self.iter().map(|e| e.serialize()).collect())
75    }
76}
77
78impl<T: Serialize> Serialize for &[T] {
79    fn serialize(&self) -> Values {
80        Values::Array(self.iter().map(|e| e.serialize()).collect())
81    }
82}
83
84impl<K: Serialize, V: Serialize> Serialize for HashMap<K, V> {
85    fn serialize(&self) -> Values {
86        let mut map = HashMap::with_capacity(4);
87        for (k, v) in self.iter() {
88            map.insert(k.serialize().to_string(), v.serialize());
89        }
90        Values::Struct(map)
91    }
92}
93
94impl<I: Serialize> Serialize for HashSet<I> {
95    fn serialize(&self) -> Values {
96        Values::Array(self.iter().map(|val| val.serialize()).collect())
97    }
98}
99
100impl<K: Serialize, V: Serialize> Serialize for BTreeMap<K, V> {
101    fn serialize(&self) -> Values {
102        let mut map = HashMap::with_capacity(4);
103        for (k, v) in self.iter() {
104            map.insert(k.serialize().to_string(), v.serialize());
105        }
106        Values::Struct(map)
107    }
108}
109
110impl<I: Serialize> Serialize for BTreeSet<I> {
111    fn serialize(&self) -> Values {
112        Values::Array(self.iter().map(|val| val.serialize()).collect())
113    }
114}
115
116impl Serialize for f32 {
117    fn serialize(&self) -> Values {
118        Values::Number(*self as f64)
119    }
120}
121
122impl Serialize for f64 {
123    fn serialize(&self) -> Values {
124        Values::Number(*self)
125    }
126}
127
128impl Serialize for str {
129    fn serialize(&self) -> Values {
130        Values::String(String::from(self))
131    }
132}
133
134impl Serialize for &str {
135    fn serialize(&self) -> Values {
136        Serialize::serialize(*self)
137    }
138}
139
140impl Serialize for String {
141    fn serialize(&self) -> Values {
142        Serialize::serialize(self.as_str())
143    }
144}
145
146impl Serialize for char {
147    fn serialize(&self) -> Values {
148        Serialize::serialize(&self.to_string())
149    }
150}
151
152impl Serialize for bool {
153    fn serialize(&self) -> Values {
154        Values::Boolean(*self)
155    }
156}
157
158impl Serialize for usize {
159    fn serialize(&self) -> Values {
160        Values::Number(*self as f64)
161    }
162}
163
164impl Serialize for u8 {
165    fn serialize(&self) -> Values {
166        Values::Number(*self as f64)
167    }
168}
169
170impl Serialize for u16 {
171    fn serialize(&self) -> Values {
172        Values::Number(*self as f64)
173    }
174}
175
176impl Serialize for u32 {
177    fn serialize(&self) -> Values {
178        Values::Number(*self as f64)
179    }
180}
181
182impl Serialize for u64 {
183    fn serialize(&self) -> Values {
184        Values::Number(*self as f64)
185    }
186}
187
188impl Serialize for u128 {
189    fn serialize(&self) -> Values {
190        Values::Number(*self as f64)
191    }
192}
193
194impl Serialize for isize {
195    fn serialize(&self) -> Values {
196        Values::Number(*self as f64)
197    }
198}
199
200impl Serialize for i8 {
201    fn serialize(&self) -> Values {
202        Values::Number(*self as f64)
203    }
204}
205
206impl Serialize for i16 {
207    fn serialize(&self) -> Values {
208        Values::Number(*self as f64)
209    }
210}
211
212impl Serialize for i32 {
213    fn serialize(&self) -> Values {
214        Values::Number(*self as f64)
215    }
216}
217
218impl Serialize for i64 {
219    fn serialize(&self) -> Values {
220        Values::Number(*self as f64)
221    }
222}
223
224impl Serialize for i128 {
225    fn serialize(&self) -> Values {
226        Values::Number(*self as f64)
227    }
228}
229
230impl<T: TryFrom<Values>> TryFrom<Values> for Vec<T> {
231    type Error = ParseError;
232    fn try_from(value: Values) -> Result<Self, Self::Error> {
233        let mut pre = value.get_list_opt().ok_or(ParseError::new())?;
234        let mut post = Vec::with_capacity(pre.len());
235        while !pre.is_empty() {
236            post.push(T::try_from(pre.pop().unwrap()).map_err(|_err| ParseError::new())?)
237        }
238        Ok(post)
239    }
240}
241
242impl TryFrom<Values> for char {
243    type Error = ParseError;
244    fn try_from(value: Values) -> Result<Self, Self::Error> {
245        String::try_from(value)?
246            .chars()
247            .next()
248            .ok_or(ParseError::new())
249    }
250}
251
252impl TryFrom<Values> for String {
253    type Error = ParseError;
254    fn try_from(value: Values) -> Result<Self, Self::Error> {
255        value.get_string().ok_or(ParseError::new())
256    }
257}
258
259impl TryFrom<Values> for f32 {
260    type Error = ParseError;
261    fn try_from(value: Values) -> Result<Self, Self::Error> {
262        f64::try_from(value).map(|val| val as f32)
263    }
264}
265
266impl TryFrom<Values> for f64 {
267    type Error = ParseError;
268    fn try_from(value: Values) -> Result<Self, Self::Error> {
269        value.get_number().ok_or(ParseError::new())
270    }
271}
272
273impl TryFrom<Values> for usize {
274    type Error = ParseError;
275    fn try_from(value: Values) -> Result<Self, Self::Error> {
276        value
277            .get_number()
278            .map(|f| f.to_string())
279            .map(|s| usize::from_str(s.as_str()))
280            .ok_or(ParseError::new())?
281            .map_err(|_err| ParseError::new())
282    }
283}
284
285impl TryFrom<Values> for u8 {
286    type Error = ParseError;
287    fn try_from(value: Values) -> Result<Self, Self::Error> {
288        usize::try_from(value)
289            .map(u8::try_from)?
290            .map_err(|_err| ParseError::new())
291    }
292}
293
294impl TryFrom<Values> for u16 {
295    type Error = ParseError;
296    fn try_from(value: Values) -> Result<Self, Self::Error> {
297        usize::try_from(value)
298            .map(u16::try_from)?
299            .map_err(|_err| ParseError::new())
300    }
301}
302
303impl TryFrom<Values> for u32 {
304    type Error = ParseError;
305    fn try_from(value: Values) -> Result<Self, Self::Error> {
306        usize::try_from(value)
307            .map(u32::try_from)?
308            .map_err(|_err| ParseError::new())
309    }
310}
311
312impl TryFrom<Values> for u64 {
313    type Error = ParseError;
314    fn try_from(value: Values) -> Result<Self, Self::Error> {
315        usize::try_from(value)
316            .map(u64::try_from)?
317            .map_err(|_err| ParseError::new())
318    }
319}
320
321impl TryFrom<Values> for u128 {
322    type Error = ParseError;
323    fn try_from(value: Values) -> Result<Self, Self::Error> {
324        usize::try_from(value)
325            .map(u128::try_from)?
326            .map_err(|_err| ParseError::new())
327    }
328}
329
330impl TryFrom<Values> for isize {
331    type Error = ParseError;
332    fn try_from(value: Values) -> Result<Self, Self::Error> {
333        String::try_from(value)
334            .map(|str| isize::from_str(str.as_str()))?
335            .map_err(|_err| ParseError::new())
336    }
337}
338
339impl TryFrom<Values> for i8 {
340    type Error = ParseError;
341    fn try_from(value: Values) -> Result<Self, Self::Error> {
342        isize::try_from(value)
343            .map(i8::try_from)?
344            .map_err(|_err| ParseError::new())
345    }
346}
347
348impl TryFrom<Values> for i16 {
349    type Error = ParseError;
350    fn try_from(value: Values) -> Result<Self, Self::Error> {
351        isize::try_from(value)
352            .map(i16::try_from)?
353            .map_err(|_err| ParseError::new())
354    }
355}
356
357impl TryFrom<Values> for i32 {
358    type Error = ParseError;
359    fn try_from(value: Values) -> Result<Self, Self::Error> {
360        isize::try_from(value)
361            .map(i32::try_from)?
362            .map_err(|_err| ParseError::new())
363    }
364}
365
366impl TryFrom<Values> for i64 {
367    type Error = ParseError;
368    fn try_from(value: Values) -> Result<Self, Self::Error> {
369        isize::try_from(value)
370            .map(i64::try_from)?
371            .map_err(|_err| ParseError::new())
372    }
373}
374
375impl TryFrom<Values> for i128 {
376    type Error = ParseError;
377    fn try_from(value: Values) -> Result<Self, Self::Error> {
378        isize::try_from(value)
379            .map(i128::try_from)?
380            .map_err(|_err| ParseError::new())
381    }
382}
383
384impl TryFrom<Values> for bool {
385    type Error = ParseError;
386    fn try_from(value: Values) -> Result<Self, Self::Error> {
387        value.get_bool().ok_or(ParseError::new())
388    }
389}
390
391impl<K, V> TryFrom<Values> for HashMap<K, V>
392where
393    K: TryFrom<Values, Error = ParseError> + Eq + Hash,
394    V: TryFrom<Values, Error = ParseError>,
395{
396    type Error = ParseError;
397    fn try_from(value: Values) -> Result<Self, Self::Error> {
398        let mut map = HashMap::new();
399        for (key, value) in value.get_struct().ok_or(ParseError::new())? {
400            map.insert(K::deserialize_str(key.as_str())?, V::try_from(value)?);
401        }
402        Ok(map)
403    }
404}
405
406impl<K, V> TryFrom<Values> for BTreeMap<K, V>
407where
408    K: TryFrom<Values, Error = ParseError> + Eq + Hash + Ord,
409    V: TryFrom<Values, Error = ParseError>,
410{
411    type Error = ParseError;
412    fn try_from(value: Values) -> Result<Self, Self::Error> {
413        let mut map = BTreeMap::new();
414        for (key, value) in value.get_struct().ok_or(ParseError::new())? {
415            map.insert(
416                Deserialize::deserialize_str(key.as_str())?,
417                V::try_from(value)?,
418            );
419        }
420        Ok(map)
421    }
422}
423
424impl<V> TryFrom<Values> for BTreeSet<V>
425where
426    V: TryFrom<Values, Error = ParseError> + Ord,
427{
428    type Error = ParseError;
429    fn try_from(value: Values) -> Result<Self, Self::Error> {
430        let val = value.get_list_opt().ok_or(ParseError::new())?;
431        let mut set = BTreeSet::new();
432        for item in val {
433            set.insert(V::try_from(item)?);
434        }
435        Ok(set)
436    }
437}
438
439impl<V> TryFrom<Values> for HashSet<V>
440where
441    V: TryFrom<Values, Error = ParseError> + Hash + Eq,
442{
443    type Error = ParseError;
444    fn try_from(value: Values) -> Result<Self, Self::Error> {
445        let val = value.get_list_opt().ok_or(ParseError::new())?;
446        let mut set = HashSet::new();
447        for item in val {
448            set.insert(V::try_from(item)?);
449        }
450        Ok(set)
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use std::collections::HashMap;
457    use std::fmt::Display;
458
459    use crate::serializer::Serialize;
460    use crate::{map, Deserialize, ParseError, SerializeHelper, Values};
461
462    #[test]
463    pub fn test_serialized_option_none() {
464        let none: Option<bool> = None;
465        assert_eq!("null", none.serialize().to_string());
466    }
467
468    #[test]
469    pub fn test_serialized_option_some() {
470        let some = Some(true);
471        assert_eq!("true", some.serialize().to_string());
472    }
473
474    #[test]
475    pub fn test_serialized_result_err() {
476        let string: Result<&str, &str> = Err("Hello I am a Error");
477        assert_eq!("\"Hello I am a Error\"", string.serialize().to_string())
478    }
479
480    #[test]
481    pub fn test_serialized_result_ok() {
482        let num: Result<f64, &str> = Ok(123.22);
483        assert_eq!("123.22", num.serialize().to_string())
484    }
485
486    #[test]
487    pub fn test_serialized_vec_empty() {
488        let arr: Vec<bool> = vec![];
489        assert_eq!("[]", arr.serialize().to_string())
490    }
491
492    #[test]
493    pub fn test_serialized_vec_filled() {
494        let arr = vec![true, false, false, false];
495        assert_eq!("[true,false,false,false]", arr.serialize().to_string())
496    }
497
498    #[test]
499    pub fn test_serialized_map_empty() {
500        let map: HashMap<String, String> = map!();
501        assert_eq!("{}", map.serialize().to_string())
502    }
503
504    #[test]
505    pub fn test_serialized_map_filled() {
506        let map = map!(("Hello", &true));
507        assert_eq!("{\"\"Hello\"\":true}", map.serialize().to_string())
508    }
509
510    #[test]
511    pub fn test_serialized_map_filled_s() {
512        #[derive(Hash, Eq, PartialEq, Debug)]
513        struct IDK {
514            map: u128,
515        }
516        impl Display for IDK {
517            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
518                write!(f, "{}", self.json())
519            }
520        }
521        impl TryFrom<Values> for IDK {
522            type Error = ParseError;
523            fn try_from(value: Values) -> Result<Self, Self::Error> {
524                let mut struc = value.get_struct().ok_or(ParseError::new())?;
525                Ok(Self {
526                    map: struc.map_val("map", u128::try_from)?,
527                })
528            }
529        }
530        impl Serialize for IDK {
531            fn serialize(&self) -> Values {
532                Values::Struct(map!(("map", &self.map)))
533            }
534        }
535
536        let mut map = HashMap::new();
537        map.insert(100u8, IDK { map: 1 });
538        let ser = map.json();
539        println!("{}", ser);
540        let back = HashMap::<u8, IDK>::deserialize_str(ser.as_str());
541        println!("{:?}", back);
542    }
543}