1
#[allow(unused_imports)]
2
pub use super::*;
3
#[cfg(test)]
4
mod jq_recursion_tests {
5
    use super::*;
6

            
7
    /// AUDIT 2026-07-08: a pointer with a very large number of components used to
8
    /// overflow the stack via per-component recursion. Linear (non-wildcard)
9
    /// descent is now iterative, so an over-long pointer against a shallow
10
    /// document returns empty promptly with zero recursion instead of a deep call
11
    /// chain. `serde_json`'s own 128-level parse cap keeps documents shallow, but
12
    /// this guarantees the jq walk itself never blows the stack on a huge pointer.
13
    #[test]
14
    #[cfg(feature = "serde-json")]
15
1
    fn huge_pointer_on_shallow_doc_returns_empty() {
16
1
        let json = Json::parse("{\"a\":{\"b\":1}}").expect("parse");
17
1
        let pointer = "/a".repeat(200_000);
18
1
        assert_eq!(json.jq_all(&pointer).as_ref().len(), 0);
19
1
    }
20

            
21
    /// A moderately deep linear pointer (within serde's parse limit) resolves to
22
    /// its single leaf via the iterative descent.
23
    #[test]
24
    #[cfg(feature = "serde-json")]
25
1
    fn deep_linear_pointer_resolves_leaf() {
26
        const DEPTH: usize = 100; // below serde_json's 128-level parse cap
27

            
28
1
        let mut doc = String::new();
29
101
        for _ in 0..DEPTH {
30
100
            doc.push_str("{\"a\":");
31
100
        }
32
1
        doc.push_str("42");
33
101
        for _ in 0..DEPTH {
34
100
            doc.push('}');
35
100
        }
36

            
37
1
        let json = Json::parse(&doc).expect("deep doc should parse");
38
1
        let pointer = "/a".repeat(DEPTH);
39
1
        let out = json.jq_all(&pointer);
40
1
        assert_eq!(out.as_ref().len(), 1, "the single leaf should be found");
41
1
    }
42

            
43
    /// Ordinary wildcard + index access still works after the iterative rewrite.
44
    #[test]
45
    #[cfg(feature = "serde-json")]
46
1
    fn wildcard_and_index_still_work() {
47
1
        let json = Json::parse("{\"items\":[{\"v\":1},{\"v\":2},{\"v\":3}]}").expect("parse");
48
1
        let all = json.jq_all("/items/*/v");
49
1
        assert_eq!(all.as_ref().len(), 3);
50
1
        let one = json.jq_all("/items/1/v");
51
1
        assert_eq!(one.as_ref().len(), 1);
52
1
    }
53
}
54

            
55
#[cfg(test)]
56
#[allow(clippy::float_cmp, clippy::unreadable_literal)]
57
mod autotest_generated {
58
    use super::*;
59

            
60
    // ------------------------------------------------------------------
61
    // helpers
62
    // ------------------------------------------------------------------
63

            
64
    fn az(s: &str) -> AzString {
65
        AzString::from(String::from(s))
66
    }
67

            
68
    /// Build a `Json` by hand, bypassing the constructors. Used to feed the
69
    /// accessors a *corrupt* value (e.g. `value_type: Array` whose internal
70
    /// string is not parseable JSON) — reachable over FFI because every field
71
    /// of `Json` / `JsonInternal` is `pub`.
72
    fn raw(value_type: JsonType, string_value: &str) -> Json {
73
        Json {
74
            value_type,
75
            internal: JsonInternal {
76
                string_value: az(string_value),
77
                number_value: 0.0,
78
                bool_value: false,
79
            },
80
        }
81
    }
82

            
83
    fn two_pow_63() -> f64 {
84
        2_f64.powi(63)
85
    }
86

            
87
    // ==================================================================
88
    // f64_as_i64  (numeric: zero / min_max / negative / overflow / nan_inf)
89
    // ==================================================================
90

            
91
    #[test]
92
    fn f64_as_i64_zero_and_negative_zero() {
93
        assert_eq!(f64_as_i64(0.0), Some(0));
94
        // -0.0 is an integer and in range: the sign is silently dropped.
95
        assert_eq!(f64_as_i64(-0.0), Some(0));
96
    }
97

            
98
    #[test]
99
    fn f64_as_i64_min_max_boundaries() {
100
        // -2^63 is exactly representable and is exactly i64::MIN.
101
        assert_eq!(f64_as_i64(-two_pow_63()), Some(i64::MIN));
102
        // +2^63 is NOT a valid i64 — must be rejected rather than wrapping.
103
        assert_eq!(f64_as_i64(two_pow_63()), None);
104
        // i64::MAX rounds *up* to 2^63 when cast to f64, so it is rejected too.
105
        // This is the documented reason the bound is `< 2^63` and not `<= MAX`.
106
        #[allow(clippy::cast_precision_loss)]
107
        let max_as_f64 = i64::MAX as f64;
108
        assert_eq!(max_as_f64, two_pow_63());
109
        assert_eq!(f64_as_i64(max_as_f64), None);
110
        // The largest f64 that is a valid i64: 2^63 - 1024.
111
        let just_below = two_pow_63() - 1024.0;
112
        assert_eq!(f64_as_i64(just_below), Some(9_223_372_036_854_774_784));
113
    }
114

            
115
    #[test]
116
    fn f64_as_i64_negatives_are_deterministic() {
117
        assert_eq!(f64_as_i64(-1.0), Some(-1));
118
        assert_eq!(f64_as_i64(-42.0), Some(-42));
119
        assert_eq!(f64_as_i64(-0.5), None);
120
        assert_eq!(f64_as_i64(-1.0 - f64::EPSILON), None);
121
        // One ULP below -2^63 is out of range.
122
        assert_eq!(f64_as_i64(-two_pow_63() * (1.0 + f64::EPSILON)), None);
123
    }
124

            
125
    #[test]
126
    fn f64_as_i64_overflow_inputs_return_none_not_a_wrapped_cast() {
127
        for n in [
128
            1e19_f64,
129
            1e300_f64,
130
            -1e300_f64,
131
            f64::MAX,
132
            f64::MIN,
133
            two_pow_63() * 2.0,
134
        ] {
135
            assert_eq!(f64_as_i64(n), None, "{n} must not be cast to i64");
136
        }
137
    }
138

            
139
    #[test]
140
    fn f64_as_i64_nan_and_infinity_do_not_panic() {
141
        // NaN.fract() is NaN, and NaN == 0.0 is false, so all three fall through
142
        // to `None` without ever reaching the (UB-adjacent) `as i64` cast.
143
        assert_eq!(f64_as_i64(f64::NAN), None);
144
        assert_eq!(f64_as_i64(f64::INFINITY), None);
145
        assert_eq!(f64_as_i64(f64::NEG_INFINITY), None);
146
    }
147

            
148
    #[test]
149
    fn f64_as_i64_fractional_and_subnormal_return_none() {
150
        assert_eq!(f64_as_i64(0.5), None);
151
        assert_eq!(f64_as_i64(f64::EPSILON), None);
152
        assert_eq!(f64_as_i64(f64::MIN_POSITIVE), None);
153
        // Smallest subnormal.
154
        assert_eq!(f64_as_i64(f64::from_bits(1)), None);
155
    }
156

            
157
    // ==================================================================
158
    // Json::number / Json::integer  (numeric)
159
    // ==================================================================
160

            
161
    #[test]
162
    fn number_stores_nan_and_infinity_without_panicking() {
163
        for n in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
164
            let j = Json::number(n);
165
            assert!(j.is_number());
166
            assert_eq!(j.as_i64(), OptionI64::None);
167
            match j.as_number() {
168
                OptionF64::Some(v) => assert_eq!(v.is_nan(), n.is_nan()),
169
                OptionF64::None => panic!("as_number() must be Some for a Number"),
170
            }
171
            // Display must not panic on non-finite floats.
172
            let s = alloc::format!("{j}");
173
            assert!(!s.is_empty());
174
        }
175
    }
176

            
177
    #[test]
178
    fn number_min_max_and_zero() {
179
        assert_eq!(Json::number(0.0).as_i64(), OptionI64::Some(0));
180
        assert_eq!(Json::number(-0.0).as_i64(), OptionI64::Some(0));
181
        assert_eq!(
182
            Json::number(f64::MAX).as_number(),
183
            OptionF64::Some(f64::MAX)
184
        );
185
        assert_eq!(
186
            Json::number(f64::MIN).as_number(),
187
            OptionF64::Some(f64::MIN)
188
        );
189
        // Huge-but-finite values are numbers, but not integers.
190
        assert_eq!(Json::number(f64::MAX).as_i64(), OptionI64::None);
191
    }
192

            
193
    #[test]
194
    fn integer_min_round_trips_but_max_does_not() {
195
        // i64::MIN == -2^63 is exactly representable in f64.
196
        assert_eq!(Json::integer(i64::MIN).as_i64(), OptionI64::Some(i64::MIN));
197
        // i64::MAX is NOT: `value as f64` rounds it up to 2^63, which is out of
198
        // i64 range, so the value cannot be read back. Documented on the fn as
199
        // "silent precision loss" for |value| > 2^53.
200
        assert_eq!(Json::integer(i64::MAX).as_i64(), OptionI64::None);
201
        assert_eq!(
202
            Json::integer(i64::MAX).as_number(),
203
            OptionF64::Some(two_pow_63())
204
        );
205
    }
206

            
207
    #[test]
208
    fn integer_silently_loses_precision_above_2_pow_53() {
209
        let boundary = 1_i64 << 53; // 9_007_199_254_740_992
210
        assert_eq!(Json::integer(boundary).as_i64(), OptionI64::Some(boundary));
211
        // 2^53 + 1 is not representable: it rounds *down* to 2^53.
212
        assert_eq!(
213
            Json::integer(boundary + 1).as_i64(),
214
            OptionI64::Some(boundary)
215
        );
216
        assert_eq!(Json::integer(0).as_i64(), OptionI64::Some(0));
217
        assert_eq!(Json::integer(-1).as_i64(), OptionI64::Some(-1));
218
    }
219

            
220
    // ==================================================================
221
    // constructors + predicates  (predicate: basic_true_false / edge_inputs)
222
    // ==================================================================
223

            
224
    #[test]
225
    fn predicates_are_mutually_exclusive_for_every_type() {
226
        let cases = [
227
            (Json::null(), JsonType::Null),
228
            (Json::bool(false), JsonType::Bool),
229
            (Json::number(f64::NAN), JsonType::Number),
230
            (Json::integer(0), JsonType::Number),
231
            (Json::string(""), JsonType::String),
232
            (raw(JsonType::Array, "[]"), JsonType::Array),
233
            (raw(JsonType::Object, "{}"), JsonType::Object),
234
        ];
235
        for (j, ty) in &cases {
236
            let flags = [
237
                j.is_null(),
238
                j.is_bool(),
239
                j.is_number(),
240
                j.is_string(),
241
                j.is_array(),
242
                j.is_object(),
243
            ];
244
            assert_eq!(
245
                flags.iter().filter(|b| **b).count(),
246
                1,
247
                "exactly one predicate must hold for {ty:?}"
248
            );
249
            assert_eq!(j.value_type, *ty);
250
        }
251
    }
252

            
253
    #[test]
254
    fn predicates_on_a_default_internal_do_not_panic() {
255
        // A hand-rolled Json with a default (empty) payload — the FFI worst case.
256
        for ty in [
257
            JsonType::Null,
258
            JsonType::Bool,
259
            JsonType::Number,
260
            JsonType::String,
261
            JsonType::Array,
262
            JsonType::Object,
263
        ] {
264
            let j = Json {
265
                value_type: ty,
266
                internal: JsonInternal::default(),
267
            };
268
            assert_eq!(j.is_null(), ty == JsonType::Null);
269
            assert_eq!(j.is_object(), ty == JsonType::Object);
270
            assert_eq!(j.raw_string(), "");
271
        }
272
    }
273

            
274
    #[test]
275
    fn bool_constructor_keeps_both_values() {
276
        assert_eq!(Json::bool(true).as_bool(), OptionBool::Some(true));
277
        assert_eq!(Json::bool(false).as_bool(), OptionBool::Some(false));
278
        // The unused payload fields are zeroed, which the derived PartialEq relies on.
279
        assert_eq!(Json::bool(true).raw_string(), "");
280
        assert_eq!(Json::bool(true).as_number(), OptionF64::None);
281
    }
282

            
283
    #[test]
284
    fn string_constructor_handles_empty_unicode_and_huge_inputs() {
285
        assert_eq!(Json::string("").as_string(), OptionString::Some(az("")));
286

            
287
        let unicode = "😀 náïve \u{0301}\u{202e}\0 中文";
288
        assert_eq!(
289
            Json::string(unicode).as_string(),
290
            OptionString::Some(az(unicode))
291
        );
292
        assert_eq!(Json::string(unicode).raw_string(), unicode);
293

            
294
        let huge = "a".repeat(1_000_000);
295
        let j = Json::string(huge.clone());
296
        assert_eq!(j.raw_string().len(), 1_000_000);
297
        assert_eq!(j.as_string(), OptionString::Some(AzString::from(huge)));
298
    }
299

            
300
    // ==================================================================
301
    // getters  (getter: basic_access / edge_access)
302
    // ==================================================================
303

            
304
    #[test]
305
    fn getters_return_none_on_type_mismatch() {
306
        let null = Json::null();
307
        assert_eq!(null.as_bool(), OptionBool::None);
308
        assert_eq!(null.as_number(), OptionF64::None);
309
        assert_eq!(null.as_i64(), OptionI64::None);
310
        assert_eq!(null.as_string(), OptionString::None);
311

            
312
        // A Bool whose *number* payload happens to be set must still not be
313
        // readable as a number (the tag, not the payload, decides).
314
        let mut liar = Json::bool(true);
315
        liar.internal.number_value = 7.0;
316
        liar.internal.string_value = az("7");
317
        assert_eq!(liar.as_number(), OptionF64::None);
318
        assert_eq!(liar.as_i64(), OptionI64::None);
319
        assert_eq!(liar.as_string(), OptionString::None);
320
        assert_eq!(liar.as_bool(), OptionBool::Some(true));
321
        // ...but raw_string() is the *unchecked* accessor and does hand it back.
322
        assert_eq!(liar.raw_string(), "7");
323
    }
324

            
325
    #[test]
326
    fn raw_string_is_empty_for_scalars_and_serialized_for_containers() {
327
        assert_eq!(Json::null().raw_string(), "");
328
        assert_eq!(Json::bool(true).raw_string(), "");
329
        assert_eq!(Json::number(1.5).raw_string(), "");
330
        assert_eq!(Json::string("hi").raw_string(), "hi");
331
        assert_eq!(raw(JsonType::Array, "[1,2]").raw_string(), "[1,2]");
332
        // Corrupt payloads are handed back verbatim, never panic.
333
        assert_eq!(raw(JsonType::Object, "{not json").raw_string(), "{not json");
334
    }
335

            
336
    // ==================================================================
337
    // Display for Json  (round_trip / serializer)
338
    // ==================================================================
339

            
340
    #[test]
341
    fn display_scalar_values() {
342
        assert_eq!(alloc::format!("{}", Json::null()), "null");
343
        assert_eq!(alloc::format!("{}", Json::bool(true)), "true");
344
        assert_eq!(alloc::format!("{}", Json::bool(false)), "false");
345
        // Integral floats print without a fractional part (via f64_as_i64).
346
        assert_eq!(alloc::format!("{}", Json::number(3.0)), "3");
347
        assert_eq!(alloc::format!("{}", Json::integer(-42)), "-42");
348
        assert_eq!(alloc::format!("{}", Json::number(1.5)), "1.5");
349
        assert_eq!(alloc::format!("{}", Json::string("x")), "\"x\"");
350
    }
351

            
352
    #[test]
353
    fn display_of_non_finite_numbers_is_not_json() {
354
        // Characterization: Display is documented as human-readable, NOT JSON.
355
        assert_eq!(alloc::format!("{}", Json::number(f64::NAN)), "NaN");
356
        assert_eq!(alloc::format!("{}", Json::number(f64::INFINITY)), "inf");
357
        assert_eq!(
358
            alloc::format!("{}", Json::number(f64::NEG_INFINITY)),
359
            "-inf"
360
        );
361
        // -0.0 loses its sign because f64_as_i64(-0.0) == Some(0).
362
        assert_eq!(alloc::format!("{}", Json::number(-0.0)), "0");
363
    }
364

            
365
    #[test]
366
    fn display_does_not_escape_strings() {
367
        // Documented caveat on the Display impl: embedded quotes/newlines are
368
        // NOT escaped, so the output is deliberately not valid JSON.
369
        let j = Json::string("a\"b\nc");
370
        assert_eq!(alloc::format!("{j}"), "\"a\"b\nc\"");
371
    }
372

            
373
    #[test]
374
    fn display_of_container_emits_the_raw_payload_even_when_corrupt() {
375
        assert_eq!(
376
            alloc::format!("{}", raw(JsonType::Array, "[1, 2]")),
377
            "[1, 2]"
378
        );
379
        assert_eq!(
380
            alloc::format!("{}", raw(JsonType::Object, "<<garbage>>")),
381
            "<<garbage>>"
382
        );
383
        assert_eq!(alloc::format!("{}", raw(JsonType::Array, "")), "");
384
    }
385

            
386
    // ==================================================================
387
    // JsonParseError::fmt  (serializer)
388
    // ==================================================================
389

            
390
    #[test]
391
    fn parse_error_display_with_and_without_position() {
392
        let with_pos = JsonParseError {
393
            message: az("expected value"),
394
            line: 3,
395
            column: 7,
396
        };
397
        assert_eq!(alloc::format!("{with_pos}"), "3:7: expected value");
398

            
399
        let no_pos = JsonParseError {
400
            message: az("expected value"),
401
            line: 0,
402
            column: 99,
403
        };
404
        assert_eq!(alloc::format!("{no_pos}"), "expected value");
405
    }
406

            
407
    #[test]
408
    fn parse_error_display_edge_values_do_not_panic() {
409
        let empty = JsonParseError {
410
            message: az(""),
411
            line: 0,
412
            column: 0,
413
        };
414
        assert_eq!(alloc::format!("{empty}"), "");
415

            
416
        let maxed = JsonParseError {
417
            message: az("😀"),
418
            line: u32::MAX,
419
            column: u32::MAX,
420
        };
421
        assert_eq!(
422
            alloc::format!("{maxed}"),
423
            alloc::format!("{}:{}: 😀", u32::MAX, u32::MAX)
424
        );
425
    }
426

            
427
    // ==================================================================
428
    // JsonKeyValue::create  (other: no_panic_smoke)
429
    // ==================================================================
430

            
431
    #[test]
432
    fn key_value_create_preserves_key_and_value() {
433
        let kv = JsonKeyValue::create(az(""), Json::null());
434
        assert_eq!(kv.key.as_str(), "");
435
        assert!(kv.value.is_null());
436

            
437
        let big_key = "k".repeat(100_000);
438
        let kv = JsonKeyValue::create(
439
            AzString::from(big_key.clone()),
440
            Json::number(f64::NEG_INFINITY),
441
        );
442
        assert_eq!(kv.key.as_str().len(), big_key.len());
443
        assert!(kv.value.is_number());
444

            
445
        let kv = JsonKeyValue::create(az("😀/\u{0}"), Json::string("v"));
446
        assert_eq!(kv.key.as_str(), "😀/\u{0}");
447
        assert_eq!(kv.value.as_string(), OptionString::Some(az("v")));
448
    }
449

            
450
    // ==================================================================
451
    // copy_from_array  (numeric: zero / min_max / overflow)
452
    // ==================================================================
453

            
454
    #[test]
455
    fn json_vec_copy_from_array_null_ptr_is_empty_even_at_usize_max_len() {
456
        // The null check runs first, so a bogus (null, huge) pair from C must
457
        // yield an empty vec rather than constructing a wild slice.
458
        let v = JsonVec::copy_from_array(core::ptr::null(), 0);
459
        assert!(v.is_empty());
460
        let v = JsonVec::copy_from_array(core::ptr::null(), usize::MAX);
461
        assert!(v.is_empty());
462
        assert_eq!(v.len(), 0);
463
    }
464

            
465
    #[test]
466
    fn json_vec_copy_from_array_zero_len_with_valid_ptr_is_empty() {
467
        let items = [Json::null(), Json::bool(true)];
468
        let v = JsonVec::copy_from_array(items.as_ptr(), 0);
469
        assert!(v.is_empty());
470
    }
471

            
472
    #[test]
473
    fn json_vec_copy_from_array_deep_copies_the_elements() {
474
        let items = vec![
475
            Json::null(),
476
            Json::bool(true),
477
            Json::number(f64::NAN),
478
            Json::string("😀"),
479
        ];
480
        let v = JsonVec::copy_from_array(items.as_ptr(), items.len());
481
        assert_eq!(v.len(), 4);
482
        assert_eq!(v.as_slice()[3].as_string(), OptionString::Some(az("😀")));
483
        // The copy is independent: dropping the source must not invalidate it.
484
        drop(items);
485
        assert!(v.as_slice()[0].is_null());
486
        assert_eq!(v.as_slice()[1].as_bool(), OptionBool::Some(true));
487
        assert_eq!(v.as_slice()[3].raw_string(), "😀");
488
    }
489

            
490
    #[test]
491
    fn key_value_vec_copy_from_array_null_ptr_is_empty_even_at_usize_max_len() {
492
        let v = JsonKeyValueVec::copy_from_array(core::ptr::null(), 0);
493
        assert!(v.is_empty());
494
        let v = JsonKeyValueVec::copy_from_array(core::ptr::null(), usize::MAX);
495
        assert!(v.is_empty());
496
        assert_eq!(v.len(), 0);
497
    }
498

            
499
    #[test]
500
    fn key_value_vec_copy_from_array_deep_copies_the_elements() {
501
        let items = vec![
502
            JsonKeyValue::create(az("a"), Json::integer(1)),
503
            JsonKeyValue::create(az(""), Json::null()),
504
        ];
505
        let v = JsonKeyValueVec::copy_from_array(items.as_ptr(), items.len());
506
        assert_eq!(v.len(), 2);
507
        let zero_len = JsonKeyValueVec::copy_from_array(items.as_ptr(), 0);
508
        assert!(zero_len.is_empty());
509
        drop(items);
510
        assert_eq!(v.as_slice()[0].key.as_str(), "a");
511
        assert_eq!(v.as_slice()[0].value.as_i64(), OptionI64::Some(1));
512
        assert_eq!(v.as_slice()[1].key.as_str(), "");
513
    }
514

            
515
    // ==================================================================
516
    // Json::parse / parse_bytes — malformed input
517
    // ==================================================================
518

            
519
    #[test]
520
    #[cfg(feature = "serde-json")]
521
    fn parse_empty_and_whitespace_only_input_is_an_error() {
522
        for s in ["", " ", "   ", "\t\n\r", "\u{feff}"] {
523
            let err = Json::parse(s).expect_err("empty/blank input must not parse");
524
            assert!(!err.message.as_str().is_empty());
525
            assert!(Json::parse_bytes(s.as_bytes()).is_err());
526
        }
527
        assert!(Json::parse_bytes(b"").is_err());
528
    }
529

            
530
    #[test]
531
    #[cfg(feature = "serde-json")]
532
    fn parse_garbage_returns_err_and_never_panics() {
533
        for s in [
534
            "{",
535
            "}",
536
            "[",
537
            "]",
538
            ",",
539
            ":",
540
            "nul",
541
            "tru",
542
            "'a'",
543
            "{,}",
544
            "[,]",
545
            "{\"a\"}",
546
            "{\"a\":}",
547
            "[1,]",
548
            "{\"a\":1,}",
549
            "\"unterminated",
550
            "\\",
551
            "\u{0}",
552
            "01",
553
            "+1",
554
            ".5",
555
            "1.",
556
            "-",
557
            "0x10",
558
            "--1",
559
            "1e",
560
            "{'a':1}",
561
            "undefined",
562
        ] {
563
            assert!(Json::parse(s).is_err(), "{s:?} must be rejected");
564
            assert!(Json::parse_bytes(s.as_bytes()).is_err(), "{s:?} (bytes)");
565
        }
566
    }
567

            
568
    #[test]
569
    #[cfg(feature = "serde-json")]
570
    fn parse_leading_and_trailing_junk() {
571
        // Surrounding whitespace is allowed and trimmed...
572
        assert_eq!(Json::parse("  1  ").expect("padded"), Json::integer(1));
573
        assert_eq!(
574
            Json::parse("\n\t{}\r\n").expect("padded"),
575
            Json::parse("{}").expect("{}")
576
        );
577
        // ...but trailing non-whitespace is not.
578
        for s in ["1;garbage", "{} {}", "null null", "1 2", "[1] x"] {
579
            assert!(Json::parse(s).is_err(), "{s:?} must be rejected");
580
        }
581
    }
582

            
583
    #[test]
584
    #[cfg(feature = "serde-json")]
585
    fn parse_bytes_rejects_invalid_utf8_without_panicking() {
586
        assert!(Json::parse_bytes(&[0xFF, 0xFE, 0x00]).is_err());
587
        // Structurally valid JSON, but the string body is not UTF-8.
588
        assert!(Json::parse_bytes(&[b'"', 0xFF, b'"']).is_err());
589
        // Lone continuation byte inside an otherwise fine document.
590
        assert!(Json::parse_bytes(&[b'[', 0x80, b']']).is_err());
591
    }
592

            
593
    #[test]
594
    #[cfg(feature = "serde-json")]
595
    fn parse_deeply_nested_input_errors_instead_of_overflowing_the_stack() {
596
        // serde_json's 128-level recursion cap turns this into an Err.
597
        let deep = alloc::format!("{}{}", "[".repeat(10_000), "]".repeat(10_000));
598
        assert!(Json::parse(&deep).is_err());
599
        assert!(Json::parse_bytes(deep.as_bytes()).is_err());
600

            
601
        let deep_obj = alloc::format!("{}1{}", "{\"a\":".repeat(10_000), "}".repeat(10_000));
602
        assert!(Json::parse(&deep_obj).is_err());
603

            
604
        // Unbalanced (never-closing) nesting must also terminate.
605
        let unbalanced = "[".repeat(100_000);
606
        assert!(Json::parse(&unbalanced).is_err());
607
    }
608

            
609
    #[test]
610
    #[cfg(feature = "serde-json")]
611
    fn parse_extremely_long_input_terminates() {
612
        const N: usize = 200_000;
613
        let mut doc = String::with_capacity(N * 2 + 2);
614
        doc.push('[');
615
        for i in 0..N {
616
            if i > 0 {
617
                doc.push(',');
618
            }
619
            doc.push('1');
620
        }
621
        doc.push(']');
622
        let j = Json::parse(&doc).expect("a long flat array must parse");
623
        assert!(j.is_array());
624
        assert_eq!(j.len(), N);
625

            
626
        // A ~1 MB string payload.
627
        let payload = "a".repeat(1_000_000);
628
        let j = Json::parse(&alloc::format!("\"{payload}\"")).expect("long string");
629
        assert_eq!(j.as_string(), OptionString::Some(AzString::from(payload)));
630
    }
631

            
632
    #[test]
633
    #[cfg(feature = "serde-json")]
634
    fn parse_unicode_input() {
635
        let j = Json::parse("\"\u{1F600}\"").expect("emoji");
636
        assert_eq!(j.as_string(), OptionString::Some(az("\u{1F600}")));
637

            
638
        // Combining marks + RTL override + escaped NUL survive the round trip.
639
        let j = Json::parse("\"e\\u0301\\u202e\\u0000\"").expect("escapes");
640
        assert_eq!(
641
            j.as_string(),
642
            OptionString::Some(az("e\u{0301}\u{202e}\u{0}"))
643
        );
644

            
645
        // Non-ASCII keys.
646
        let j = Json::parse("{\"ключ\":\"значение\"}").expect("cyrillic keys");
647
        assert_eq!(
648
            j.get_key("ключ").expect("key").as_string(),
649
            OptionString::Some(az("значение"))
650
        );
651

            
652
        // A lone surrogate is not encodable as UTF-8 and must be rejected.
653
        assert!(Json::parse("\"\\ud800\"").is_err());
654
    }
655

            
656
    #[test]
657
    #[cfg(feature = "serde-json")]
658
    fn parse_boundary_numbers() {
659
        assert_eq!(Json::parse("0").expect("0").as_i64(), OptionI64::Some(0));
660
        // "-0" is accepted; the sign is not observable through as_number().
661
        match Json::parse("-0").expect("-0").as_number() {
662
            OptionF64::Some(v) => assert_eq!(v, 0.0),
663
            OptionF64::None => panic!("-0 must be a number"),
664
        }
665

            
666
        // i64::MIN is exactly representable in f64 and reads back exactly.
667
        assert_eq!(
668
            Json::parse("-9223372036854775808")
669
                .expect("i64::MIN")
670
                .as_i64(),
671
            OptionI64::Some(i64::MIN)
672
        );
673
        // i64::MAX is NOT: it rounds up to 2^63 on the f64 hop through
674
        // `Number::as_f64()`, so as_i64() reports None (silent precision loss).
675
        let max = Json::parse("9223372036854775807").expect("i64::MAX");
676
        assert_eq!(max.as_number(), OptionF64::Some(two_pow_63()));
677
        assert_eq!(max.as_i64(), OptionI64::None);
678
        // Same for u64::MAX.
679
        assert_eq!(
680
            Json::parse("18446744073709551615")
681
                .expect("u64::MAX")
682
                .as_i64(),
683
            OptionI64::None
684
        );
685

            
686
        assert!(Json::parse("1e308").expect("1e308").is_number());
687
        assert!(Json::parse("1e-308").expect("1e-308").is_number());
688

            
689
        // JSON has no NaN/Infinity literals.
690
        for s in ["NaN", "nan", "Infinity", "-Infinity", "inf"] {
691
            assert!(Json::parse(s).is_err(), "{s:?} is not valid JSON");
692
        }
693

            
694
        // Overflowing exponents must not panic; whatever serde decides, the
695
        // result is a deterministic Ok(number) or Err.
696
        if let Ok(j) = Json::parse("1e400") {
697
            assert!(j.is_number());
698
        }
699
        if let Ok(j) = Json::parse("1e-400") {
700
            assert!(j.is_number());
701
        }
702
    }
703

            
704
    #[test]
705
    #[cfg(feature = "serde-json")]
706
    fn parse_valid_minimal_inputs() {
707
        assert_eq!(Json::parse("null").expect("null"), Json::null());
708
        assert_eq!(Json::parse("true").expect("true"), Json::bool(true));
709
        assert_eq!(Json::parse("false").expect("false"), Json::bool(false));
710
        assert_eq!(Json::parse("1").expect("1"), Json::integer(1));
711
        assert_eq!(Json::parse("1.5").expect("1.5"), Json::number(1.5));
712
        assert_eq!(Json::parse("\"s\"").expect("str"), Json::string("s"));
713
        assert!(Json::parse("[]").expect("[]").is_array());
714
        assert!(Json::parse("{}").expect("{}").is_object());
715
        // parse_bytes agrees with parse.
716
        assert_eq!(
717
            Json::parse_bytes(b"{\"a\":[1,2]}").expect("bytes"),
718
            Json::parse("{\"a\":[1,2]}").expect("str")
719
        );
720
    }
721

            
722
    // ==================================================================
723
    // round trips  (round_trip: representative / edge / stable)
724
    // ==================================================================
725

            
726
    #[cfg(feature = "serde-json")]
727
    fn round_trip_corpus() -> Vec<Json> {
728
        vec![
729
            Json::null(),
730
            Json::bool(true),
731
            Json::bool(false),
732
            Json::integer(0),
733
            Json::integer(-1),
734
            Json::integer(i64::MIN),
735
            Json::number(1.5),
736
            Json::number(-0.25),
737
            Json::number(1e21),
738
            Json::string(""),
739
            Json::string("😀 \"quoted\" \\slash\\ \n\t \u{0}"),
740
            Json::parse("[]").expect("[]"),
741
            Json::parse("{}").expect("{}"),
742
            Json::parse("[1,[2,[3]],{\"k\":null}]").expect("nested array"),
743
            Json::parse("{\"a\":{\"b\":[1,2,3]},\"ünï\":\"😀\"}").expect("nested object"),
744
        ]
745
    }
746

            
747
    #[test]
748
    #[cfg(feature = "serde-json")]
749
    fn parse_of_to_json_string_reproduces_the_value() {
750
        for j in round_trip_corpus() {
751
            let encoded = j.to_json_string();
752
            let decoded = Json::parse(encoded.as_str())
753
                .unwrap_or_else(|e| panic!("{encoded:?} must re-parse: {e}"));
754
            assert_eq!(decoded, j, "round trip failed for {encoded:?}");
755
        }
756
    }
757

            
758
    #[test]
759
    #[cfg(feature = "serde-json")]
760
    fn serialize_parse_serialize_is_idempotent() {
761
        for j in round_trip_corpus() {
762
            let once = j.to_json_string();
763
            let twice = Json::parse(once.as_str())
764
                .expect("re-parse")
765
                .to_json_string();
766
            assert_eq!(once.as_str(), twice.as_str());
767
        }
768
    }
769

            
770
    #[test]
771
    #[cfg(feature = "serde-json")]
772
    fn round_trip_extreme_floats() {
773
        for n in [f64::MAX, f64::MIN, f64::MIN_POSITIVE, -f64::MIN_POSITIVE] {
774
            let j = Json::number(n);
775
            let encoded = j.to_json_string();
776
            let decoded = Json::parse(encoded.as_str())
777
                .unwrap_or_else(|e| panic!("{encoded:?} must re-parse: {e}"));
778
            assert_eq!(decoded.as_number(), OptionF64::Some(n));
779
        }
780
    }
781

            
782
    #[test]
783
    #[cfg(feature = "serde-json")]
784
    fn non_finite_numbers_do_not_survive_to_json_string() {
785
        // BUG (characterized, not fixed here): `to_json_string()` promises valid
786
        // JSON, but for a non-finite `number_value` it falls back to Rust's float
787
        // Display and emits the bare tokens `NaN` / `inf` / `-inf`, which no JSON
788
        // parser accepts. `to_serde_value()` handles the same input correctly by
789
        // mapping it to `null`. Callers must therefore not assume
790
        // `parse(to_json_string(x))` succeeds for a hand-built non-finite number.
791
        for (n, token) in [
792
            (f64::NAN, "NaN"),
793
            (f64::INFINITY, "inf"),
794
            (f64::NEG_INFINITY, "-inf"),
795
        ] {
796
            let j = Json::number(n);
797
            let encoded = j.to_json_string();
798
            assert_eq!(encoded.as_str(), token);
799
            assert!(
800
                Json::parse(encoded.as_str()).is_err(),
801
                "{token} is not valid JSON"
802
            );
803
            // The serde path degrades safely instead.
804
            assert_eq!(j.to_serde_value(), serde_json::Value::Null);
805
        }
806
    }
807

            
808
    // ==================================================================
809
    // from_serde_value / to_serde_value
810
    // ==================================================================
811

            
812
    #[test]
813
    #[cfg(feature = "serde-json")]
814
    fn from_serde_value_maps_every_variant() {
815
        use serde_json::json;
816

            
817
        assert!(Json::from_serde_value(json!(null)).is_null());
818
        assert_eq!(
819
            Json::from_serde_value(json!(true)).as_bool(),
820
            OptionBool::Some(true)
821
        );
822
        assert_eq!(
823
            Json::from_serde_value(json!(-3)).as_i64(),
824
            OptionI64::Some(-3)
825
        );
826
        assert_eq!(
827
            Json::from_serde_value(json!("😀")).as_string(),
828
            OptionString::Some(az("😀"))
829
        );
830

            
831
        let arr = Json::from_serde_value(json!([1, "two", null]));
832
        assert!(arr.is_array());
833
        assert_eq!(arr.len(), 3);
834
        assert_eq!(arr.get_index(1).expect("idx 1"), Json::string("two"));
835

            
836
        let obj = Json::from_serde_value(json!({"a": 1, "b": {"c": []}}));
837
        assert!(obj.is_object());
838
        assert_eq!(obj.len(), 2);
839
        assert_eq!(obj.get_key("a").expect("a"), Json::integer(1));
840
        // The serialized payload must itself be valid JSON (invariant).
841
        assert!(Json::parse(obj.raw_string()).is_ok());
842
    }
843

            
844
    #[test]
845
    #[cfg(feature = "serde-json")]
846
    fn to_serde_value_round_trips_through_from_serde_value() {
847
        use serde_json::json;
848

            
849
        for v in [
850
            json!(null),
851
            json!(false),
852
            json!(0),
853
            json!(-1.5),
854
            json!(""),
855
            json!([]),
856
            json!({}),
857
            json!({"k": [1, {"n": null}], "ü": "😀"}),
858
        ] {
859
            let back = Json::from_serde_value(v.clone()).to_serde_value();
860
            assert_eq!(back, v);
861
        }
862
    }
863

            
864
    #[test]
865
    #[cfg(feature = "serde-json")]
866
    fn to_serde_value_on_a_corrupt_container_yields_null() {
867
        assert_eq!(
868
            raw(JsonType::Array, "not json").to_serde_value(),
869
            serde_json::Value::Null
870
        );
871
        assert_eq!(
872
            raw(JsonType::Object, "").to_serde_value(),
873
            serde_json::Value::Null
874
        );
875
    }
876

            
877
    // ==================================================================
878
    // Json::array / Json::object  (other: no_panic_smoke)
879
    // ==================================================================
880

            
881
    #[test]
882
    #[cfg(feature = "serde-json")]
883
    fn array_constructor_handles_empty_and_non_finite_members() {
884
        let empty = Json::array(JsonVec::new());
885
        assert!(empty.is_array());
886
        assert_eq!(empty.len(), 0);
887
        assert!(empty.is_empty());
888
        assert_eq!(empty.raw_string(), "[]");
889

            
890
        // A NaN member cannot be represented in JSON — it degrades to null
891
        // (via to_serde_value) rather than producing invalid output or panicking.
892
        let with_nan = Json::array(JsonVec::from_vec(vec![
893
            Json::number(f64::NAN),
894
            Json::number(f64::INFINITY),
895
            Json::integer(1),
896
        ]));
897
        assert_eq!(with_nan.raw_string(), "[null,null,1]");
898
        assert_eq!(with_nan.len(), 3);
899
        assert!(Json::parse(with_nan.raw_string()).is_ok());
900
    }
901

            
902
    #[test]
903
    #[cfg(feature = "serde-json")]
904
    fn object_constructor_dedupes_duplicate_keys_last_one_wins() {
905
        let empty = Json::object(JsonKeyValueVec::new());
906
        assert!(empty.is_object());
907
        assert!(empty.is_empty());
908
        assert_eq!(empty.raw_string(), "{}");
909

            
910
        let dup = Json::object(JsonKeyValueVec::from_vec(vec![
911
            JsonKeyValue::create(az("k"), Json::integer(1)),
912
            JsonKeyValue::create(az("k"), Json::integer(2)),
913
            JsonKeyValue::create(az(""), Json::null()),
914
        ]));
915
        assert_eq!(dup.len(), 2, "duplicate keys collapse into one entry");
916
        assert_eq!(dup.get_key("k").expect("k"), Json::integer(2));
917
        assert!(dup.get_key("").expect("empty key").is_null());
918
    }
919

            
920
    #[test]
921
    #[cfg(feature = "serde-json")]
922
    fn object_constructor_escapes_hostile_keys() {
923
        let obj = Json::object(JsonKeyValueVec::from_vec(vec![JsonKeyValue::create(
924
            az("\"}\n😀"),
925
            Json::string("v"),
926
        )]));
927
        // The payload must still be parseable JSON — i.e. the key was escaped.
928
        let reparsed = Json::parse(obj.raw_string()).expect("hostile key must be escaped");
929
        assert_eq!(
930
            reparsed.get_key("\"}\n😀").expect("key").as_string(),
931
            OptionString::Some(az("v"))
932
        );
933
    }
934

            
935
    // ==================================================================
936
    // len / is_empty  (getter + predicate)
937
    // ==================================================================
938

            
939
    #[test]
940
    #[cfg(feature = "serde-json")]
941
    fn len_is_zero_for_scalars_which_makes_is_empty_true() {
942
        // Characterization: len()/is_empty() are documented "for arrays/objects";
943
        // for scalars they report 0 / true, so `is_empty()` is NOT "has no value".
944
        for j in [
945
            Json::null(),
946
            Json::bool(true),
947
            Json::integer(7),
948
            Json::string("hello"),
949
        ] {
950
            assert_eq!(j.len(), 0);
951
            assert!(j.is_empty());
952
        }
953
    }
954

            
955
    #[test]
956
    #[cfg(feature = "serde-json")]
957
    fn len_of_containers_and_corrupt_payloads() {
958
        assert_eq!(Json::parse("[1,2,3]").expect("arr").len(), 3);
959
        assert_eq!(Json::parse("{\"a\":1}").expect("obj").len(), 1);
960
        assert_eq!(Json::parse("[]").expect("[]").len(), 0);
961
        // Corrupt payload → 0 rather than a panic.
962
        assert_eq!(raw(JsonType::Array, "not json").len(), 0);
963
        assert!(raw(JsonType::Object, "").is_empty());
964
        // Tag/payload mismatch (Array tag over an object payload) → 0.
965
        assert_eq!(raw(JsonType::Array, "{\"a\":1}").len(), 0);
966
    }
967

            
968
    // ==================================================================
969
    // get_index / get_key / keys / to_array / to_object
970
    // ==================================================================
971

            
972
    #[test]
973
    #[cfg(feature = "serde-json")]
974
    fn get_index_boundaries() {
975
        let arr = Json::parse("[10,20]").expect("arr");
976
        assert_eq!(arr.get_index(0).expect("0"), Json::integer(10));
977
        assert_eq!(arr.get_index(1).expect("1"), Json::integer(20));
978
        assert!(arr.get_index(2).is_none());
979
        assert!(arr.get_index(usize::MAX).is_none());
980

            
981
        assert!(Json::parse("[]").expect("[]").get_index(0).is_none());
982
        // Non-arrays never index, whatever the payload says.
983
        assert!(Json::parse("{\"0\":1}")
984
            .expect("obj")
985
            .get_index(0)
986
            .is_none());
987
        assert!(Json::string("abc").get_index(0).is_none());
988
        assert!(raw(JsonType::Array, "not json").get_index(0).is_none());
989
        assert!(raw(JsonType::Array, "{\"a\":1}").get_index(0).is_none());
990
    }
991

            
992
    #[test]
993
    #[cfg(feature = "serde-json")]
994
    fn get_key_edge_inputs() {
995
        let obj = Json::parse("{\"\":1,\"a\":null,\"😀\":[]}").expect("obj");
996
        assert_eq!(obj.get_key("").expect("empty key"), Json::integer(1));
997
        assert!(obj.get_key("a").expect("a").is_null());
998
        assert!(obj.get_key("😀").expect("emoji").is_array());
999
        assert!(obj.get_key("missing").is_none());
        // Keys are exact, not prefix/trimmed matches.
        assert!(obj.get_key(" a").is_none());
        assert!(obj.get_key("A").is_none());
        // A huge key must not panic.
        assert!(obj.get_key(&"k".repeat(1_000_000)).is_none());
        // Non-objects always return None.
        assert!(Json::parse("[1]").expect("arr").get_key("0").is_none());
        assert!(Json::null().get_key("").is_none());
        assert!(raw(JsonType::Object, "not json").get_key("a").is_none());
    }
    #[test]
    #[cfg(feature = "serde-json")]
    fn keys_returns_every_key_and_nothing_for_non_objects() {
        let obj = Json::parse("{\"b\":1,\"a\":2,\"\":3}").expect("obj");
        let keys = obj.keys();
        assert_eq!(keys.len(), 3);
        for expected in ["a", "b", ""] {
            assert!(
                keys.iter().any(|k| k.as_str() == expected),
                "missing key {expected:?}"
            );
        }
        assert!(Json::parse("{}").expect("{}").keys().is_empty());
        assert!(Json::parse("[1,2]").expect("arr").keys().is_empty());
        assert!(Json::string("x").keys().is_empty());
        assert!(raw(JsonType::Object, "not json").keys().is_empty());
    }
    #[test]
    #[cfg(feature = "serde-json")]
    fn to_array_and_to_object_on_wrong_types_and_corrupt_payloads() {
        let arr = Json::parse("[null,1]")
            .expect("arr")
            .to_array()
            .expect("to_array");
        assert_eq!(arr.len(), 2);
        assert!(arr.as_slice()[0].is_null());
        assert_eq!(arr.as_slice()[1].as_i64(), OptionI64::Some(1));
        let obj = Json::parse("{\"a\":\"v\"}")
            .expect("obj")
            .to_object()
            .expect("to_object");
        assert_eq!(obj.len(), 1);
        assert_eq!(obj.as_slice()[0].key.as_str(), "a");
        assert_eq!(
            obj.as_slice()[0].value.as_string(),
            OptionString::Some(az("v"))
        );
        assert!(Json::parse("[]")
            .expect("[]")
            .to_array()
            .expect("empty")
            .is_empty());
        assert!(Json::parse("{}")
            .expect("{}")
            .to_object()
            .expect("empty")
            .is_empty());
        // Wrong type / corrupt payload / tag mismatch → None, never a panic.
        assert!(Json::null().to_array().is_none());
        assert!(Json::string("[]").to_array().is_none());
        assert!(Json::parse("[]").expect("[]").to_object().is_none());
        assert!(raw(JsonType::Array, "not json").to_array().is_none());
        assert!(raw(JsonType::Object, "").to_object().is_none());
        assert!(raw(JsonType::Array, "{\"a\":1}").to_array().is_none());
        assert!(raw(JsonType::Object, "[1]").to_object().is_none());
    }
    // ==================================================================
    // to_json_string / to_string_pretty
    // ==================================================================
    #[test]
    #[cfg(feature = "serde-json")]
    fn to_json_string_escapes_strings_unlike_display() {
        let j = Json::string("a\"b\nc\\d\u{0}");
        let encoded = j.to_json_string();
        // Valid JSON that re-parses to the identical value...
        assert_eq!(Json::parse(encoded.as_str()).expect("escaped"), j);
        // ...and it differs from the (documented as non-JSON) Display output.
        assert_ne!(encoded.as_str(), alloc::format!("{j}"));
    }
    #[test]
    #[cfg(feature = "serde-json")]
    fn to_string_pretty_matches_to_json_string_for_scalars() {
        for j in [
            Json::null(),
            Json::bool(false),
            Json::integer(-7),
            Json::number(0.5),
            Json::string("😀"),
        ] {
            assert_eq!(j.to_string_pretty().as_str(), j.to_json_string().as_str());
        }
    }
    #[test]
    #[cfg(feature = "serde-json")]
    fn to_string_pretty_of_containers_reparses_to_the_same_value() {
        let j = Json::parse("{\"a\":[1,{\"b\":null}],\"c\":{}}").expect("obj");
        let pretty = j.to_string_pretty();
        assert!(
            pretty.as_str().contains('\n'),
            "pretty output must be indented"
        );
        assert_eq!(Json::parse(pretty.as_str()).expect("pretty reparses"), j);
        // A corrupt payload is passed through verbatim instead of panicking.
        let corrupt = raw(JsonType::Object, "not json");
        assert_eq!(corrupt.to_string_pretty().as_str(), "not json");
        assert_eq!(raw(JsonType::Array, "").to_string_pretty().as_str(), "");
    }
    // ==================================================================
    // jq / jq_all  (other: no_panic_smoke)
    // ==================================================================
    #[test]
    #[cfg(feature = "serde-json")]
    fn jq_on_scalars_only_matches_the_empty_pointer() {
        for j in [
            Json::null(),
            Json::bool(true),
            Json::integer(1),
            Json::string("s"),
        ] {
            assert_eq!(j.jq(""), j);
            assert!(j.jq("/").is_null());
            assert!(j.jq("/a").is_null());
            assert!(j.jq("nonsense").is_null());
            assert_eq!(j.jq_all("").as_ref().len(), 1);
            assert_eq!(j.jq_all("/a").as_ref().len(), 0);
        }
    }
    #[test]
    #[cfg(feature = "serde-json")]
    fn jq_navigates_and_degrades_to_null() {
        let j = Json::parse("{\"a\":{\"b\":[10,20]},\"\":1}").expect("doc");
        assert_eq!(j.jq(""), j, "the empty pointer selects the whole document");
        assert_eq!(j.jq("/a/b/1"), Json::integer(20));
        assert_eq!(
            j.jq("/"),
            Json::integer(1),
            "'/' selects the empty-string key"
        );
        // Misses / malformed pointers / hostile input → null, never a panic.
        assert!(j.jq("/a/b/2").is_null(), "out-of-range index");
        assert!(j.jq("/a/b/-1").is_null(), "negative index is not a usize");
        assert!(
            j.jq("/a/b/99999999999999999999").is_null(),
            "index overflows usize"
        );
        assert!(j.jq("a/b").is_null(), "pointer must start with '/'");
        assert!(j.jq("/missing").is_null());
        assert!(j.jq(&"/a".repeat(100_000)).is_null(), "huge pointer");
        assert!(
            j.jq("/a/b/1/deeper").is_null(),
            "descending through a scalar"
        );
        assert!(raw(JsonType::Object, "not json").jq("/a").is_null());
    }
    #[test]
    #[cfg(feature = "serde-json")]
    fn jq_all_wildcards_and_empty_results() {
        let j = Json::parse("{\"a\":[{\"v\":1},{\"v\":2}],\"b\":{\"v\":3},\"c\":7}").expect("doc");
        assert_eq!(j.jq_all("/a/*/v").as_ref().len(), 2);
        // A wildcard over an object iterates its values; scalars contribute nothing.
        assert_eq!(j.jq_all("/*/v").as_ref().len(), 1);
        assert_eq!(j.jq_all("/*").as_ref().len(), 3);
        assert_eq!(j.jq_all("").as_ref().len(), 1);
        // No match / malformed / corrupt → empty vec.
        assert_eq!(j.jq_all("/missing/*").as_ref().len(), 0);
        assert_eq!(j.jq_all("a").as_ref().len(), 0);
        assert_eq!(j.jq_all("/c/*").as_ref().len(), 0, "wildcard over a scalar");
        assert_eq!(j.jq_all("/*/*/*/*/*").as_ref().len(), 0);
        assert_eq!(
            raw(JsonType::Array, "not json").jq_all("/*").as_ref().len(),
            0
        );
        // A pointer that is only wildcards, far longer than the document is deep.
        let many = "/*".repeat(10_000);
        assert_eq!(j.jq_all(&many).as_ref().len(), 0);
    }
    // ==================================================================
    // jq_all_recursive_depth  (numeric: zero / min_max / overflow)
    // ==================================================================
    #[test]
    #[cfg(feature = "serde-json")]
    fn jq_all_recursive_depth_honours_the_wildcard_cap() {
        let value = serde_json::json!({"a": 1});
        // depth 0 (what jq_all_recursive passes) resolves normally.
        assert_eq!(Json::jq_all_recursive_depth(&value, "/a", 0).len(), 1);
        // Exactly at the cap it still resolves...
        assert_eq!(
            Json::jq_all_recursive_depth(&value, "/a", Json::JQ_MAX_WILDCARD_DEPTH).len(),
            1
        );
        // ...one past it, the guard fires and yields no match instead of recursing.
        assert_eq!(
            Json::jq_all_recursive_depth(&value, "/a", Json::JQ_MAX_WILDCARD_DEPTH + 1).len(),
            0
        );
        // usize::MAX must hit the guard before the `depth + 1` in the wildcard arm,
        // so there is no add-overflow panic.
        assert_eq!(
            Json::jq_all_recursive_depth(&value, "/*", usize::MAX).len(),
            0
        );
        assert_eq!(
            Json::jq_all_recursive_depth(&value, "", usize::MAX).len(),
            0
        );
    }
    #[test]
    #[cfg(feature = "serde-json")]
    fn jq_all_wildcard_fanout_deeper_than_the_cap_returns_empty() {
        // Build the document programmatically: serde_json's own 128-level parse
        // cap means such a document can never come from `Json::parse`, so this is
        // the only way to drive the wildcard recursion to its 512 limit.
        fn nest(depth: usize) -> serde_json::Value {
            let mut v = serde_json::Value::from(1_i64);
            for _ in 0..depth {
                v = serde_json::Value::Array(vec![v]);
            }
            v
        }
        // Below the cap: the leaf is found.
        let shallow = nest(400);
        let found = Json::jq_all_recursive(&shallow, &"/*".repeat(400));
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].as_i64(), OptionI64::Some(1));
        // Above the cap: the guard stops the recursion and returns no match.
        let deep = nest(600);
        assert!(Json::jq_all_recursive(&deep, &"/*".repeat(600)).is_empty());
    }
}