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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use super::RouteError;
use chrono::{DateTime, Utc};
use std::collections::HashMap;

/// A JSON structure that is formatted
/// like the following:
///
/// {
///     "key": "value"
/// }
#[derive(Debug)]
pub struct JsonObject {
    keys: HashMap<String, String>,
}

impl JsonObject {

    /// Creates an empty JSON object.
    /// This is useful for building a JSON
    /// object from scratch.
    pub fn empty() -> JsonObject {
        JsonObject {
            keys: HashMap::new()
        }
    }

    /// Builds a JSONObject from a string
    /// containing keys and values.
    ///
    /// # Arguments
    ///
    /// * `json` — An owned string containing the JSON.
    pub fn from_string(json: &str) -> JsonObject {
        let mut keys: HashMap<String, String> = HashMap::new();

        let mut current_key = String::new();
        let mut current_value = String::new();

        let mut enumerator = json.chars();

        while let Some(c) = enumerator.next() {
            if c == '"' {
                // Get key content.
                'key: while let Some(key_content) = enumerator.next() {
                    if key_content != '"' {
                        current_key.push(key_content)
                    } else {
                        // Skip the colon (and spaces)
                        for t in enumerator.by_ref() {
                            if t == ':' { break }
                        }
                        break 'key;
                    }
                }

                // Get value of derived key
                let mut value_start = ' ';
                while value_start == ' ' {
                    value_start = enumerator.next().unwrap();
                }

                if let Some(t) = JsonType::type_for_delimiter(value_start) {
                    // Read value
                    if t == JsonType::Primitive {
                        // We need to add the first index to the value.
                        // Because the other types have delimeters (", {, [)
                        // but primitives do not.
                        current_value.push(value_start);
                        let mut in_quote = value_start == '"';
                        for inner_value in enumerator.by_ref() {
                            if current_value.chars().last().unwrap_or('_') != '\\'
                                && inner_value == '"'
                            {
                                in_quote = !in_quote;
                            }
                            if (inner_value == ',' || inner_value == '}' || inner_value == ']')
                                && !in_quote
                            {
                                break;
                            } else {
                                current_value.push(inner_value);
                            }
                        }
                    } else if t == JsonType::Object {
                        let mut delimiter_stack_count = 1;
                        current_value.push('{');
                        for inner_value in enumerator.by_ref() {
                            current_value.push(inner_value);
                            if inner_value == '{' {
                                delimiter_stack_count += 1;
                            }
                            if inner_value == '}' {
                                delimiter_stack_count -= 1;
                                if delimiter_stack_count == 0 {
                                    // Remove the trailing }
                                    // current_value.pop();
                                    break;
                                }
                            }
                        }
                    } else if t == JsonType::Array {
                        let mut delimiter_stack_count = 1;
                        current_value.push('[');
                        for inner_value in enumerator.by_ref() {
                            current_value.push(inner_value);
                            if inner_value == '[' {
                                delimiter_stack_count += 1;
                            }
                            if inner_value == ']' {
                                delimiter_stack_count -= 1;
                                if delimiter_stack_count == 0 {
                                    break;
                                }
                            }
                        }
                    }
                    keys.insert(current_key, current_value);
                }
                current_key = String::new();
                current_value = String::new();
            }
        }
        JsonObject { keys }
    }

    /// Return a key of the JSON object as a type which
    /// implements JsonRetrieve.
    ///
    /// # Arguments
    ///
    /// * `key` — The key to retrieve from.
    pub fn get<T: JsonRetrieve>(&self, key: &str) -> Result<T, JsonParseError> {
        T::parse(key.to_string(), self.keys.get(key))
    }

    /// Return a key of the JSON object as a type which
    /// implements JsonRetrieve.
    ///
    /// # Arguments
    ///
    /// * `key` — The key to retrieve from.
    pub fn set<T: ToJson>(&mut self, key: &str, data: T) {
        self.keys.insert(key.to_string(), data.to_json());
    }
}
impl Default for JsonObject {
    fn default() -> Self {
        JsonObject::empty()
    }
}

#[derive(Debug)]
pub struct JsonArray {
    values: Vec<String>,
}
impl JsonArray {
    /// Creates an empty JSON array.
    /// This is useful for building a JSON
    /// array from scratch.
    pub fn empty() -> JsonArray {
        JsonArray { values: Vec::new() }
    }

    /// Builds a JSONArray from a string
    /// containing children that implement
    /// `JsonRetreive`
    ///
    /// # Arguments
    ///
    /// * `json` — An owned string containing the JSON.
    pub fn from_string(json: &str) -> JsonArray {
        let mut values: Vec<String> = Vec::new();
        let json = json[1..json.chars().count()].to_string();

        let mut enumerator = json.chars().peekable();
        let mut current_value = String::new();

        while enumerator.peek().is_some() {
            let mut value_start = ' ';
            // Trim any extra whitespace
            for value_spacing in enumerator.by_ref() {
                if value_spacing != ' ' {
                    value_start = value_spacing;
                    break;
                }
            }
            if let Some(current_type) = JsonType::type_for_delimiter(value_start) {
                // Read value
                if current_type == JsonType::Primitive {
                    // We need to add the first index to the value.
                    // Because the other types have delimeters (", {, [)
                    // but primitives do not.
                    current_value.push(value_start);
                    for inner_value in enumerator.by_ref() {
                        if inner_value != ',' {
                            current_value.push(inner_value)
                        } else {
                            break;
                        }
                    }
                } else if current_type == JsonType::Object {
                    let mut delimiter_stack_count = 1;
                    current_value.push('{');
                    for inner_value in enumerator.by_ref() {
                        current_value.push(inner_value);
                        if inner_value == '{' {
                            delimiter_stack_count += 1;
                        }
                        if inner_value == '}' {
                            delimiter_stack_count -= 1;
                            if delimiter_stack_count == 0 {
                                // Remove the trailing }
                                break;
                            }
                        }
                    }
                } else if current_type == JsonType::Array {
                    let mut delimiter_stack_count = 1;
                    current_value.push('[');
                    for inner_value in enumerator.by_ref() {
                        current_value.push(inner_value);
                        if inner_value == '[' {
                            delimiter_stack_count += 1;
                        }
                        if inner_value == ']' {
                            delimiter_stack_count -= 1;
                            if delimiter_stack_count == 0 {
                                break;
                            }
                        }
                    }
                }
                // Because the primitive types do not have a ending delimiter
                // and read straight to the comma, we do not search until a comma
                // if our type is primitive.
                if current_type != JsonType::Primitive {
                    for value_skipper in enumerator.by_ref() {
                        if value_skipper == ',' {
                            break;
                        }
                    }
                }
            }
            values.push(current_value);
            current_value = String::new();
        }

        JsonArray { values }
    }

    /// Gets the object at the index as a type
    /// that implements JsonRetrieve.
    ///
    /// # Arguments
    ///
    /// * `index` — The index to retrieve from.
    pub fn get<T: JsonRetrieve>(&self, index: usize) -> Result<T, JsonParseError> {
        T::parse(index.to_string(), self.values.get(index))
    }

    /// Converts all elements of this JSONArray
    /// to a type that implements JsonRetrieve.
    /// Progagates errors if any child keys are invalid.
    pub fn map<T: JsonRetrieve>(&self) -> Result<Vec<T>, JsonParseError> {
        if self.values.is_empty() {
            return Ok(Vec::new());
        }
        let mut build = Vec::new();
        for i in 0..self.values.len() {
            let value = &self.values[i];
            build.push(T::parse(i.to_string(), Some(value))?);
        }
        Ok(build)
    }
}
impl Default for JsonArray {
    fn default() -> Self {
        JsonArray::empty()
    }
}

#[derive(Debug, PartialEq)]
enum JsonType {
    Primitive,
    Object,
    Array,
}

impl JsonType {
    pub fn type_for_delimiter(dlm: char) -> Option<JsonType> {
        if dlm == '[' {
            Some(JsonType::Array)
        } else if dlm == '{' {
            Some(JsonType::Object)
        } else {
            Some(JsonType::Primitive)
        }
    }
}

#[derive(Debug)]
pub enum JsonParseError {
    NotFound(String),
    InvalidType(String, &'static str),
}
impl From<JsonParseError> for RouteError {
    fn from(val: JsonParseError) -> Self {
        match val {
            JsonParseError::NotFound(k) => RouteError::bad_request(&format!("Key {} not found", k)),
            JsonParseError::InvalidType(k, t) => RouteError::bad_request(&format!("Key {} expected type {}", k, t)),
        }
    }
}

/// ToJson is a trait that allows any conforming
/// structs to convert to a JSON format.
///
/// A default implemenation is most easily
/// obtained by deriving this trait.
pub trait ToJson {
    /// ToJson creates a JSON string from
    /// anything which implements it
    fn to_json(&self) -> String;
}

/// FromJs is a trait that allows any conforming
/// structs to be converted from a JSON format.
///
/// A default implemenation is most easily
/// obtained by deriving this trait.
pub trait FromJson {
    fn from_json(json: &JsonObject) -> Result<Self, JsonParseError>
    where
        Self: Sized;
}

impl ToJson for String {
    fn to_json(&self) -> String {
        let mut o = String::new();
        o += "\"";
        o += &self.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n").replace('\t', "\\t");
        o += "\"";
        o
    }
}
impl ToJson for str {
    fn to_json(&self) -> String {
        let mut o = String::new();
        o += "\"";
        o += &self.replace('\\', "\\\\").replace('"', "\\\"").replace('\n', "\\n").replace('\t', "\\t");
        o += "\"";
        o
    }
}
impl ToJson for i32 {
    fn to_json(&self) -> String {
        self.to_string()
    }
}
impl ToJson for i64 {
    fn to_json(&self) -> String {
        self.to_string()
    }
}
impl ToJson for u32 {
    fn to_json(&self) -> String {
        self.to_string()
    }
}
impl ToJson for u64 {
    fn to_json(&self) -> String {
        self.to_string()
    }
}
impl ToJson for f32 {
    fn to_json(&self) -> String {
        self.to_string()
    }
}
impl ToJson for f64 {
    fn to_json(&self) -> String {
        self.to_string()
    }
}
impl ToJson for bool {
    fn to_json(&self) -> String {
        if *self {
            "true".to_string()
        } else {
            "false".to_string()
        }
    }
}
impl<T: ToJson> ToJson for Vec<T> {
    fn to_json(&self) -> String {
        let mut output = String::new();
        output += "[";
        for i in self.iter() {
            output += &i.to_json();
            output += ",";
        }
        if !self.is_empty() {
            output.pop();
        }
        output += "]";
        output
    }
}
impl<T: ToJson> ToJson for Option<T> {
    fn to_json(&self) -> String {
        match self {
            Some(x) => x.to_json(),
            None => "null".to_string(),
        }
    }
}
impl<K: ToJson, V: ToJson> ToJson for HashMap<K, V> {
    fn to_json(&self) -> String {
        let mut output = String::new();
        output += "{";
        for (k, v) in self {
            output += "\"";
            output += &k.to_json();
            output += "\":";
            output += &v.to_json();
            output += ",";
        }
        output.pop();
        output += "}";
        output
    }
}
impl ToJson for DateTime<Utc> {
    fn to_json(&self) -> String {
        format!("\"{}\"", self.to_rfc3339())
    }
}
impl ToJson for JsonObject {
    fn to_json(&self) -> String {
        let mut output = "{".to_string();
        for (k, v) in &self.keys {
            output += "\"";
            output += k;
            output += "\":";
            output += v;
            output += ",";
        }
        output.pop();
        output += "}";
        output
    }
}
impl ToJson for JsonArray {
    fn to_json(&self) -> String {
        let mut output = "[".to_string();
        for v in &self.values {
            output += v;
            output += ",";
        }
        output.pop();
        output += "]";
        output
    }
}

pub trait JsonRetrieve {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError>
    where
        Self: Sized;
}

impl JsonRetrieve for String {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        let mut v = value.ok_or(JsonParseError::NotFound(key))?.clone();
        v.remove(0);
        v.pop();
        v = v.replace("\\\"", "\"");
        Ok(v)
    }
}
impl JsonRetrieve for i32 {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        if let Some(v) = value {
            Ok(v.parse().map_err(|_| JsonParseError::InvalidType(key, "i32"))?)
        } else {
            Err(JsonParseError::NotFound(key))
        }
    }
}
impl JsonRetrieve for i64 {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        if let Some(v) = value {
            Ok(v.parse().map_err(|_| JsonParseError::InvalidType(key, "i64"))?)
        } else {
            Err(JsonParseError::NotFound(key))
        }
    }
}
impl JsonRetrieve for f32 {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        if let Some(v) = value {
            Ok(v.parse().map_err(|_| JsonParseError::InvalidType(key, "f32"))?)
        } else {
            Err(JsonParseError::NotFound(key))
        }
    }
}
impl JsonRetrieve for f64 {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        if let Some(v) = value {
            Ok(v.parse().map_err(|_| JsonParseError::InvalidType(key, "f64"))?)
        } else {
            Err(JsonParseError::NotFound(key))
        }
    }
}
impl JsonRetrieve for bool {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError>  {
        if let Some(v) = value {
            match v.as_ref() {
                "true" => Ok(true),
                "false" => Ok(false),
                _ => Err(JsonParseError::InvalidType(key, "bool")),
            }
        } else {
            Err(JsonParseError::NotFound(key))
        }
    }
}
impl<T: JsonRetrieve> JsonRetrieve for Vec<T> {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        JsonArray::from_string(value.ok_or(JsonParseError::NotFound(key))?).map()
    }
}
impl<T: JsonRetrieve> JsonRetrieve for Option<T> {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        if let Some(v) = value {
            if v != "null" {
                return Ok(Some(T::parse(key, value)?));
            }
        }
        Ok(None)
    }
}
impl JsonRetrieve for JsonObject {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        Ok(JsonObject::from_string(value.ok_or(JsonParseError::NotFound(key))?))
    }
}
impl JsonRetrieve for JsonArray {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        Ok(JsonArray::from_string(value.ok_or(JsonParseError::NotFound(key))?))
    }
}
impl JsonRetrieve for DateTime<Utc> {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        if let Some(v) = value {
            Ok(DateTime::parse_from_rfc3339(&v.replace('\"', ""))
                .map_err(|_| JsonParseError::InvalidType(key, "RFC3339 Date"))?
                .with_timezone(&Utc))
        } else {
            Err(JsonParseError::NotFound(key))
        }
    }
}
impl<T: FromJson> JsonRetrieve for T {
    fn parse(key: String, value: Option<&String>) -> Result<Self, JsonParseError> {
        Self::from_json(&JsonObject::from_string(value.ok_or(JsonParseError::NotFound(key))?))
    }
}