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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::hash::Hash;
use std::isize;
use std::str::FromStr;

use crate::deserialize::Deserialize;
use crate::error::ParseError;
use crate::values::Values;
/// Trait for Serializing Rust Structs into JSON
pub trait Serialize {
    /// This method is used to serialize your struct into a Values Object representing a JSON hierarchy
    ///
    /// Example:
    ///
    /// ```rust
    /// //Example Struct to show how this library works
    /// use wjp::{map, Serialize, Values};
    /// #[derive(Debug)]
    /// struct Example {
    ///     code: f32,
    ///     messages: Vec<String>,
    ///     opt: Option<bool>,
    /// }
    ///
    /// // Implementing the Serialize Trait allows you to call the .json() method on your struct
    /// impl Serialize for Example {
    ///     fn serialize(&self) -> Values {
    ///         // The map!() macro is a helper to create a hashmap from the given values
    ///         Values::Struct(map!(
    ///             // Many Data Structures and Types already have Serialize implemented
    ///             ("code", self.code.serialize()),
    ///             ("messages", self.messages.serialize()),
    ///             ("opt", self.opt.serialize())
    ///         ))
    ///     }
    /// }
    /// let example = Example {
    ///     code: 123.0,
    ///     messages: vec!["Important".to_string(), "Message".to_string()],
    ///     opt: None,
    /// };   
    /// // After implementing these two traits you can call the .json() method to serialize your struct
    /// let json = example.json();
    /// println!("{}", json);
    /// ```
    fn serialize(&self) -> Values;
    /// This method has a default impl and it is not advised on writing your own impl for your structs
    fn json(&self) -> String {
        self.serialize().to_string()
    }
}

impl<S: Serialize> Serialize for Option<S> {
    fn serialize(&self) -> Values {
        match self {
            None => Values::Null,
            Some(s) => s.serialize(),
        }
    }
}

impl<R: Serialize, E: Serialize> Serialize for Result<R, E> {
    fn serialize(&self) -> Values {
        match self {
            Err(e) => e.serialize(),
            Ok(r) => r.serialize(),
        }
    }
}

impl<T: Serialize> Serialize for Vec<T> {
    fn serialize(&self) -> Values {
        Values::Array(self.iter().map(|e| e.serialize()).collect())
    }
}

impl<T: Serialize> Serialize for &[T] {
    fn serialize(&self) -> Values {
        Values::Array(self.iter().map(|e| e.serialize()).collect())
    }
}

impl<K: ToString, V: Serialize> Serialize for HashMap<K, V> {
    fn serialize(&self) -> Values {
        let mut map = HashMap::with_capacity(4);
        for (k, v) in self.iter() {
            map.insert(k.to_string(), v.serialize());
        }
        Values::Struct(map)
    }
}

impl<I: Serialize> Serialize for HashSet<I> {
    fn serialize(&self) -> Values {
        Values::Array(self.iter().map(|val| val.serialize()).collect())
    }
}

impl<K: ToString, V: Serialize> Serialize for BTreeMap<K, V> {
    fn serialize(&self) -> Values {
        let mut map = HashMap::with_capacity(4);
        for (k, v) in self.iter() {
            map.insert(k.to_string(), v.serialize());
        }
        Values::Struct(map)
    }
}

impl<I: Serialize> Serialize for BTreeSet<I> {
    fn serialize(&self) -> Values {
        Values::Array(self.iter().map(|val| val.serialize()).collect())
    }
}

impl Serialize for f32 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for f64 {
    fn serialize(&self) -> Values {
        Values::Number(*self)
    }
}

impl Serialize for str {
    fn serialize(&self) -> Values {
        Values::String(String::from(self))
    }
}

impl Serialize for &str {
    fn serialize(&self) -> Values {
        Serialize::serialize(*self)
    }
}

impl Serialize for String {
    fn serialize(&self) -> Values {
        Serialize::serialize(self.as_str())
    }
}

impl Serialize for char {
    fn serialize(&self) -> Values {
        Serialize::serialize(&self.to_string())
    }
}

impl Serialize for bool {
    fn serialize(&self) -> Values {
        Values::Boolean(*self)
    }
}

impl Serialize for usize {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for u8 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for u16 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for u32 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for u64 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for u128 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for isize {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for i8 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for i16 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for i32 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for i64 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl Serialize for i128 {
    fn serialize(&self) -> Values {
        Values::Number(*self as f64)
    }
}

impl<T: TryFrom<Values>> TryFrom<Values> for Vec<T> {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        let mut pre = value.get_list_opt().ok_or(ParseError::new())?;
        let mut post = Vec::with_capacity(pre.len());
        while !pre.is_empty() {
            post.push(T::try_from(pre.pop().unwrap()).map_err(|_err| ParseError::new())?)
        }
        Ok(post)
    }
}

impl TryFrom<Values> for char {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        String::try_from(value)?
            .chars()
            .next()
            .ok_or(ParseError::new())
    }
}

impl TryFrom<Values> for String {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        value.get_string().ok_or(ParseError::new())
    }
}

impl TryFrom<Values> for f32 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        f64::try_from(value).map(|val| val as f32)
    }
}
impl TryFrom<Values> for f64 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        value.get_number().ok_or(ParseError::new())
    }
}

impl TryFrom<Values> for usize {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        value
            .get_number()
            .map(|f| f.to_string())
            .map(|s| usize::from_str(s.as_str()))
            .ok_or(ParseError::new())?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for u8 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        usize::try_from(value)
            .map(u8::try_from)?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for u16 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        usize::try_from(value)
            .map(u16::try_from)?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for u32 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        usize::try_from(value)
            .map(u32::try_from)?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for u64 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        usize::try_from(value)
            .map(u64::try_from)?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for u128 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        usize::try_from(value)
            .map(u128::try_from)?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for isize {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        String::try_from(value)
            .map(|str| isize::from_str(str.as_str()))?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for i8 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        isize::try_from(value)
            .map(i8::try_from)?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for i16 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        isize::try_from(value)
            .map(i16::try_from)?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for i32 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        isize::try_from(value)
            .map(i32::try_from)?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for i64 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        isize::try_from(value)
            .map(i64::try_from)?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for i128 {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        isize::try_from(value)
            .map(i128::try_from)?
            .map_err(|_err| ParseError::new())
    }
}

impl TryFrom<Values> for bool {
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        value.get_bool().ok_or(ParseError::new())
    }
}

impl<K, V> TryFrom<Values> for HashMap<K, V>
where
    K: TryFrom<Values, Error = ParseError> + Eq + Hash,
    V: TryFrom<Values, Error = ParseError>,
{
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        let mut map = HashMap::new();
        for (key, value) in value.get_struct().ok_or(ParseError::new())? {
            map.insert(Deserialize::deserialize(key)?, V::try_from(value)?);
        }
        Ok(map)
    }
}

impl<K, V> TryFrom<Values> for BTreeMap<K, V>
where
    K: TryFrom<Values, Error = ParseError> + Eq + Hash + Ord,
    V: TryFrom<Values, Error = ParseError>,
{
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        let mut map = BTreeMap::new();
        for (key, value) in value.get_struct().ok_or(ParseError::new())? {
            map.insert(Deserialize::deserialize(key)?, V::try_from(value)?);
        }
        Ok(map)
    }
}

impl<V> TryFrom<Values> for BTreeSet<V>
where
    V: TryFrom<Values, Error = ParseError> + Ord,
{
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        let val = value.get_list_opt().ok_or(ParseError::new())?;
        let mut set = BTreeSet::new();
        for item in val {
            set.insert(V::try_from(item)?);
        }
        Ok(set)
    }
}

impl<V> TryFrom<Values> for HashSet<V>
where
    V: TryFrom<Values, Error = ParseError> + Hash + Eq,
{
    type Error = ParseError;
    fn try_from(value: Values) -> Result<Self, Self::Error> {
        let val = value.get_list_opt().ok_or(ParseError::new())?;
        let mut set = HashSet::new();
        for item in val {
            set.insert(V::try_from(item)?);
        }
        Ok(set)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use crate::map;
    use crate::serializer::Serialize;

    #[test]
    pub fn test_serialized_option_none() {
        let none: Option<bool> = None;
        assert_eq!("null", none.serialize().to_string());
    }
    #[test]
    pub fn test_serialized_option_some() {
        let some = Some(true);
        assert_eq!("true", some.serialize().to_string());
    }
    #[test]
    pub fn test_serialized_result_err() {
        let string: Result<&str, &str> = Err("Hello I am a Error");
        assert_eq!("\"Hello I am a Error\"", string.serialize().to_string())
    }
    #[test]
    pub fn test_serialized_result_ok() {
        let num: Result<f64, &str> = Ok(123.22);
        assert_eq!("123.22", num.serialize().to_string())
    }
    #[test]
    pub fn test_serialized_vec_empty() {
        let arr: Vec<bool> = vec![];
        assert_eq!("[]", arr.serialize().to_string())
    }
    #[test]
    pub fn test_serialized_vec_filled() {
        let arr = vec![true, false, false, false];
        assert_eq!("[true,false,false,false]", arr.serialize().to_string())
    }
    #[test]
    pub fn test_serialized_map_empty() {
        let map: HashMap<String, String> = map!();
        assert_eq!("{}", map.serialize().to_string())
    }
    #[test]
    pub fn test_serialized_map_filled() {
        let map = map!(("Hello", true));
        assert_eq!("{\"Hello\":true}", map.serialize().to_string())
    }
}