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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
//! Json file parser library
//!
//! # Installation
//! ```toml
//! ...
//! [dependencies]
//! rsjson = "0.4.0";
//! ```
//! or run
//! ```bash
//! cargo add rsjson
//! ```
//!
//! # Importation
//! ```rust
//! use rsjson;
//! ```
//!
//! # Code example
//! - read and parse a json file
//! ```rust
//! let json: Result<rsjson::Json, String> = rsjson::Json::fromFile("/path/to/file.json");
//! ```
//!
//! - read and parse a json structure from a string
//! - the string can be both "normal" and raw
//! ```rust
//! let json: Result<rsjson::Json, String> = rsjson::json!(
//!     r#"{
//!         "key" : "value",
//!         "second_key" : ["one", "two"]
//!     }"#
//! );
//! ```
//! - in both previous cases, remeber to handle the eventual error (e.g. using `match`) or to call `unwrap()`
//!
//!
//!
//! - create an empty json instance
//! ```rust
//! let json = rsjson::Json::new();
//! ```
//!
//! - add a node
//! ```rust
//! json.addNode(
//!     rsjson::Node::new(
//!         "nodeLabel",
//!         rsjson::NodeContent::Int(32)
//!     )
//! );
//! ```
//!
//! - edit a node's label
//! ```rust
//! json.editNode(
//!     "nodeLabel",
//!     "newNodeLabel"
//! );
//! ```
//!
//! - edit a node's content
//! ```rust
//! json.editContent(
//!     "nodeLabel",
//!     rsjson::NodeContent::Bool(true)
//! );
//! ```
//!
//! - remove a node
//! ```rust
//! json.removeNode(
//!     "nodeLabel"
//! );
//! ```

#![allow(non_snake_case, unused_assignments, dead_code)]

use std::{fs, path};
use std::ops::Add;

const DIGITS: [&str; 11] = [
    "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "."
];

#[derive(Debug, PartialEq)]
enum Token {
    String(String),
    Int(usize),
    Float(f32),
    OpenBrace,
    CloseBrace,
    OpenBracket,
    CloseBracket,
    Colon,
    Comma,
    Bool(bool),
    Null
}

impl Token {
    fn toString(&self) -> String {
        match self {
            Token::String(string) => string.clone(),
            _ => String::new()
        }
    }
}

struct Parser {
    tokens: Vec<Token>,
    index: usize,
    text: String ,
    len: usize
}

impl Parser {
    fn new(text: String) -> Parser {
        return Parser {
            tokens: Vec::<Token>::new(),
            index: 0_usize,
            len: (&text).len(),
            text: text
        }
    }

    fn get(&mut self) -> String {
        self.text[self.index..self.index + 1].to_string()
    }

    fn checkNotEnd(&self) -> bool {
        self.index != self.len
    }

    fn parse(&mut self) -> bool {
        self.skipNull();
        while self.checkNotEnd() {
            let current = self.get();
            if current == "\"" {
                self.index += 1;
                let mut value = String::new();

                while self.checkNotEnd() && self.get() != "\"" {
                    value += self.get().as_str();
                    self.index += 1;
                }

                if ! self.checkNotEnd() {
                    return true;
                }
                self.index += 1;

                self.tokens.push(Token::String(value));

            } else if self.get() == ":" {
                self.tokens.push(Token::Colon);
                self.index += 1;

            } else if self.get() == "," {
                self.tokens.push(Token::Comma);
                self.index += 1;

            } else if self.get() == "{" {
                self.tokens.push(Token::OpenBrace);
                self.index += 1;

            } else if self.get() == "}" {
                self.tokens.push(Token::CloseBrace);
                self.index += 1;

            } else if self.get() == "[" {
                self.tokens.push(Token::OpenBracket);
                self.index += 1;

            } else if self.get() == "]" {
                self.tokens.push(Token::CloseBracket);
                self.index += 1;

            } else if DIGITS.contains(&self.get().as_str()) {
                let mut value = String::new();

                while self.checkNotEnd() && DIGITS.contains(&self.get().as_str()) {
                    value += self.get().as_str();
                    self.index += 1;
                }

                if ! self.checkNotEnd() {
                    return true;
                }

                if value.contains(".") {
                    self.tokens.push(Token::Float(value.parse::<f32>().unwrap()))

                } else {
                    self.tokens.push(Token::Int(value.parse::<usize>().unwrap()))
                }

            } else if self.get() == "t" || self.get() == "f" || self.get() == "n" {
                if self.len - self.index - 4 > 0 && &self.text[self.index..self.index + 4] == "true" {
                    self.tokens.push(Token::Bool(true));
                    self.index += 4;

                } else if self.len - self.index - 4 > 0 && &self.text[self.index..self.index + 4] == "null" {
                    self.tokens.push(Token::Null);
                    self.index += 4;

                } else if self.len - self.index - 5 > 0 && &self.text[self.index..self.index + 5] == "false" {
                    self.tokens.push(Token::Bool(false));
                    self.index += 5;

                } else {
                    return true
                }
            }
            self.skipNull();
        }

        false
    }

    fn skipNull(&mut self) {
        let skip = [" ", "\t", "\n"];

        while self.index < self.len && skip.contains(&&self.text[self.index..self.index + 1]) {
            self.index += 1;
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum NodeContent {
    String(String),
    Int(usize),
    Float(f32),
    Bool(bool),
    List(Vec<NodeContent>),
    Json(Json),
    Null
}

impl NodeContent {
    pub fn toString(&self) -> Option<String> {
        match self {
            NodeContent::String(value) => Some(value.to_string()),
            _ => None
        }
    }

    pub fn toUsize(&self) -> Option<usize> {
        match self {
            NodeContent::Int(value) => Some(value.to_owned()),
            _ => None
        }
    }

    pub fn toBool(&self) -> Option<bool> {
        match self {
            NodeContent::Bool(value) => Some(value.to_owned()),
            _ => None
        }
    }

    pub fn toFloat(&self) -> Option<f32> {
        match self {
            NodeContent::Float(value) => Some(value.to_owned()),
            _ => None
        }
    }

    pub fn toJson(&self) -> Option<Json> {
        match self {
            NodeContent::Json(value) => Some(value.clone()),
            _ => None
        }
    }

    pub fn toList(&self) -> Option<Vec<NodeContent>> {
        match self {
            NodeContent::List(value) => Some(value.clone()),
            _ => None
        }
    }

    pub fn toNull(&self) -> Option<Node> {
        return None;
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Node {
    label: String,
    content: NodeContent
}

impl Node {
    pub fn new<T: ToString>(label: T, content: NodeContent) -> Node {
        Node {
            label: label.to_string(),
            content: content
        }
    }

    pub fn getLabel(&self) -> String {
        return self.label.clone();
    }

    pub fn getContent(&self) -> NodeContent {
        return self.content.clone();
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Json {
    nodes: Vec<Node>
}

impl Json {
    pub fn new() -> Json {
        return Json {
            nodes: Vec::<Node>::new()
        }
    }

    /// Reads the file at `filePath` and returns a Json struct corresponding to its content
    pub fn fromFile<T: ToString>(filePath: T) -> Result<Json, String> {
        match std::fs::read_to_string(filePath.to_string()) {
            Err(why) => Err(format!("Failed because: {why}")),
            Ok(content) => Json::fromString(content)
        }
    }


    fn fromString<T: ToString>(text: T) -> Result<Json, String> {
        let mut parser = Parser::new(text.to_string());
        let error = parser.parse();

        if error {
            return Err(String::from("Json format error"));
        }

        let tokens = parser.tokens;

        if tokens.get(0).unwrap() != &Token::OpenBrace {
            return Err(String::from("Json format error: missing opening curly bracket"));
        }

        let index = 1_usize;

        let (_, json, error) = Self::json(&tokens, index);
        if error {
            return Err(String::from("Json format error"));
        }

        return Ok(json.unwrap())
    }

    fn json(tokens: &Vec<Token>, startIndex: usize) -> (usize, Option<Json>, bool) {
        let mut index = startIndex;
        let mut nodes = Vec::<Node>::new();

        while index < tokens.len() {
            match tokens.get(index).unwrap() {
                Token::String(_) => {
                    let (newIndex, node, error) = Self::node(&tokens, index);

                    if error {
                        return (index, None, true)
                    }

                    index = newIndex;
                    if tokens.get(index).unwrap() != &Token::CloseBrace && tokens.get(index).unwrap() != &Token::Comma {
                        return (index, None, true)

                    } else if tokens.get(index).unwrap() == &Token::Comma {
                        index += 1;
                    }

                    nodes.push(node.unwrap());
                },
                Token::CloseBrace => {
                    break
                }
                _ => return (index, None, true)
            }
        }
        (index, Some(Json{nodes: nodes}), false)
    }

    fn list(tokens: &Vec<Token>, startIndex: usize) -> (usize, Option<NodeContent>, bool) {
        let mut index = startIndex;
        let mut content = Vec::<NodeContent>::new();

        while tokens.get(index).unwrap() != &Token::CloseBracket {
            match tokens.get(index).unwrap() {
                Token::String(string) => {
                    content.push(NodeContent::String(string.to_owned()));
                    index += 1;
                },

                Token::Int(int) => {
                    content.push(NodeContent::Int(int.to_owned()));
                    index += 1;
                },

                Token::Float(float) => {
                    content.push(NodeContent::Float(float.to_owned()));
                    index += 1;
                },

                Token::Null => {
                    content.push(NodeContent::Null);
                    index += 1;
                },

                Token::Bool(bool) => {
                    content.push(NodeContent::Bool(bool.to_owned()));
                    index += 1;
                },

                Token::OpenBrace => {
                    let (newIndex, json, error) = Self::json(tokens, index + 1);

                    if error {
                        return (index, None, true)
                    }

                    index = newIndex + 1;
                    content.push(NodeContent::Json(json.unwrap()));
                },

                Token::OpenBracket => {
                    let (newIndex, list, error) = Self::list(tokens, index);

                    if error {
                        return (index, None, true)
                    }

                    index = newIndex;
                    content.push(list.unwrap())
                },

                Token::Comma => {
                    index += 1;
                },

                _ => {
                    return (index, None, true)
                }


            }
        }
        if tokens.get(index-1).unwrap() == &Token::Comma {
            return (index, None, true);
        }

        (index, Some(NodeContent::List(content)), false)
    }

    fn node(tokens: &Vec<Token>, startIndex: usize) -> (usize, Option<Node>, bool) {
        let mut index = startIndex;
        let label = tokens.get(index).unwrap().toString();

        index += 1;
        if tokens.get(index).unwrap() != &Token::Colon {
            return (index, None, true)
        }
        index += 1;

        let mut content = NodeContent::Null;
        match tokens.get(index).unwrap() {
            Token::Null => {
                content = NodeContent::Null;
                index += 1;
            },

            Token::Int(int) => {
                content = NodeContent::Int(int.to_owned());
                index += 1;
            },

            Token::Float(float) => {
                content = NodeContent::Float(float.to_owned());
                index += 1;
            },

            Token::Bool(bool) => {
                content = NodeContent::Bool(bool.to_owned());
                index += 1;
            },

            Token::String(string) => {
                content = NodeContent::String(string.to_owned());
                index += 1;
            },

            Token::OpenBrace => {
                index += 1;
                let (newIndex, nodeContent, error) = Self::json(tokens, index);
                if error {
                    return (index, None, true)
                }
                index = newIndex + 1;
                content = NodeContent::Json(nodeContent.unwrap());
            },

            Token::OpenBracket => {
                index += 1;
                let (newIndex, list, error) = Self::list(tokens, index);

                if error {
                    return (index, None, true);
                }

                index = newIndex + 1;
                content = list.unwrap();
            }

            _ => {
                return (index, None, true)
            }
        }

        (index, Some(Node{label: label, content: content}), false)
    }

    /// Returns a vector containing all nodes in the Json object
    pub fn getAllNodes(&self) -> Vec<Node> {
        return self.nodes.clone();
    }

    /// Returns the content of the requested node
    pub fn get<T: ToString>(&self, label: T) -> Option<&NodeContent> {
        for node in &self.nodes {
            if node.label == label.to_string() {
                return Some(&node.content)
            }
        }

        return None;
    }

    /// Returns the requested node
    pub fn getNode<T: ToString>(&self, label: T) -> Option<&Node> {
        for node in &self.nodes {
            if node.label == label.to_string() {
                return Some(node);
            }
        }
        return None;
    }

    fn renderJson(json: &Json, indent: String) -> String {
        let mut content = String::from("{");

        for node in &json.nodes {
            let nodeContent = &node.content;

            if nodeContent.toString() != None {
                content = content.add(format!("\n{}\"{}\" : \"{}\",", indent, node.label, nodeContent.toString().unwrap()).as_str());

            } else if nodeContent.toUsize() != None {
                content = content.add(format!("\n{}\"{}\" : {},", indent, node.label, nodeContent.toUsize().unwrap()).as_str());

            } else if nodeContent.toFloat() != None {
                content = content.add(format!("\n{}\"{}\" : {},", indent, node.label, nodeContent.toFloat().unwrap()).as_str());

            } else if nodeContent.toBool() != None {
                content = content.add(format!("\n{}\"{}\" : {},", indent, node.label, nodeContent.toBool().unwrap()).as_str());

            } else if nodeContent.toUsize() != None {
                content = content.add(format!("\n{}\"{}\" : {},", indent, node.label, nodeContent.toUsize().unwrap()).as_str());
            } else if nodeContent.toList() != None {
                content = content.add(
                    format!(
                        "\n{}\"{}\" : {},",
                        indent,
                        node.label,
                        Json::renderList(&nodeContent.toList().unwrap()).as_str()
                    ).as_str()
                );
            } else if nodeContent.toJson() != None {
                let subContent = Json::renderJson(&node.content.toJson().unwrap(), indent.clone().add("\t").to_string());
                content = content.add(format!("\n{}\"{}\" : {}", indent, node.label, subContent).as_str());
                content = content[0..content.len()-1].to_string().add(&indent).add("},");

            } else {
                content = content.add(format!("\n{}\"{}\" : null,", indent, node.label).as_str());
            }
        }

        content = content[0..content.len()-1].to_string().add("\n").add("}");
        return content;
    }

    fn renderList(list: &Vec<NodeContent>, ) -> String {
        let mut content = String::from("[");

        for element in list {
            if element.toString() != None {
                content = content.add(format!("\"{}\", ", element.toString().unwrap()).as_str());

            } else if element.toUsize() != None {
                content = content.add(format!("{}, ", element.toUsize().unwrap()).as_str());

            } else if element.toFloat() != None {
                content = content.add(format!("{}, ", element.toFloat().unwrap()).as_str());

            } else if element.toBool() != None {
                content = content.add(format!("{}, ", element.toBool().unwrap()).as_str());

            } else if element.toUsize() != None {
                content = content.add(format!("{}, ", element.toUsize().unwrap()).as_str());

            } else if element.toJson() != None {
                let subContent = Json::renderJson(&element.toJson().unwrap(), String::from("\t"));

                content = content.add(format!("{}, ", subContent).as_str());

            } else {
                content = content.add("null, ");
            }
        }

        if content.len() > 2 {
            content = (&content[0..content.len()-2]).to_string().add("]");
        } else {
            content = content.add("]");
        }

        return content;
    }

    /// Exports the Json struct into a Json file and writes it into `fileName`
    pub fn writeToFile<T: ToString>(&self, fileName: T) -> bool {
        let content = Json::renderJson(self, "\t".to_string());

        return match fs::write(path::Path::new(&fileName.to_string()), content) {
            Err(_) => false,
            Ok(_) => true
        }
    }

    /// Adds a node to the Json struct
    pub fn addNode(&mut self, node: Node) {
        self.nodes.push(node);
    }

    /// Changes the label of a node, returns a bool representing the status of the change
    pub fn changeLabel<T: ToString>(&mut self, label: T, newLabel: T) -> bool {
        for node in &mut self.nodes {
            if node.label == label.to_string() {

                node.label = newLabel.to_string().clone();
                return true;
            }
        }

        return false;
    }

    /// Changes the content of a node, returns a bool representing the status of the change
    pub fn changeContent<T: ToString>(&mut self, label: T, content: NodeContent) -> bool {
        for node in &mut self.nodes {
            if node.label == label.to_string() {

                node.content = content;
                return true;
            }
        }

        return false;
    }

    /// Removes a node basing on its label
    pub fn removeNode<T: ToString>(&mut self, label: T) -> bool {
        let mut index: usize = 0;

        for node in &self.nodes {
            if node.label == label.to_string() {
                self.nodes.remove(index);

                return true;
            }
            index += 1;
        }
        return false;
    }
}

#[macro_export]
macro_rules! json {
    ( $string:expr ) => {
        Json::fromString($string)
    };
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test() {
        let mut j = json!(
            r#"{
                "a" : "b",
                "b" : "c"
            }"#
        );
        println!("{:?}", j);
        assert_eq!(0, 0);
    }
}