azul-core 0.0.16

Common datatypes used for the Azul document object model, shared across all azul-* crates
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
//! JSON value types for C API (data definitions only, no serde_json dependency)
//!
//! The actual parsing/serialization lives in `azul_layout::json` which adds
//! serde_json-based implementations on top of these types.

use alloc::string::String;
use alloc::vec::Vec;
use azul_css::{
    impl_option, impl_option_inner, impl_result, impl_result_inner, impl_vec, impl_vec_clone,
    impl_vec_debug, impl_vec_mut, impl_vec_partialeq, AzString, OptionBool, OptionF64,
    OptionString,
};
use core::fmt;

// ============================================================================
// JSON Value Type
// ============================================================================

/// A generic JSON value that can hold any JSON type
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct Json {
    /// The type of this JSON value
    pub value_type: JsonType,
    /// Internal storage - interpretation depends on `value_type`
    /// For objects/arrays, this contains serialized data
    pub internal: JsonInternal,
}

/// Internal storage for JSON values.
///
/// This is a C-FFI-compatible tagged-union-via-struct: all fields always exist,
/// but only the field(s) corresponding to `JsonType` in the parent `Json` are
/// meaningful.  For compound types (`Array`, `Object`) the serialized JSON is
/// stored in `string_value` and re-parsed on each access — this trades repeated
/// parsing cost for a flat, FFI-safe layout with no interior pointers.
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct JsonInternal {
    /// For strings and serialized objects/arrays
    pub string_value: AzString,
    /// For numbers
    pub number_value: f64,
    /// For booleans
    pub bool_value: bool,
}

/// `Json::null()`. A default that is JSON null, rather than an empty string
/// masquerading as a value.
impl Default for Json {
    fn default() -> Self {
        Self::null()
    }
}

impl Default for JsonInternal {
    fn default() -> Self {
        Self {
            string_value: AzString::from(String::new()),
            number_value: 0.0,
            bool_value: false,
        }
    }
}

/// Type of a JSON value
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub enum JsonType {
    /// JSON null
    Null,
    /// JSON boolean (true/false)
    Bool,
    /// JSON number (stored as f64)
    Number,
    /// JSON string
    String,
    /// JSON array
    Array,
    /// JSON object
    Object,
}

/// Error when parsing JSON
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct JsonParseError {
    /// Error message
    pub message: AzString,
    /// Line number (if available)
    pub line: u32,
    /// Column number (if available)
    pub column: u32,
}

impl fmt::Display for JsonParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.line > 0 {
            write!(
                f,
                "{}:{}: {}",
                self.line,
                self.column,
                self.message.as_str()
            )
        } else {
            write!(f, "{}", self.message.as_str())
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for JsonParseError {}

/// A key-value pair in a JSON object
#[derive(Debug, Clone, PartialEq)]
#[repr(C)]
pub struct JsonKeyValue {
    /// The key
    pub key: AzString,
    /// The value
    pub value: Json,
}

impl JsonKeyValue {
    /// Create a new key-value pair
    #[must_use]
    pub const fn create(key: AzString, value: Json) -> Self {
        Self { key, value }
    }
}

// ============================================================================
// FFI-safe collection types
// ============================================================================

/// Option type for JsonKeyValue
impl_option!(
    JsonKeyValue,
    OptionJsonKeyValue,
    copy = false,
    [Debug, Clone, PartialEq]
);

/// Vec of JsonKeyValue (FFI-safe)
impl_vec!(
    JsonKeyValue,
    JsonKeyValueVec,
    JsonKeyValueVecDestructor,
    JsonKeyValueVecDestructorType,
    JsonKeyValueVecSlice,
    OptionJsonKeyValue
);
impl_vec_clone!(JsonKeyValue, JsonKeyValueVec, JsonKeyValueVecDestructor);
impl_vec_debug!(JsonKeyValue, JsonKeyValueVec);

impl JsonKeyValueVec {
    /// Creates a new, heap-allocated `JsonKeyValueVec` by copying elements from a C array
    #[inline]
    #[allow(clippy::not_unsafe_ptr_arg_deref)]
    // SAFETY/FFI: `*const T` is the C-ABI signature; the fn null-checks then derefs under the documented caller contract (C guarantees a valid ptr/len). Marking it `unsafe fn` would force unsafe blocks into the generated dll bindings.
    #[must_use]
    pub fn copy_from_array(ptr: *const JsonKeyValue, len: usize) -> Self {
        if ptr.is_null() || len == 0 {
            return Self::new();
        }
        let slice = unsafe { core::slice::from_raw_parts(ptr, len) };
        Self::from_vec(slice.to_vec())
    }
}

// FFI-safe JsonVec using impl_vec! macro
impl_vec!(
    Json,
    JsonVec,
    JsonVecDestructor,
    JsonVecDestructorType,
    JsonVecSlice,
    OptionJson
);
impl_vec_clone!(Json, JsonVec, JsonVecDestructor);
impl_vec_debug!(Json, JsonVec);
impl_vec_partialeq!(Json, JsonVec);
impl_vec_mut!(Json, JsonVec);

impl JsonVec {
    /// Creates a new, heap-allocated `JsonVec` by copying elements from a C array
    #[inline]
    #[allow(clippy::not_unsafe_ptr_arg_deref)]
    // SAFETY/FFI: `*const T` is the C-ABI signature; the fn null-checks then derefs under the documented caller contract (C guarantees a valid ptr/len). Marking it `unsafe fn` would force unsafe blocks into the generated dll bindings.
    #[must_use]
    pub fn copy_from_array(ptr: *const Json, len: usize) -> Self {
        if ptr.is_null() || len == 0 {
            return Self::new();
        }
        let slice = unsafe { core::slice::from_raw_parts(ptr, len) };
        Self::from_vec(slice.to_vec())
    }
}

// FFI-safe Result type for JSON parsing
impl_result!(
    Json,
    JsonParseError,
    ResultJsonJsonParseError,
    copy = false,
    [Debug, Clone, PartialEq]
);

// FFI-safe Option types for JSON
impl_option!(Json, OptionJson, copy = false, [Clone, Debug, PartialEq]);
impl_option!(JsonVec, OptionJsonVec, copy = false, [Clone, Debug]);
impl_option!(
    JsonKeyValueVec,
    OptionJsonKeyValueVec,
    copy = false,
    [Clone, Debug]
);

// FFI-safe Option types for JSON value extraction
// Note: OptionBool and OptionF64 are already exported from azul_css
impl_option!(
    i64,
    OptionI64,
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash]
);

// ============================================================================
// Helpers
// ============================================================================

/// Try to losslessly convert an `f64` to `i64`.
///
/// Returns `Some` only when `n` is an integer that fits in `i64` without
/// overflow.  The upper bound uses `< 2^63` (not `<= i64::MAX as f64`)
/// because `i64::MAX` cannot be represented exactly in `f64` — the cast
/// rounds up to `2^63`, which would cause overflow on `n as i64`.
#[allow(clippy::cast_possible_truncation)] // bounded DPI/dimension/number conversion
fn f64_as_i64(n: f64) -> Option<i64> {
    if n.fract() == 0.0 && n >= -(2_f64.powi(63)) && n < 2_f64.powi(63) {
        Some(n as i64)
    } else {
        None
    }
}

// ============================================================================
// Non-serde methods on Json (pure data, no parsing)
// ============================================================================

impl Json {
    /// Create a null JSON value
    #[must_use]
    pub fn null() -> Self {
        Self {
            value_type: JsonType::Null,
            internal: JsonInternal::default(),
        }
    }

    /// Create a boolean JSON value
    #[must_use]
    pub fn bool(value: bool) -> Self {
        Self {
            value_type: JsonType::Bool,
            internal: JsonInternal {
                string_value: AzString::from(String::new()),
                number_value: 0.0,
                bool_value: value,
            },
        }
    }

    /// Create a number JSON value (floating-point)
    #[must_use]
    pub fn number(value: f64) -> Self {
        Self {
            value_type: JsonType::Number,
            internal: JsonInternal {
                string_value: AzString::from(String::new()),
                number_value: value,
                bool_value: false,
            },
        }
    }

    /// Create an integer JSON value.
    ///
    /// **Note:** the value is stored as `f64` internally, so `i64` values with
    /// magnitude greater than 2^53 will lose precision silently.
    #[allow(clippy::cast_precision_loss)] // bounded DPI/dimension/number conversion
    #[must_use]
    pub fn integer(value: i64) -> Self {
        Self {
            value_type: JsonType::Number,
            internal: JsonInternal {
                string_value: AzString::from(String::new()),
                number_value: value as f64,
                bool_value: false,
            },
        }
    }

    /// Create a string JSON value
    pub fn string(value: impl Into<String>) -> Self {
        Self {
            value_type: JsonType::String,
            internal: JsonInternal {
                string_value: AzString::from(value.into()),
                number_value: 0.0,
                bool_value: false,
            },
        }
    }

    /// Check if this is null
    #[must_use]
    pub fn is_null(&self) -> bool {
        self.value_type == JsonType::Null
    }

    /// Check if this is a boolean
    #[must_use]
    pub fn is_bool(&self) -> bool {
        self.value_type == JsonType::Bool
    }

    /// Check if this is a number
    #[must_use]
    pub fn is_number(&self) -> bool {
        self.value_type == JsonType::Number
    }

    /// Check if this is a string
    #[must_use]
    pub fn is_string(&self) -> bool {
        self.value_type == JsonType::String
    }

    /// Check if this is an array
    #[must_use]
    pub fn is_array(&self) -> bool {
        self.value_type == JsonType::Array
    }

    /// Check if this is an object
    #[must_use]
    pub fn is_object(&self) -> bool {
        self.value_type == JsonType::Object
    }

    /// Get as boolean (returns None if not a bool)
    #[must_use]
    pub fn as_bool(&self) -> OptionBool {
        if self.value_type == JsonType::Bool {
            OptionBool::Some(self.internal.bool_value)
        } else {
            OptionBool::None
        }
    }

    /// Get as number (returns None if not a number)
    #[must_use]
    pub fn as_number(&self) -> OptionF64 {
        if self.value_type == JsonType::Number {
            OptionF64::Some(self.internal.number_value)
        } else {
            OptionF64::None
        }
    }

    /// Get as integer (returns None if not a number or not an integer)
    #[must_use]
    pub fn as_i64(&self) -> OptionI64 {
        if self.value_type == JsonType::Number {
            f64_as_i64(self.internal.number_value).map_or(OptionI64::None, OptionI64::Some)
        } else {
            OptionI64::None
        }
    }

    /// Get as string (returns None if not a string)
    #[must_use]
    pub fn as_string(&self) -> OptionString {
        if self.value_type == JsonType::String {
            OptionString::Some(self.internal.string_value.clone())
        } else {
            OptionString::None
        }
    }

    /// Get the raw internal string value (for arrays/objects this is the serialized JSON)
    #[must_use]
    pub fn raw_string(&self) -> &str {
        self.internal.string_value.as_str()
    }
}

/// Note: the `Display` output is meant for human-readable / debug display.
/// String values are quoted but **not** JSON-escaped (no backslash escaping
/// of embedded quotes, newlines, etc.).  Use `to_json_string()` (requires
/// the `serde-json` feature) when valid JSON output is needed.
impl fmt::Display for Json {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.value_type {
            JsonType::Null => write!(f, "null"),
            JsonType::Bool => write!(f, "{}", self.internal.bool_value),
            JsonType::Number => {
                let num = self.internal.number_value;
                if let Some(i) = f64_as_i64(num) {
                    write!(f, "{i}")
                } else {
                    write!(f, "{num}")
                }
            }
            JsonType::String => write!(f, "\"{}\"", self.internal.string_value.as_str()),
            JsonType::Array | JsonType::Object => {
                write!(f, "{}", self.internal.string_value.as_str())
            }
        }
    }
}

// ============================================================================
// serde_json-dependent methods (gated behind "serde-json" feature)
// ============================================================================

#[cfg(feature = "serde-json")]
impl serde::Serialize for Json {
    /// Serialize as the JSON value this represents, not as its repr(C) fields.
    ///
    /// Without this, a struct holding a `Json` field cannot derive
    /// `Serialize` at all — and the obvious workaround, storing the payload
    /// as a `String` of JSON, produces escaped JSON-inside-JSON that every
    /// consumer has to parse twice and nothing validates.
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        self.to_serde_value().serialize(s)
    }
}

#[cfg(feature = "serde-json")]
impl<'de> serde::Deserialize<'de> for Json {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        Ok(Self::from_serde_value(serde_json::Value::deserialize(d)?))
    }
}

#[cfg(feature = "serde-json")]
impl Json {
    /// Parse JSON from a string.
    ///
    /// # Errors
    ///
    /// Returns [`JsonParseError`] (message plus line/column) if `s` is not
    /// well-formed JSON.
    pub fn parse(s: &str) -> Result<Self, JsonParseError> {
        let value: serde_json::Value = serde_json::from_str(s).map_err(|e| JsonParseError {
            message: AzString::from(alloc::format!("{e}")),
            line: u32::try_from(e.line()).unwrap_or(u32::MAX),
            column: u32::try_from(e.column()).unwrap_or(u32::MAX),
        })?;
        Ok(Self::from_serde_value(value))
    }

    /// Parse JSON from bytes (UTF-8).
    ///
    /// # Errors
    ///
    /// Returns [`JsonParseError`] (message plus line/column) if `bytes` is not
    /// well-formed UTF-8 JSON.
    pub fn parse_bytes(bytes: &[u8]) -> Result<Self, JsonParseError> {
        let value: serde_json::Value =
            serde_json::from_slice(bytes).map_err(|e| JsonParseError {
                message: AzString::from(alloc::format!("{e}")),
                line: u32::try_from(e.line()).unwrap_or(u32::MAX),
                column: u32::try_from(e.column()).unwrap_or(u32::MAX),
            })?;
        Ok(Self::from_serde_value(value))
    }

    /// Convert from `serde_json::Value`
    #[must_use]
    pub fn from_serde_value(value: serde_json::Value) -> Self {
        match value {
            serde_json::Value::Null => Self::null(),
            serde_json::Value::Bool(b) => Self::bool(b),
            serde_json::Value::Number(n) => Self::number(n.as_f64().unwrap_or(0.0)),
            serde_json::Value::String(s) => Self::string(s),
            serde_json::Value::Array(arr) => {
                let json_str =
                    serde_json::to_string(&serde_json::Value::Array(arr)).unwrap_or_default();
                Self {
                    value_type: JsonType::Array,
                    internal: JsonInternal {
                        string_value: AzString::from(json_str),
                        number_value: 0.0,
                        bool_value: false,
                    },
                }
            }
            serde_json::Value::Object(obj) => {
                let json_str =
                    serde_json::to_string(&serde_json::Value::Object(obj)).unwrap_or_default();
                Self {
                    value_type: JsonType::Object,
                    internal: JsonInternal {
                        string_value: AzString::from(json_str),
                        number_value: 0.0,
                        bool_value: false,
                    },
                }
            }
        }
    }

    /// Convert this Json to a `serde_json::Value`
    #[must_use]
    pub fn to_serde_value(&self) -> serde_json::Value {
        match self.value_type {
            JsonType::Null => serde_json::Value::Null,
            JsonType::Bool => serde_json::Value::Bool(self.internal.bool_value),
            JsonType::Number => {
                let num = self.internal.number_value;
                f64_as_i64(num).map_or_else(
                    || {
                        serde_json::Number::from_f64(num)
                            .map_or(serde_json::Value::Null, serde_json::Value::Number)
                    },
                    |i| serde_json::Value::Number(serde_json::Number::from(i)),
                )
            }
            JsonType::String => {
                serde_json::Value::String(self.internal.string_value.as_str().to_string())
            }
            JsonType::Array | JsonType::Object => {
                serde_json::from_str(self.internal.string_value.as_str())
                    .unwrap_or(serde_json::Value::Null)
            }
        }
    }

    /// Create a JSON array from a vector of JSON values
    // By-value is the C-ABI shape: the generated bindings hand ownership in.
    #[allow(clippy::needless_pass_by_value)]
    #[must_use]
    pub fn array(values: JsonVec) -> Self {
        let serde_array: Vec<serde_json::Value> =
            values.as_slice().iter().map(Self::to_serde_value).collect();
        let json_str = serde_json::to_string(&serde_json::Value::Array(serde_array))
            .unwrap_or_else(|_| "[]".to_string());
        Self {
            value_type: JsonType::Array,
            internal: JsonInternal {
                string_value: AzString::from(json_str),
                number_value: 0.0,
                bool_value: false,
            },
        }
    }

    /// Create a JSON object from key-value pairs
    // By-value is the C-ABI shape: the generated bindings hand ownership in.
    #[allow(clippy::needless_pass_by_value)]
    #[must_use]
    pub fn object(entries: JsonKeyValueVec) -> Self {
        let mut map = serde_json::Map::new();
        for kv in entries.as_slice() {
            map.insert(kv.key.as_str().to_string(), kv.value.to_serde_value());
        }
        let json_str = serde_json::to_string(&serde_json::Value::Object(map))
            .unwrap_or_else(|_| "{}".to_string());
        Self {
            value_type: JsonType::Object,
            internal: JsonInternal {
                string_value: AzString::from(json_str),
                number_value: 0.0,
                bool_value: false,
            },
        }
    }

    /// Get the number of elements (for arrays) or keys (for objects)
    #[must_use]
    pub fn len(&self) -> usize {
        match self.value_type {
            JsonType::Array => {
                if let Ok(serde_json::Value::Array(arr)) =
                    serde_json::from_str(self.internal.string_value.as_str())
                {
                    arr.len()
                } else {
                    0
                }
            }
            JsonType::Object => {
                if let Ok(serde_json::Value::Object(obj)) =
                    serde_json::from_str(self.internal.string_value.as_str())
                {
                    obj.len()
                } else {
                    0
                }
            }
            _ => 0,
        }
    }

    /// Check if empty (for arrays/objects)
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get array element by index
    #[must_use]
    pub fn get_index(&self, index: usize) -> Option<Self> {
        if self.value_type != JsonType::Array {
            return None;
        }
        let value: serde_json::Value =
            serde_json::from_str(self.internal.string_value.as_str()).ok()?;
        if let serde_json::Value::Array(arr) = value {
            arr.get(index).map(|v| Self::from_serde_value(v.clone()))
        } else {
            None
        }
    }

    /// Get object value by key
    #[must_use]
    pub fn get_key(&self, key: &str) -> Option<Self> {
        if self.value_type != JsonType::Object {
            return None;
        }
        let value: serde_json::Value =
            serde_json::from_str(self.internal.string_value.as_str()).ok()?;
        if let serde_json::Value::Object(obj) = value {
            obj.get(key).map(|v| Self::from_serde_value(v.clone()))
        } else {
            None
        }
    }

    /// Get all keys of an object
    #[must_use]
    pub fn keys(&self) -> Vec<AzString> {
        if self.value_type != JsonType::Object {
            return Vec::new();
        }
        let value: serde_json::Value =
            match serde_json::from_str(self.internal.string_value.as_str()) {
                Ok(v) => v,
                Err(_) => return Vec::new(),
            };
        if let serde_json::Value::Object(obj) = value {
            obj.keys().map(|k| AzString::from(k.clone())).collect()
        } else {
            Vec::new()
        }
    }

    /// Convert array to Vec<Json>
    pub fn to_array(&self) -> Option<JsonVec> {
        if self.value_type != JsonType::Array {
            return None;
        }
        let value: serde_json::Value =
            serde_json::from_str(self.internal.string_value.as_str()).ok()?;
        if let serde_json::Value::Array(arr) = value {
            Some(arr.into_iter().map(Self::from_serde_value).collect())
        } else {
            None
        }
    }

    /// Convert object to Vec<JsonKeyValue>
    #[must_use]
    pub fn to_object(&self) -> Option<JsonKeyValueVec> {
        if self.value_type != JsonType::Object {
            return None;
        }
        let value: serde_json::Value =
            serde_json::from_str(self.internal.string_value.as_str()).ok()?;
        if let serde_json::Value::Object(obj) = value {
            Some(
                obj.into_iter()
                    .map(|(k, v)| JsonKeyValue {
                        key: AzString::from(k),
                        value: Self::from_serde_value(v),
                    })
                    .collect(),
            )
        } else {
            None
        }
    }

    /// Serialize to JSON string (returns `AzString`)
    #[must_use]
    pub fn to_json_string(&self) -> AzString {
        match self.value_type {
            JsonType::Null => AzString::from(alloc::string::String::from("null")),
            JsonType::Bool => AzString::from(if self.internal.bool_value {
                alloc::string::String::from("true")
            } else {
                alloc::string::String::from("false")
            }),
            JsonType::Number => {
                let num = self.internal.number_value;
                f64_as_i64(num).map_or_else(
                    || AzString::from(alloc::format!("{num}")),
                    |i| AzString::from(alloc::format!("{i}")),
                )
            }
            JsonType::String => {
                let escaped =
                    serde_json::to_string(self.internal.string_value.as_str()).unwrap_or_default();
                AzString::from(escaped)
            }
            JsonType::Array | JsonType::Object => self.internal.string_value.clone(),
        }
    }

    /// Serialize to pretty-printed JSON string
    #[must_use]
    pub fn to_string_pretty(&self) -> AzString {
        match self.value_type {
            JsonType::Null | JsonType::Bool | JsonType::Number | JsonType::String => {
                self.to_json_string()
            }
            JsonType::Array | JsonType::Object => {
                serde_json::from_str::<serde_json::Value>(self.internal.string_value.as_str())
                    .map_or_else(
                        |_| self.internal.string_value.clone(),
                        |value| {
                            AzString::from(serde_json::to_string_pretty(&value).unwrap_or_default())
                        },
                    )
            }
        }
    }

    /// Access a nested value using a JSON Pointer (RFC 6901).
    #[must_use]
    pub fn jq(&self, path: &str) -> Self {
        match self.value_type {
            JsonType::Null | JsonType::Bool | JsonType::Number | JsonType::String => {
                if path.is_empty() {
                    self.clone()
                } else {
                    Self::null()
                }
            }
            JsonType::Array | JsonType::Object => {
                let value: serde_json::Value =
                    match serde_json::from_str(self.internal.string_value.as_str()) {
                        Ok(v) => v,
                        Err(_) => return Self::null(),
                    };
                value
                    .pointer(path)
                    .map_or_else(Self::null, |v| Self::from_serde_value(v.clone()))
            }
        }
    }

    /// Access nested values using a JSON Pointer with wildcard support.
    #[must_use]
    pub fn jq_all(&self, path: &str) -> JsonVec {
        let result = match self.value_type {
            JsonType::Null | JsonType::Bool | JsonType::Number | JsonType::String => {
                if path.is_empty() {
                    vec![self.clone()]
                } else {
                    vec![]
                }
            }
            JsonType::Array | JsonType::Object => {
                let value: serde_json::Value =
                    match serde_json::from_str(self.internal.string_value.as_str()) {
                        Ok(v) => v,
                        Err(_) => return JsonVec::from_vec(vec![]),
                    };
                Self::jq_all_recursive(&value, path)
            }
        };
        JsonVec::from_vec(result)
    }

    /// Maximum JSON-Pointer component depth for [`jq_all`](Self::jq_all).
    ///
    /// AUDIT 2026-07-08: `jq_all_recursive` recursed once per pointer component,
    /// so an attacker-supplied pointer with tens of thousands of `/` segments
    /// (e.g. `"/a".repeat(100_000)`) overflowed the stack. The single-child
    /// descent is now iterative (unbounded, allocation-free); only the wildcard
    /// (`*`) fan-out still recurses, and that recursion is capped here. 512 is far
    /// deeper than any real document nesting while staying well inside the stack.
    const JQ_MAX_WILDCARD_DEPTH: usize = 512;

    /// Recursive helper for `jq_all` that handles wildcards.
    ///
    /// Non-wildcard components are walked in a loop so a long linear pointer can
    /// never overflow the stack; only `*` fan-out recurses, bounded by
    /// [`JQ_MAX_WILDCARD_DEPTH`](Self::JQ_MAX_WILDCARD_DEPTH).
    fn jq_all_recursive(value: &serde_json::Value, path: &str) -> Vec<Self> {
        Self::jq_all_recursive_depth(value, path, 0)
    }

    fn jq_all_recursive_depth(value: &serde_json::Value, path: &str, depth: usize) -> Vec<Self> {
        // Guard the wildcard recursion; exceeding the cap yields no match rather
        // than crashing.
        if depth > Self::JQ_MAX_WILDCARD_DEPTH {
            return vec![];
        }

        // Walk non-wildcard components iteratively.
        let mut value = value;
        let mut path = path;
        loop {
            if path.is_empty() {
                return vec![Self::from_serde_value(value.clone())];
            }
            if !path.starts_with('/') {
                return vec![];
            }
            let rest = &path[1..];
            let (component, remaining) = rest
                .find('/')
                .map_or((rest, ""), |idx| (&rest[..idx], &rest[idx..]));

            if component == "*" {
                let mut results = Vec::new();
                match value {
                    serde_json::Value::Array(arr) => {
                        for item in arr {
                            results.extend(Self::jq_all_recursive_depth(
                                item,
                                remaining,
                                depth + 1,
                            ));
                        }
                    }
                    serde_json::Value::Object(obj) => {
                        for (_key, val) in obj {
                            results.extend(Self::jq_all_recursive_depth(val, remaining, depth + 1));
                        }
                    }
                    _ => {}
                }
                return results;
            }

            // Single-child descent: advance the cursor instead of recursing.
            let next = match value {
                serde_json::Value::Array(arr) => {
                    component.parse::<usize>().ok().and_then(|idx| arr.get(idx))
                }
                serde_json::Value::Object(obj) => obj.get(component),
                _ => None,
            };
            match next {
                Some(v) => {
                    value = v;
                    path = remaining;
                }
                None => return vec![],
            }
        }
    }
}

#[cfg(test)]
#[path = "json_test.rs"]
mod json_test;