1
//! JSON value types for C API (data definitions only, no serde_json dependency)
2
//!
3
//! The actual parsing/serialization lives in `azul_layout::json` which adds
4
//! serde_json-based implementations on top of these types.
5

            
6
use alloc::{string::String, vec::Vec};
7
use core::fmt;
8

            
9
use azul_css::{
10
    impl_option, impl_option_inner, impl_result, impl_result_inner, impl_vec, impl_vec_clone,
11
    impl_vec_debug, impl_vec_mut, impl_vec_partialeq, AzString, OptionBool, OptionF64,
12
    OptionString,
13
};
14

            
15
// ============================================================================
16
// JSON Value Type
17
// ============================================================================
18

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

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

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

            
56
impl Default for JsonInternal {
57
31774
    fn default() -> Self {
58
31774
        Self {
59
31774
            string_value: AzString::from(String::new()),
60
31774
            number_value: 0.0,
61
31774
            bool_value: false,
62
31774
        }
63
31774
    }
64
}
65

            
66
/// Type of a JSON value
67
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68
#[repr(C)]
69
pub enum JsonType {
70
    /// JSON null
71
    Null,
72
    /// JSON boolean (true/false)
73
    Bool,
74
    /// JSON number (stored as f64)
75
    Number,
76
    /// JSON string
77
    String,
78
    /// JSON array
79
    Array,
80
    /// JSON object
81
    Object,
82
}
83

            
84
/// Error when parsing JSON
85
#[derive(Debug, Clone, PartialEq, Eq)]
86
#[repr(C)]
87
pub struct JsonParseError {
88
    /// Error message
89
    pub message: AzString,
90
    /// Line number (if available)
91
    pub line: u32,
92
    /// Column number (if available)
93
    pub column: u32,
94
}
95

            
96
impl fmt::Display for JsonParseError {
97
4
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98
4
        if self.line > 0 {
99
2
            write!(
100
2
                f,
101
2
                "{}:{}: {}",
102
                self.line,
103
                self.column,
104
2
                self.message.as_str()
105
            )
106
        } else {
107
2
            write!(f, "{}", self.message.as_str())
108
        }
109
4
    }
110
}
111

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

            
115
/// A key-value pair in a JSON object
116
#[derive(Debug, Clone, PartialEq)]
117
#[repr(C)]
118
pub struct JsonKeyValue {
119
    /// The key
120
    pub key: AzString,
121
    /// The value
122
    pub value: Json,
123
}
124

            
125
impl JsonKeyValue {
126
    /// Create a new key-value pair
127
    #[must_use]
128
9
    pub const fn create(key: AzString, value: Json) -> Self {
129
9
        Self { key, value }
130
9
    }
131
}
132

            
133
// ============================================================================
134
// FFI-safe collection types
135
// ============================================================================
136

            
137
/// Option type for JsonKeyValue
138
impl_option!(
139
    JsonKeyValue,
140
    OptionJsonKeyValue,
141
    copy = false,
142
    [Debug, Clone, PartialEq]
143
);
144

            
145
/// Vec of JsonKeyValue (FFI-safe)
146
impl_vec!(
147
    JsonKeyValue,
148
    JsonKeyValueVec,
149
    JsonKeyValueVecDestructor,
150
    JsonKeyValueVecDestructorType,
151
    JsonKeyValueVecSlice,
152
    OptionJsonKeyValue
153
);
154
impl_vec_clone!(JsonKeyValue, JsonKeyValueVec, JsonKeyValueVecDestructor);
155
impl_vec_debug!(JsonKeyValue, JsonKeyValueVec);
156

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

            
174
// FFI-safe JsonVec using impl_vec! macro
175
impl_vec!(
176
    Json,
177
    JsonVec,
178
    JsonVecDestructor,
179
    JsonVecDestructorType,
180
    JsonVecSlice,
181
    OptionJson
182
);
183
impl_vec_clone!(Json, JsonVec, JsonVecDestructor);
184
impl_vec_debug!(Json, JsonVec);
185
impl_vec_partialeq!(Json, JsonVec);
186
impl_vec_mut!(Json, JsonVec);
187

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

            
205
// FFI-safe Result type for JSON parsing
206
impl_result!(
207
    Json,
208
    JsonParseError,
209
    ResultJsonJsonParseError,
210
    copy = false,
211
    [Debug, Clone, PartialEq]
212
);
213

            
214
// FFI-safe Option types for JSON
215
impl_option!(Json, OptionJson, copy = false, [Clone, Debug, PartialEq]);
216
impl_option!(JsonVec, OptionJsonVec, copy = false, [Clone, Debug]);
217
impl_option!(
218
    JsonKeyValueVec,
219
    OptionJsonKeyValueVec,
220
    copy = false,
221
    [Clone, Debug]
222
);
223

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

            
232
// ============================================================================
233
// Helpers
234
// ============================================================================
235

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

            
251
// ============================================================================
252
// Non-serde methods on Json (pure data, no parsing)
253
// ============================================================================
254

            
255
impl Json {
256
    /// Create a null JSON value
257
    #[must_use]
258
48
    pub fn null() -> Self {
259
48
        Self {
260
48
            value_type: JsonType::Null,
261
48
            internal: JsonInternal::default(),
262
48
        }
263
48
    }
264

            
265
    /// Create a boolean JSON value
266
    #[must_use]
267
28
    pub fn bool(value: bool) -> Self {
268
28
        Self {
269
28
            value_type: JsonType::Bool,
270
28
            internal: JsonInternal {
271
28
                string_value: AzString::from(String::new()),
272
28
                number_value: 0.0,
273
28
                bool_value: value,
274
28
            },
275
28
        }
276
28
    }
277

            
278
    /// Create a number JSON value (floating-point)
279
    #[must_use]
280
85
    pub fn number(value: f64) -> Self {
281
85
        Self {
282
85
            value_type: JsonType::Number,
283
85
            internal: JsonInternal {
284
85
                string_value: AzString::from(String::new()),
285
85
                number_value: value,
286
85
                bool_value: false,
287
85
            },
288
85
        }
289
85
    }
290

            
291
    /// Create an integer JSON value.
292
    ///
293
    /// **Note:** the value is stored as `f64` internally, so `i64` values with
294
    /// magnitude greater than 2^53 will lose precision silently.
295
    #[allow(clippy::cast_precision_loss)] // bounded DPI/dimension/number conversion
296
    #[must_use]
297
31
    pub fn integer(value: i64) -> Self {
298
31
        Self {
299
31
            value_type: JsonType::Number,
300
31
            internal: JsonInternal {
301
31
                string_value: AzString::from(String::new()),
302
31
                number_value: value as f64,
303
31
                bool_value: false,
304
31
            },
305
31
        }
306
31
    }
307

            
308
    /// Create a string JSON value
309
39
    pub fn string(value: impl Into<String>) -> Self {
310
39
        Self {
311
39
            value_type: JsonType::String,
312
39
            internal: JsonInternal {
313
39
                string_value: AzString::from(value.into()),
314
39
                number_value: 0.0,
315
39
                bool_value: false,
316
39
            },
317
39
        }
318
39
    }
319

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

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

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

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

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

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

            
356
    /// Get as boolean (returns None if not a bool)
357
    #[must_use]
358
6
    pub fn as_bool(&self) -> OptionBool {
359
6
        if self.value_type == JsonType::Bool {
360
5
            OptionBool::Some(self.internal.bool_value)
361
        } else {
362
1
            OptionBool::None
363
        }
364
6
    }
365

            
366
    /// Get as number (returns None if not a number)
367
    #[must_use]
368
15
    pub fn as_number(&self) -> OptionF64 {
369
15
        if self.value_type == JsonType::Number {
370
12
            OptionF64::Some(self.internal.number_value)
371
        } else {
372
3
            OptionF64::None
373
        }
374
15
    }
375

            
376
    /// Get as integer (returns None if not a number or not an integer)
377
    #[must_use]
378
22
    pub fn as_i64(&self) -> OptionI64 {
379
22
        if self.value_type == JsonType::Number {
380
20
            f64_as_i64(self.internal.number_value).map_or(OptionI64::None, OptionI64::Some)
381
        } else {
382
2
            OptionI64::None
383
        }
384
22
    }
385

            
386
    /// Get as string (returns None if not a string)
387
    #[must_use]
388
14
    pub fn as_string(&self) -> OptionString {
389
14
        if self.value_type == JsonType::String {
390
12
            OptionString::Some(self.internal.string_value.clone())
391
        } else {
392
2
            OptionString::None
393
        }
394
14
    }
395

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

            
403
/// Note: the `Display` output is meant for human-readable / debug display.
404
/// String values are quoted but **not** JSON-escaped (no backslash escaping
405
/// of embedded quotes, newlines, etc.).  Use `to_json_string()` (requires
406
/// the `serde-json` feature) when valid JSON output is needed.
407
impl fmt::Display for Json {
408
21
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
409
21
        match self.value_type {
410
3
            JsonType::Null => write!(f, "null"),
411
2
            JsonType::Bool => write!(f, "{}", self.internal.bool_value),
412
            JsonType::Number => {
413
10
                let num = self.internal.number_value;
414
10
                if let Some(i) = f64_as_i64(num) {
415
3
                    write!(f, "{i}")
416
                } else {
417
7
                    write!(f, "{num}")
418
                }
419
            }
420
3
            JsonType::String => write!(f, "\"{}\"", self.internal.string_value.as_str()),
421
            JsonType::Array | JsonType::Object => {
422
3
                write!(f, "{}", self.internal.string_value.as_str())
423
            }
424
        }
425
21
    }
426
}
427

            
428
// ============================================================================
429
// serde_json-dependent methods (gated behind "serde-json" feature)
430
// ============================================================================
431

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

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

            
452
#[cfg(feature = "serde-json")]
453
impl Json {
454
    /// Parse JSON from a string.
455
    ///
456
    /// # Errors
457
    ///
458
    /// Returns [`JsonParseError`] (message plus line/column) if `s` is not
459
    /// well-formed JSON.
460
159
    pub fn parse(s: &str) -> Result<Self, JsonParseError> {
461
159
        let value: serde_json::Value = serde_json::from_str(s).map_err(|e| JsonParseError {
462
51
            message: AzString::from(alloc::format!("{e}")),
463
51
            line: u32::try_from(e.line()).unwrap_or(u32::MAX),
464
51
            column: u32::try_from(e.column()).unwrap_or(u32::MAX),
465
51
        })?;
466
108
        Ok(Self::from_serde_value(value))
467
159
    }
468

            
469
    /// Parse JSON from bytes (UTF-8).
470
    ///
471
    /// # Errors
472
    ///
473
    /// Returns [`JsonParseError`] (message plus line/column) if `bytes` is not
474
    /// well-formed UTF-8 JSON.
475
39
    pub fn parse_bytes(bytes: &[u8]) -> Result<Self, JsonParseError> {
476
1
        let value: serde_json::Value =
477
39
            serde_json::from_slice(bytes).map_err(|e| JsonParseError {
478
38
                message: AzString::from(alloc::format!("{e}")),
479
38
                line: u32::try_from(e.line()).unwrap_or(u32::MAX),
480
38
                column: u32::try_from(e.column()).unwrap_or(u32::MAX),
481
38
            })?;
482
1
        Ok(Self::from_serde_value(value))
483
39
    }
484

            
485
    /// Convert from `serde_json::Value`
486
    #[must_use]
487
155
    pub fn from_serde_value(value: serde_json::Value) -> Self {
488
155
        match value {
489
8
            serde_json::Value::Null => Self::null(),
490
8
            serde_json::Value::Bool(b) => Self::bool(b),
491
50
            serde_json::Value::Number(n) => Self::number(n.as_f64().unwrap_or(0.0)),
492
15
            serde_json::Value::String(s) => Self::string(s),
493
24
            serde_json::Value::Array(arr) => {
494
24
                let json_str =
495
24
                    serde_json::to_string(&serde_json::Value::Array(arr)).unwrap_or_default();
496
24
                Self {
497
24
                    value_type: JsonType::Array,
498
24
                    internal: JsonInternal {
499
24
                        string_value: AzString::from(json_str),
500
24
                        number_value: 0.0,
501
24
                        bool_value: false,
502
24
                    },
503
24
                }
504
            }
505
50
            serde_json::Value::Object(obj) => {
506
50
                let json_str =
507
50
                    serde_json::to_string(&serde_json::Value::Object(obj)).unwrap_or_default();
508
50
                Self {
509
50
                    value_type: JsonType::Object,
510
50
                    internal: JsonInternal {
511
50
                        string_value: AzString::from(json_str),
512
50
                        number_value: 0.0,
513
50
                        bool_value: false,
514
50
                    },
515
50
                }
516
            }
517
        }
518
155
    }
519

            
520
    /// Convert this Json to a `serde_json::Value`
521
    #[must_use]
522
28
    pub fn to_serde_value(&self) -> serde_json::Value {
523
28
        match self.value_type {
524
2
            JsonType::Null => serde_json::Value::Null,
525
1
            JsonType::Bool => serde_json::Value::Bool(self.internal.bool_value),
526
            JsonType::Number => {
527
10
                let num = self.internal.number_value;
528
10
                f64_as_i64(num).map_or_else(
529
6
                    || {
530
6
                        serde_json::Number::from_f64(num)
531
6
                            .map_or(serde_json::Value::Null, serde_json::Value::Number)
532
6
                    },
533
4
                    |i| serde_json::Value::Number(serde_json::Number::from(i)),
534
                )
535
            }
536
            JsonType::String => {
537
2
                serde_json::Value::String(self.internal.string_value.as_str().to_string())
538
            }
539
            JsonType::Array | JsonType::Object => {
540
13
                serde_json::from_str(self.internal.string_value.as_str())
541
13
                    .unwrap_or(serde_json::Value::Null)
542
            }
543
        }
544
28
    }
545

            
546
    /// Create a JSON array from a vector of JSON values
547
    // By-value is the C-ABI shape: the generated bindings hand ownership in.
548
    #[allow(clippy::needless_pass_by_value)]
549
    #[must_use]
550
2
    pub fn array(values: JsonVec) -> Self {
551
2
        let serde_array: Vec<serde_json::Value> =
552
2
            values.as_slice().iter().map(Self::to_serde_value).collect();
553
2
        let json_str = serde_json::to_string(&serde_json::Value::Array(serde_array))
554
2
            .unwrap_or_else(|_| "[]".to_string());
555
2
        Self {
556
2
            value_type: JsonType::Array,
557
2
            internal: JsonInternal {
558
2
                string_value: AzString::from(json_str),
559
2
                number_value: 0.0,
560
2
                bool_value: false,
561
2
            },
562
2
        }
563
2
    }
564

            
565
    /// Create a JSON object from key-value pairs
566
    // By-value is the C-ABI shape: the generated bindings hand ownership in.
567
    #[allow(clippy::needless_pass_by_value)]
568
    #[must_use]
569
3
    pub fn object(entries: JsonKeyValueVec) -> Self {
570
3
        let mut map = serde_json::Map::new();
571
4
        for kv in entries.as_slice() {
572
4
            map.insert(kv.key.as_str().to_string(), kv.value.to_serde_value());
573
4
        }
574
3
        let json_str = serde_json::to_string(&serde_json::Value::Object(map))
575
3
            .unwrap_or_else(|_| "{}".to_string());
576
3
        Self {
577
3
            value_type: JsonType::Object,
578
3
            internal: JsonInternal {
579
3
                string_value: AzString::from(json_str),
580
3
                number_value: 0.0,
581
3
                bool_value: false,
582
3
            },
583
3
        }
584
3
    }
585

            
586
    /// Get the number of elements (for arrays) or keys (for objects)
587
    #[must_use]
588
22
    pub fn len(&self) -> usize {
589
22
        match self.value_type {
590
            JsonType::Array => {
591
7
                if let Ok(serde_json::Value::Array(arr)) =
592
9
                    serde_json::from_str(self.internal.string_value.as_str())
593
                {
594
7
                    arr.len()
595
                } else {
596
2
                    0
597
                }
598
            }
599
            JsonType::Object => {
600
4
                if let Ok(serde_json::Value::Object(obj)) =
601
5
                    serde_json::from_str(self.internal.string_value.as_str())
602
                {
603
4
                    obj.len()
604
                } else {
605
1
                    0
606
                }
607
            }
608
8
            _ => 0,
609
        }
610
22
    }
611

            
612
    /// Check if empty (for arrays/objects)
613
    #[must_use]
614
7
    pub fn is_empty(&self) -> bool {
615
7
        self.len() == 0
616
7
    }
617

            
618
    /// Get array element by index
619
    #[must_use]
620
10
    pub fn get_index(&self, index: usize) -> Option<Self> {
621
10
        if self.value_type != JsonType::Array {
622
2
            return None;
623
8
        }
624
7
        let value: serde_json::Value =
625
8
            serde_json::from_str(self.internal.string_value.as_str()).ok()?;
626
7
        if let serde_json::Value::Array(arr) = value {
627
6
            arr.get(index).map(|v| Self::from_serde_value(v.clone()))
628
        } else {
629
1
            None
630
        }
631
10
    }
632

            
633
    /// Get object value by key
634
    #[must_use]
635
15
    pub fn get_key(&self, key: &str) -> Option<Self> {
636
15
        if self.value_type != JsonType::Object {
637
2
            return None;
638
13
        }
639
12
        let value: serde_json::Value =
640
13
            serde_json::from_str(self.internal.string_value.as_str()).ok()?;
641
12
        if let serde_json::Value::Object(obj) = value {
642
12
            obj.get(key).map(|v| Self::from_serde_value(v.clone()))
643
        } else {
644
            None
645
        }
646
15
    }
647

            
648
    /// Get all keys of an object
649
    #[must_use]
650
5
    pub fn keys(&self) -> Vec<AzString> {
651
5
        if self.value_type != JsonType::Object {
652
2
            return Vec::new();
653
3
        }
654
2
        let value: serde_json::Value =
655
3
            match serde_json::from_str(self.internal.string_value.as_str()) {
656
2
                Ok(v) => v,
657
1
                Err(_) => return Vec::new(),
658
            };
659
2
        if let serde_json::Value::Object(obj) = value {
660
3
            obj.keys().map(|k| AzString::from(k.clone())).collect()
661
        } else {
662
            Vec::new()
663
        }
664
5
    }
665

            
666
    /// Convert array to Vec<Json>
667
6
    pub fn to_array(&self) -> Option<JsonVec> {
668
6
        if self.value_type != JsonType::Array {
669
2
            return None;
670
4
        }
671
3
        let value: serde_json::Value =
672
4
            serde_json::from_str(self.internal.string_value.as_str()).ok()?;
673
3
        if let serde_json::Value::Array(arr) = value {
674
2
            Some(arr.into_iter().map(Self::from_serde_value).collect())
675
        } else {
676
1
            None
677
        }
678
6
    }
679

            
680
    /// Convert object to Vec<JsonKeyValue>
681
    #[must_use]
682
5
    pub fn to_object(&self) -> Option<JsonKeyValueVec> {
683
5
        if self.value_type != JsonType::Object {
684
1
            return None;
685
4
        }
686
3
        let value: serde_json::Value =
687
4
            serde_json::from_str(self.internal.string_value.as_str()).ok()?;
688
3
        if let serde_json::Value::Object(obj) = value {
689
            Some(
690
2
                obj.into_iter()
691
2
                    .map(|(k, v)| JsonKeyValue {
692
1
                        key: AzString::from(k),
693
1
                        value: Self::from_serde_value(v),
694
1
                    })
695
2
                    .collect(),
696
            )
697
        } else {
698
1
            None
699
        }
700
5
    }
701

            
702
    /// Serialize to JSON string (returns `AzString`)
703
    #[must_use]
704
63
    pub fn to_json_string(&self) -> AzString {
705
63
        match self.value_type {
706
5
            JsonType::Null => AzString::from(alloc::string::String::from("null")),
707
8
            JsonType::Bool => AzString::from(if self.internal.bool_value {
708
3
                alloc::string::String::from("true")
709
            } else {
710
5
                alloc::string::String::from("false")
711
            }),
712
            JsonType::Number => {
713
29
                let num = self.internal.number_value;
714
29
                f64_as_i64(num).map_or_else(
715
18
                    || AzString::from(alloc::format!("{num}")),
716
11
                    |i| AzString::from(alloc::format!("{i}")),
717
                )
718
            }
719
            JsonType::String => {
720
9
                let escaped =
721
9
                    serde_json::to_string(self.internal.string_value.as_str()).unwrap_or_default();
722
9
                AzString::from(escaped)
723
            }
724
12
            JsonType::Array | JsonType::Object => self.internal.string_value.clone(),
725
        }
726
63
    }
727

            
728
    /// Serialize to pretty-printed JSON string
729
    #[must_use]
730
8
    pub fn to_string_pretty(&self) -> AzString {
731
8
        match self.value_type {
732
            JsonType::Null | JsonType::Bool | JsonType::Number | JsonType::String => {
733
5
                self.to_json_string()
734
            }
735
            JsonType::Array | JsonType::Object => {
736
3
                serde_json::from_str::<serde_json::Value>(self.internal.string_value.as_str())
737
3
                    .map_or_else(
738
2
                        |_| self.internal.string_value.clone(),
739
1
                        |value| {
740
1
                            AzString::from(serde_json::to_string_pretty(&value).unwrap_or_default())
741
1
                        },
742
                    )
743
            }
744
        }
745
8
    }
746

            
747
    /// Access a nested value using a JSON Pointer (RFC 6901).
748
    #[must_use]
749
27
    pub fn jq(&self, path: &str) -> Self {
750
27
        match self.value_type {
751
            JsonType::Null | JsonType::Bool | JsonType::Number | JsonType::String => {
752
16
                if path.is_empty() {
753
4
                    self.clone()
754
                } else {
755
12
                    Self::null()
756
                }
757
            }
758
            JsonType::Array | JsonType::Object => {
759
10
                let value: serde_json::Value =
760
11
                    match serde_json::from_str(self.internal.string_value.as_str()) {
761
10
                        Ok(v) => v,
762
1
                        Err(_) => return Self::null(),
763
                    };
764
10
                value
765
10
                    .pointer(path)
766
10
                    .map_or_else(Self::null, |v| Self::from_serde_value(v.clone()))
767
            }
768
        }
769
27
    }
770

            
771
    /// Access nested values using a JSON Pointer with wildcard support.
772
    #[must_use]
773
22
    pub fn jq_all(&self, path: &str) -> JsonVec {
774
22
        let result = match self.value_type {
775
            JsonType::Null | JsonType::Bool | JsonType::Number | JsonType::String => {
776
8
                if path.is_empty() {
777
4
                    vec![self.clone()]
778
                } else {
779
4
                    vec![]
780
                }
781
            }
782
            JsonType::Array | JsonType::Object => {
783
13
                let value: serde_json::Value =
784
14
                    match serde_json::from_str(self.internal.string_value.as_str()) {
785
13
                        Ok(v) => v,
786
1
                        Err(_) => return JsonVec::from_vec(vec![]),
787
                    };
788
13
                Self::jq_all_recursive(&value, path)
789
            }
790
        };
791
21
        JsonVec::from_vec(result)
792
22
    }
793

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

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

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

            
820
        // Walk non-wildcard components iteratively.
821
956
        let mut value = value;
822
956
        let mut path = path;
823
        loop {
824
1071
            if path.is_empty() {
825
15
                return vec![Self::from_serde_value(value.clone())];
826
1056
            }
827
1056
            if !path.starts_with('/') {
828
1
                return vec![];
829
1055
            }
830
1055
            let rest = &path[1..];
831
1055
            let (component, remaining) = rest
832
1055
                .find('/')
833
1055
                .map_or((rest, ""), |idx| (&rest[..idx], &rest[idx..]));
834

            
835
1055
            if component == "*" {
836
936
                let mut results = Vec::new();
837
936
                match value {
838
917
                    serde_json::Value::Array(arr) => {
839
1839
                        for item in arr {
840
922
                            results.extend(Self::jq_all_recursive_depth(
841
922
                                item,
842
922
                                remaining,
843
922
                                depth + 1,
844
922
                            ));
845
922
                        }
846
                    }
847
10
                    serde_json::Value::Object(obj) => {
848
28
                        for (_key, val) in obj {
849
18
                            results.extend(Self::jq_all_recursive_depth(val, remaining, depth + 1));
850
18
                        }
851
                    }
852
9
                    _ => {}
853
                }
854
936
                return results;
855
119
            }
856

            
857
            // Single-child descent: advance the cursor instead of recursing.
858
119
            let next = match value {
859
2
                serde_json::Value::Array(arr) => {
860
2
                    component.parse::<usize>().ok().and_then(|idx| arr.get(idx))
861
                }
862
116
                serde_json::Value::Object(obj) => obj.get(component),
863
1
                _ => None,
864
            };
865
119
            match next {
866
115
                Some(v) => {
867
115
                    value = v;
868
115
                    path = remaining;
869
115
                }
870
4
                None => return vec![],
871
            }
872
        }
873
960
    }
874
}
875

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