jlf 0.2.2

CLI for converting JSON logs to human-readable format
Documentation
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
use core::fmt;
use std::iter::Peekable;

use owo_colors::{
    colors::{Blue, BrightWhite, Green, White},
    OwoColorize, Style,
};

pub fn parse_json(input: &str) -> Result<Json<'_>, ParseError> {
    let mut json = Json::default();
    json.parse_replace(input)?;
    Ok(json)
}

#[derive(Clone, Default)]
pub enum Json<'a> {
    // first arg is the key value pairs, second is a list of keys used as
    // cache for parse_replace
    Object(JsonObject<'a>),
    Array(Vec<Json<'a>>),
    String(&'a str),
    Value(&'a str),
    #[default]
    Null,
    NullPrevObject(JsonObject<'a>),
    NullPrevArray(Vec<Json<'a>>),
}

impl<'a> Json<'a> {
    pub fn parse_replace(&mut self, input: &'a str) -> Result<(), ParseError> {
        let mut chars = input.trim().char_indices().peekable();
        if let Some((_, c)) = chars.peek() {
            if *c != '{' && *c != '[' {
                return Err(ParseError {
                    message: "JSON must be an object or array",
                    value: input.to_owned(),
                    index: 0,
                });
            }
        }

        self.parse_value_in_place(&mut chars, input)?;
        Ok(())
    }

    pub fn get(&self, key: &str) -> &Json {
        match self {
            Json::Object(obj) => obj.get(key),
            _ => &Json::Null,
        }
    }

    pub fn get_mut(&'a mut self, key: &str) -> Option<&'a mut Json<'a>> {
        match self {
            Json::Object(obj) => obj.get_mut(key),
            _ => None,
        }
    }

    pub fn get_i(&self, index: usize) -> &Json {
        match self {
            Json::Array(arr) => arr.get(index).unwrap_or(&Json::Null),
            _ => &Json::Null,
        }
    }

    pub fn get_i_mut(&'a mut self, index: usize) -> Option<&'a mut Json<'a>> {
        match self {
            Json::Array(arr) => arr.get_mut(index),
            _ => None,
        }
    }

    pub fn remove(&mut self, key: &str) -> Option<Json<'a>> {
        match self {
            Json::Object(obj) => obj.remove(key),
            _ => None,
        }
    }

    pub fn remove_i(&mut self, index: usize) -> Option<Json<'a>> {
        match self {
            Json::Array(arr) => arr.get_mut(index).map(|e| e.replace(Json::Null)),
            _ => None,
        }
    }

    /// Looks up a value by a JSON Pointer.
    ///
    /// JSON Pointer defines a string syntax for identifying a specific value
    /// within a JavaScript Object Notation (JSON) document.
    ///
    /// A Pointer is a Unicode string with the reference tokens separated by
    /// `/`. Inside tokens `/` is replaced by `~1` and `~` is replaced by
    /// `~0`. The addressed value is returned and if there is no such value
    /// `None` is returned.
    ///
    /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
    pub fn pointer(&self, pointer: &str) -> Option<&Json> {
        if pointer.is_empty() {
            return Some(self);
        }
        if !pointer.starts_with('/') {
            return None;
        }
        pointer
            .split('/')
            .skip(1)
            .map(|x| x.replace("~1", "/").replace("~0", "~"))
            .try_fold(self, |target, token| match target {
                Json::Object(map) => map.try_get(&token),
                Json::Array(list) => parse_index(&token).and_then(|x| list.get(x)),
                _ => None,
            })
    }

    /// Looks up a value by a JSON Pointer and returns a mutable reference to
    /// that value.
    ///
    /// JSON Pointer defines a string syntax for identifying a specific value
    /// within a JavaScript Object Notation (JSON) document.
    ///
    /// A Pointer is a Unicode string with the reference tokens separated by
    /// `/`. Inside tokens `/` is replaced by `~1` and `~` is replaced by
    /// `~0`. The addressed value is returned and if there is no such value
    /// `None` is returned.
    ///
    /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901).
    pub fn pointer_mut(&'a mut self, pointer: &str) -> Option<&'a mut Json<'a>> {
        if pointer.is_empty() {
            return Some(self);
        }
        if !pointer.starts_with('/') {
            return None;
        }

        pointer
            .split('/')
            .skip(1)
            .map(|x| x.replace("~1", "/").replace("~0", "~"))
            .try_fold(self, |target, token| match target {
                Json::Object(map) => map.get_mut(&token),
                Json::Array(list) => parse_index(&token).and_then(move |x| list.get_mut(x)),
                _ => None,
            })
    }

    pub fn is_null(&self) -> bool {
        matches!(
            self,
            Json::Null | Json::NullPrevObject(_) | Json::NullPrevArray(_)
        )
    }

    pub fn is_empty(&self) -> bool {
        match self {
            Json::Object(obj) => obj.is_empty(),
            Json::Array(arr) => arr.is_empty() || arr.iter().all(Json::is_null),
            Json::String(s) => s.is_empty(),
            Json::Value(_) => false,
            Json::Null | Json::NullPrevObject(_) | Json::NullPrevArray(_) => true,
        }
    }

    pub fn is_object(&self) -> bool { matches!(self, Json::Object(_)) }

    pub fn is_array(&self) -> bool { matches!(self, Json::Array(_)) }

    pub fn is_str(&self) -> bool { matches!(self, Json::String(_)) }

    pub fn is_value(&self) -> bool { matches!(self, Json::Value(_)) }

    pub fn as_object(&self) -> Option<&JsonObject<'a>> {
        match self {
            Json::Object(obj) => Some(obj),
            _ => None,
        }
    }

    pub fn as_object_mut(&mut self) -> Option<&mut JsonObject<'a>> {
        match self {
            Json::Object(obj) => Some(obj),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&Vec<Json<'a>>> {
        match self {
            Json::Array(arr) => Some(arr),
            _ => None,
        }
    }

    pub fn as_array_mut(&mut self) -> Option<&mut Vec<Json<'a>>> {
        match self {
            Json::Array(arr) => Some(arr),
            _ => None,
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            Json::String(s) => Some(s),
            _ => None,
        }
    }

    pub fn as_value(&self) -> Option<&str> {
        match self {
            Json::Value(v) => Some(v),
            _ => None,
        }
    }

    // Replace self with a new value and return the previous value
    pub fn replace(&mut self, value: Json<'a>) -> Json<'a> { std::mem::replace(self, value) }

    fn parse_value_in_place<I>(
        &mut self,
        chars: &mut Peekable<I>,
        input: &'a str,
    ) -> Result<(), ParseError>
    where
        I: Iterator<Item = (usize, char)>,
    {
        match chars.peek().map(|&(_, c)| c) {
            Some('{') => {
                if let Json::Object(obj) = self {
                    obj.parse_object_in_place(chars, input)?;
                } else {
                    let this = self.replace(Json::Null);
                    if let Json::NullPrevObject(mut obj) = this {
                        obj.parse_object_in_place(chars, input)?;
                        *self = Json::Object(obj);
                    } else {
                        let mut obj = JsonObject(Vec::new());
                        obj.parse_object_in_place(chars, input)?;
                        *self = Json::Object(obj);
                    }
                }
            }
            Some('[') => {
                if let Json::Array(arr) = self {
                    parse_array_in_place(arr, chars, input)?;
                } else {
                    let this = self.replace(Json::Null);
                    if let Json::NullPrevArray(mut arr) = this {
                        parse_array_in_place(&mut arr, chars, input)?;
                        *self = Json::Array(arr);
                    } else {
                        let mut arr = Vec::new();
                        parse_array_in_place(&mut arr, chars, input)?;
                        *self = Json::Array(arr);
                    }
                }
            }
            Some('"') => {
                *self = parse_string(chars, input)?;
            }
            Some('n') => {
                parse_null(chars, input)?;
                self.replace_with_null();
            }
            Some(']') => {
                return Err(ParseError {
                    message: "Unexpected closing bracket",
                    value: input.to_owned(),
                    index: chars
                        .peek()
                        .map(|&(i, _)| i)
                        .unwrap_or_else(|| input.len() - 1),
                })
            }
            Some('}') => {
                return Err(ParseError {
                    message: "Unexpected closing brace",
                    value: input.to_owned(),
                    index: chars
                        .peek()
                        .map(|&(i, _)| i)
                        .unwrap_or_else(|| input.len() - 1),
                })
            }
            Some(_) => {
                *self = parse_raw_value(chars, input)?;
            }
            None => {
                return Err(ParseError {
                    message: "Unexpected end of input",
                    value: input.to_owned(),
                    index: input.len(),
                })
            }
        }

        Ok(())
    }

    fn replace_with_null(&mut self) {
        let prev = self.replace(Json::Null);

        if let Json::Object(obj) = prev {
            *self = Json::NullPrevObject(obj);
        } else if let Json::Array(arr) = prev {
            *self = Json::NullPrevArray(arr);
        } else if matches!(prev, Json::NullPrevObject(_)) || matches!(prev, Json::NullPrevArray(_))
        {
            *self = prev;
        }
    }
}

#[derive(Clone, Default)]
pub struct JsonObject<'a>(pub Vec<(&'a str, Json<'a>)>);

impl<'a> JsonObject<'a> {
    pub fn get(&self, key: &str) -> &Json { self.try_get(key).unwrap_or(&Json::Null) }

    pub fn get_mut(&'a mut self, key: &str) -> Option<&'a mut Json<'a>> {
        self.0.iter_mut().find(|(k, _)| k == &key).map(|(_, v)| v)
    }

    pub fn try_get(&self, key: &str) -> Option<&Json> {
        self.0.iter().find(|(k, _)| k == &key).map(|(_, v)| v)
    }

    pub fn insert(&mut self, key: &'a str, value: Json<'a>) {
        if let Some((_, v)) = self.0.iter_mut().find(|(k, _)| k == &key) {
            *v = value;
        } else {
            self.0.push((key, value));
        }
    }

    pub fn remove(&mut self, key: &str) -> Option<Json<'a>> {
        if let Some((_, val)) = self.0.iter_mut().find(|(k, _)| k == &key) {
            Some(val.replace(Json::Null))
        } else {
            None
        }
    }

    pub fn is_empty(&self) -> bool {
        if self.0.is_empty() {
            return true;
        }

        self.0.iter().all(|(_, v)| v.is_null())
    }

    pub fn iter(&self) -> std::slice::Iter<(&'a str, Json<'a>)> { self.0.iter() }

    pub fn iter_mut(&mut self) -> std::slice::IterMut<(&'a str, Json<'a>)> { self.0.iter_mut() }

    pub fn parse_insert(&mut self, key: &'a str, input: &'a str) -> Result<(), ParseError> {
        if let Some((old_key, value)) = self.0.iter_mut().find(|(k, _)| k == &key) {
            *old_key = key;
            value.parse_replace(input)?;
        } else {
            let mut new_value = Json::Null;
            new_value.parse_replace(input)?;

            self.0.push((key, new_value));
        }

        Ok(())
    }

    fn parse_object_in_place<I>(
        &mut self,
        chars: &mut Peekable<I>,
        input: &'a str,
    ) -> Result<(), ParseError>
    where
        I: Iterator<Item = (usize, char)>,
    {
        // Consume the opening '{'
        let Some((_, '{')) = chars.next() else {
            return Err(ParseError {
                message: "Object doesn't have a starting brace",
                value: input.to_owned(),
                index: 0,
            });
        };

        skip_whitespace(chars);
        if let Some((_, '}')) = chars.peek() {
            chars.next(); // Consume the closing '}'

            // Set values to Json::Null for keys not found in the input
            for (_, value) in self.iter_mut() {
                value.replace_with_null();
            }

            return Ok(());
        }

        let mut count = 0;

        loop {
            let Ok(Json::String(key)) = parse_string(chars, input) else {
                return Err(ParseError {
                    message: "Unexpected char in object",
                    value: input.to_owned(),
                    index: chars
                        .peek()
                        .map(|&(i, _)| i - 1)
                        .unwrap_or_else(|| input.len() - 1),
                });
            };

            skip_whitespace(chars);
            if chars.next().map(|(_, c)| c) != Some(':') {
                return Err(ParseError {
                    message: "Expected colon ':' after key in object",
                    value: input.to_owned(),
                    // Use the index right after the key, which should be the
                    // current position
                    index: chars
                        .peek()
                        .map(|&(i, _)| i - 1)
                        .unwrap_or_else(|| input.len() - 1),
                });
            }

            skip_whitespace(chars);
            if let Some((old_key, value)) = self.0.get_mut(count) {
                *old_key = key;
                value.parse_value_in_place(chars, input)?;
            } else {
                let mut new_value = Json::Null;
                new_value.parse_value_in_place(chars, input)?;
                self.0.push((key, new_value));
            }

            count += 1;

            skip_whitespace(chars);
            match chars.peek().map(|&(_, c)| c) {
                Some(',') => {
                    chars.next();
                    skip_whitespace(chars);
                } // Consume and continue
                Some('}') => {
                    chars.next(); // Consume the closing '}'

                    for (_, value) in self.iter_mut().skip(count) {
                        value.replace_with_null();
                    }

                    return Ok(());
                }
                _ => {
                    return Err(ParseError {
                        message: "Expected comma or closing brace '}' in \
                                  object",
                        value: input.to_owned(),
                        index: chars.peek().map(|&(i, _)| i).unwrap_or_else(|| input.len()),
                    })
                }
            }
        }
    }
}

fn parse_array_in_place<'a, I>(
    arr: &mut Vec<Json<'a>>,
    chars: &mut Peekable<I>,
    input: &'a str,
) -> Result<(), ParseError>
where
    I: Iterator<Item = (usize, char)>,
{
    chars.next(); // Consume the opening '['

    skip_whitespace(chars);
    if let Some((_, ']')) = chars.peek() {
        chars.next(); // Consume the closing ']'

        for value in arr.iter_mut() {
            value.replace_with_null();
        }

        return Ok(());
    }

    let mut count = 0;

    loop {
        if count < arr.len() {
            arr[count].parse_value_in_place(chars, input)?;
        } else {
            let mut new_element = Json::Null;
            new_element.parse_value_in_place(chars, input)?;
            arr.push(new_element);
        }
        count += 1;

        skip_whitespace(chars);
        match chars.peek().map(|&(_, c)| c) {
            Some(',') => {
                chars.next();
                skip_whitespace(chars);
            } // Consume and continue
            Some(']') => {
                chars.next(); // Consume the closing ']'

                for value in arr.iter_mut().skip(count) {
                    value.replace_with_null();
                }

                return Ok(());
            } // Handle in the next loop iteration
            _ => {
                return Err(ParseError {
                    message: "Expected comma or closing bracket ']' in array",
                    value: input.to_owned(),
                    // Use the current position as the error index
                    index: chars
                        .peek()
                        .map(|&(i, _)| i)
                        .unwrap_or_else(|| input.len() - 1),
                });
            }
        }
    }
}

fn parse_string<'a, I>(chars: &mut Peekable<I>, input: &'a str) -> Result<Json<'a>, ParseError>
where
    I: Iterator<Item = (usize, char)>,
{
    // Consume the opening quote
    let Some((start_index, '"')) = chars.next() else {
        return Err(ParseError {
            message: "Expected opening quote for string",
            value: input.to_owned(),
            index: input.len(),
        });
    };

    while let Some((i, c)) = chars.next() {
        match c {
            '"' => return Ok(Json::String(&input[start_index + 1..i])),
            '\\' => {
                chars.next(); // Skip the character following the escape
            }
            _ => {}
        }
    }

    Err(ParseError {
        message: "Closing quote not found for string started",
        value: input.to_owned(),
        index: start_index,
    })
}

fn parse_null<'a, I>(chars: &mut Peekable<I>, input: &'a str) -> Result<Json<'a>, ParseError>
where
    I: Iterator<Item = (usize, char)>,
{
    let start_index = chars.peek().map(|&(i, _)| i).unwrap_or_else(|| input.len());
    if chars.next().map(|(_, c)| c) == Some('n')
        && chars.next().map(|(_, c)| c) == Some('u')
        && chars.next().map(|(_, c)| c) == Some('l')
        && chars.next().map(|(_, c)| c) == Some('l')
    {
        Ok(Json::Null)
    } else {
        Err(ParseError {
            message: "Invalid null value",
            value: input.to_owned(),
            // Point to the start of 'n' that led to expecting "null"
            index: start_index,
        })
    }
}

fn parse_raw_value<'a, I>(chars: &mut Peekable<I>, input: &'a str) -> Result<Json<'a>, ParseError>
where
    I: Iterator<Item = (usize, char)>,
{
    let start_index = chars.peek().map(|&(i, _)| i).unwrap_or_else(|| input.len());
    while let Some(&(i, c)) = chars.peek() {
        if c == ',' || c == ']' || c == '}' {
            return Ok(Json::Value(&input[start_index..i]));
        }
        chars.next();
    }

    Ok(Json::Value(&input[start_index..]))
}

// skip whitespaces and return the number of characters skipped
fn skip_whitespace<I>(chars: &mut Peekable<I>)
where
    I: Iterator<Item = (usize, char)>,
{
    while let Some(&(_, c)) = chars.peek() {
        if c.is_whitespace() {
            chars.next();
        } else {
            break;
        }
    }
}

impl Json<'_> {
    pub fn indented(&self, indent: usize) -> StyledJson {
        StyledJson {
            json: self,
            indent,
            styles: None,
        }
    }

    pub fn styled(&self, styles: MarkupStyles) -> StyledJson {
        StyledJson {
            json: self,
            indent: 0,
            styles: Some(styles),
        }
    }
}

pub struct StyledJson<'a> {
    json: &'a Json<'a>,
    indent: usize,
    styles: Option<MarkupStyles>,
}

impl StyledJson<'_> {
    pub fn indented(self, indent: usize) -> Self { Self { indent, ..self } }

    pub fn styled(self, styles: MarkupStyles) -> Self {
        Self {
            styles: Some(styles),
            ..self
        }
    }
}

impl fmt::Display for StyledJson<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        self.json.fmt_compact(f, &self.styles)
    }
}

impl fmt::Debug for StyledJson<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        self.json.fmt_pretty(f, self.indent, &self.styles)
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MarkupStyles {
    pub key: Style,
    pub value: Style,
    pub str: Style,
    pub syntax: Style,
}

impl Default for MarkupStyles {
    fn default() -> Self {
        Self {
            key: Style::new().fg::<Blue>(),
            value: Style::new().fg::<BrightWhite>(),
            str: Style::new().fg::<Green>(),
            syntax: Style::new().fg::<White>(),
        }
    }
}

impl fmt::Display for Json<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        self.fmt_compact(f, &None)
    }
}

impl fmt::Debug for Json<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        self.fmt_pretty(f, 0, &None)
    }
}

impl Json<'_> {
    fn fmt_compact(
        &self,
        f: &mut fmt::Formatter<'_>,
        styles: &Option<MarkupStyles>,
    ) -> Result<(), fmt::Error> {
        match self {
            Json::Object(obj) => {
                if obj.is_empty() {
                    return write_syntax(f, "{}", styles);
                }

                let mut non_nulls = obj.iter().filter(|(_, v)| !v.is_null());
                let Some((key, value)) = non_nulls.next() else {
                    return write_syntax(f, "{}", styles);
                };

                write_syntax(f, "{", styles)?;
                write_key(f, key, styles)?;
                write_syntax(f, ":", styles)?;
                value.fmt_compact(f, styles)?;

                for (key, value) in non_nulls {
                    write_syntax(f, ",", styles)?;
                    write_key(f, key, styles)?;
                    write_syntax(f, ":", styles)?;
                    value.fmt_compact(f, styles)?;
                }

                write_syntax(f, "}", styles)
            }
            Json::Array(arr) => {
                if arr.is_empty() {
                    return write_syntax(f, "[]", styles);
                }

                let mut non_nulls = arr.iter().filter(|v| !v.is_null());
                let Some(value) = non_nulls.next() else {
                    return write_syntax(f, "[]", styles);
                };

                write_syntax(f, "[", styles)?;
                value.fmt_compact(f, styles)?;

                for value in non_nulls {
                    write_syntax(f, ",", styles)?;
                    value.fmt_compact(f, styles)?;
                }
                write_syntax(f, "]", styles)
            }
            Json::String(v) => write_str(f, v, styles),
            Json::Value(v) => write_value(f, v, styles),
            Json::Null | Json::NullPrevObject(_) | Json::NullPrevArray(_) => {
                write_value(f, "null", styles)
            }
        }
    }

    fn fmt_pretty(
        &self,
        f: &mut fmt::Formatter<'_>,
        indent: usize,
        styles: &Option<MarkupStyles>,
    ) -> Result<(), fmt::Error> {
        match self {
            Json::Object(obj) => {
                if obj.is_empty() {
                    return write_syntax(f, "{}", styles);
                }

                let mut non_nulls = obj.iter().filter(|(_, v)| !v.is_null());
                let Some((key, value)) = non_nulls.next() else {
                    return write_syntax(f, "{}", styles);
                };

                write_syntax(f, "{", styles)?;
                write!(f, "\n{:indent$}", "", indent = (indent + 2))?;
                write_key(f, key, styles)?;
                write_syntax(f, ":", styles)?;
                write!(f, " ")?;
                value.fmt_pretty(f, indent + 2, styles)?;

                for (key, value) in non_nulls {
                    write_syntax(f, ",", styles)?;
                    write!(f, "\n{:indent$}", "", indent = (indent + 2))?;
                    write_key(f, key, styles)?;
                    write_syntax(f, ":", styles)?;
                    write!(f, " ")?;
                    value.fmt_pretty(f, indent + 2, styles)?;
                }

                write!(f, "\n{:indent$}", "", indent = indent)?;
                write_syntax(f, "}", styles)
            }
            Json::Array(arr) => {
                if arr.is_empty() {
                    return write_syntax(f, "[]", styles);
                }

                let mut non_nulls = arr.iter().filter(|v| !v.is_null());
                let Some(value) = non_nulls.next() else {
                    return write_syntax(f, "[]", styles);
                };

                write_syntax(f, "[", styles)?;
                write!(f, "\n{:indent$}", "", indent = (indent + 2))?;
                value.fmt_pretty(f, indent + 2, styles)?;

                for value in non_nulls {
                    write_syntax(f, ",", styles)?;
                    write!(f, "\n{:indent$}", "", indent = (indent + 2))?;
                    value.fmt_pretty(f, indent + 2, styles)?;
                }
                write!(f, "\n{:indent$}", "", indent = indent)?;
                write_syntax(f, "]", styles)
            }
            Json::String(v) => write_str(f, v, styles),
            Json::Value(v) => write_value(f, v, styles),
            Json::Null | Json::NullPrevObject(_) | Json::NullPrevArray(_) => {
                write_value(f, "null", styles)
            }
        }
    }
}

fn write_key(
    f: &mut fmt::Formatter<'_>,
    key: &str,
    styles: &Option<MarkupStyles>,
) -> Result<(), fmt::Error> {
    if let Some(style) = styles {
        write!(f, "{}", format_args!("\"{key}\"").style(style.key))
    } else {
        write!(f, "\"{}\"", key)
    }
}

fn write_value(
    f: &mut fmt::Formatter<'_>,
    value: &str,
    styles: &Option<MarkupStyles>,
) -> Result<(), fmt::Error> {
    if let Some(style) = styles {
        write!(f, "{}", value.style(style.value))
    } else {
        write!(f, "{}", value)
    }
}

fn write_str(
    f: &mut fmt::Formatter<'_>,
    str: &str,
    styles: &Option<MarkupStyles>,
) -> Result<(), fmt::Error> {
    if let Some(style) = styles {
        write!(f, "{}", format_args!("\"{str}\"").style(style.str))
    } else {
        write!(f, "\"{}\"", str)
    }
}

fn write_syntax(
    f: &mut fmt::Formatter<'_>,
    syntax: &str,
    styles: &Option<MarkupStyles>,
) -> Result<(), fmt::Error> {
    if let Some(style) = styles {
        write!(f, "{}", syntax.style(style.syntax))
    } else {
        write!(f, "{}", syntax)
    }
}

fn parse_index(s: &str) -> Option<usize> {
    if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) {
        return None;
    }
    s.parse().ok()
}

pub struct ParseError {
    pub message: &'static str,
    pub value: String,
    pub index: usize,
}

impl std::fmt::Display for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        // Create a snippet from the input, showing up to 10 characters before
        // and after the error index
        let start = self.index.saturating_sub(15);
        let end = (self.index + 10).min(self.value.len());
        let snippet = &self.value[start..end];

        write!(f, "{} at index {}: '{}'", self.message, self.index, snippet)
    }
}

impl std::fmt::Debug for ParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let snippet_length = 20;
        let start = self.index.saturating_sub(snippet_length);
        let end = (self.index + snippet_length).min(self.value.len());
        let snippet = &self.value[start..end];

        let caret_position = self.index.saturating_sub(start) + 1;

        write!(
            f,
            "{} at index {}:\n`{}`\n{:>width$}",
            self.message,
            self.index,
            snippet,
            "^",                        // Caret pointing to the error location
            width = caret_position + 1, // Correct alignment for the caret
        )
    }
}
impl std::error::Error for ParseError {}

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

    #[test]
    fn basic() {
        let test_cases = vec![
            r#"{"key": "value"}"#,
            r#"{"escaped": "This is a \"test\""}"#,
            r#"{"nested": {"array": [1, "two", null], "emptyObj": {}, "bool": true}}"#,
            r#"["mixed", 123, {"obj": "inside array"}]"#,
            r#"{}"#,
            r#"[]"#,
        ];

        for case in test_cases {
            match parse_json(case) {
                Ok(parsed) => println!("Parsed JSON: {:#?}", parsed),
                Err(e) => println!("Failed to parse JSON: {}", e),
            }
        }

        let arr = parse_json(r#"["mixed", 123, {"obj": "inside array"}]"#).unwrap();
        println!("Array: {:#?}", arr);
        assert_eq!(arr.get_i(2).get("obj").as_value(), Some("\"inside array\""));
    }

    #[test]
    fn invalid() {
        let test_cases = vec![
            (
                r#"{"key": "value"         "#,
                "Missing Closing Brace for an Object",
            ),
            (
                r#"{"key": "value         }"#,
                "Missing Closing Quote for a String",
            ),
            (r#"{"key"     ,     "value"}"#, "Missing Colon in an Object"),
            (
                r#"{"key1": "value1", "key2": "value2"       ,          }"#,
                "Extra Comma in an Object",
            ),
            (r#"{key: "value"}"#, "Unquoted Key"),
            (
                r#"{"array": [1, 2, "missing bracket"        ,    }        "#,
                "Unclosed Array",
            ),
        ];

        for (json_str, description) in test_cases {
            println!("Testing case: {}", description);
            match parse_json(json_str) {
                Ok(_) => println!("No error detected, but expected an error."),
                Err(e) => {
                    println!("Error (Display): {}", e);
                    println!("Error (Debug):\n{:?}", e);
                }
            }
            println!("---------------------------------------\n");
        }
    }
}