qubit-json 0.12.4

Resource-aware infrastructure for lenient and strict JSON processing
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
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Defines the shared error returned by all JSON decoding facades.

use std::error::Error;
use std::fmt;
use std::io;
use std::sync::Arc;

use qubit_budget::MeasuredBudgetError;
use qubit_budget::ResourceQuantity;
use qubit_budget::json::JsonResource;
use serde_json::Error as JsonError;

use super::DiagnosticPolicy;
use super::JsonDecodeErrorKind;
use super::JsonDecodeErrorSource;
use super::JsonDecodeStage;
use super::JsonMaterializationErrorReason;
use super::JsonRootKind;
use super::JsonSyntaxError;
use crate::lexical::JsonLexicalFailure;

/// Failure produced by either strict or normalizing JSON decoding.
///
/// Internal variants are private so callers branch through stable semantic
/// accessors rather than depending on scanner, normalizer, or Serde details.
///
/// # Type Parameters
///
/// * `R` - Resource identity attached to budget failures.
/// * `Q` - Quantity representation attached to budget failures.
///
/// # Examples
///
/// ```
/// use qubit_json::decode::{JsonDecodeError, JsonDecodeErrorKind, JsonDecoder};
/// use serde_json::Value;
///
/// let mut decoder = JsonDecoder::unlimited();
/// let error: JsonDecodeError = decoder
///     .decode_str::<Value>("")
///     .expect_err("empty input must be rejected");
/// assert_eq!(error.kind(), JsonDecodeErrorKind::InvalidJson);
/// ```
#[must_use]
#[derive(Clone)]
pub struct JsonDecodeError<R = JsonResource, Q = usize>
where
    Q: Copy + fmt::Debug,
{
    /// Policy controlling input-derived source retention.
    diagnostic_policy: DiagnosticPolicy,
    /// Safe reason for a unique-key intermediate-tree construction failure.
    materialization_reason: Option<JsonMaterializationErrorReason>,
    /// Mutually exclusive structured failure.
    failure: JsonDecodeErrorSource<R, Q>,
}

impl<R, Q> JsonDecodeError<R, Q>
where
    Q: Copy + fmt::Debug,
{
    /// Creates a stream-read failure and conditionally retains its source.
    ///
    /// # Parameters
    ///
    /// * `source` - I/O error produced while reading the input.
    /// * `raw_input_bytes` - Number of input bytes read before the failure.
    /// * `diagnostic_policy` - Whether to retain the original error details.
    ///
    /// # Returns
    ///
    /// A read failure containing the I/O category and, under detailed
    /// diagnostics, the original error.
    pub(crate) fn read(source: io::Error, raw_input_bytes: usize, diagnostic_policy: DiagnosticPolicy) -> Self {
        let kind = source.kind();
        let source = (diagnostic_policy == DiagnosticPolicy::Detailed).then(|| Arc::new(source));
        Self {
            diagnostic_policy,
            materialization_reason: None,
            failure: JsonDecodeErrorSource::Read {
                raw_input_bytes,
                kind,
                source,
            },
        }
    }

    /// Creates a measured-budget failure at a semantic stage.
    ///
    /// # Parameters
    ///
    /// * `source` - Resource measurement that exceeded its budget.
    /// * `stage` - Decode stage where the budget was exceeded.
    /// * `raw_input_bytes` - Original input length in bytes.
    /// * `normalized_input_bytes` - Normalized input length, when available.
    /// * `diagnostic_policy` - Policy controlling retained input details.
    ///
    /// # Returns
    ///
    /// A budget failure retaining the measured resource error and decode
    /// stage.
    pub(crate) const fn budget(
        source: MeasuredBudgetError<R, Q>,
        stage: JsonDecodeStage,
        raw_input_bytes: usize,
        normalized_input_bytes: Option<usize>,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        Self {
            diagnostic_policy,
            materialization_reason: None,
            failure: JsonDecodeErrorSource::Budget {
                stage,
                raw_input_bytes,
                normalized_input_bytes,
                source,
            },
        }
    }

    /// Creates an empty-input failure at a semantic stage.
    ///
    /// # Parameters
    ///
    /// * `stage` - Decode stage where the empty input was detected.
    /// * `raw_input_bytes` - Original input length in bytes.
    /// * `normalized_input_bytes` - Normalized input length, when available.
    /// * `diagnostic_policy` - Policy controlling retained input details.
    ///
    /// # Returns
    ///
    /// An empty-input failure retaining the stage and input lengths.
    pub(crate) const fn empty_input(
        stage: JsonDecodeStage,
        raw_input_bytes: usize,
        normalized_input_bytes: Option<usize>,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        Self {
            diagnostic_policy,
            materialization_reason: None,
            failure: JsonDecodeErrorSource::EmptyInput {
                stage,
                raw_input_bytes,
                normalized_input_bytes,
            },
        }
    }

    /// Creates an invalid-UTF-8 failure and conditionally retains its source.
    ///
    /// # Parameters
    ///
    /// * `source` - UTF-8 validation failure for the input bytes.
    /// * `raw_input_bytes` - Original input length in bytes.
    /// * `diagnostic_policy` - Whether to retain the original error details.
    ///
    /// # Returns
    ///
    /// An invalid-UTF-8 failure retaining the invalid byte position and, under
    /// detailed diagnostics, the original validation error.
    pub(crate) fn invalid_utf8(
        source: std::str::Utf8Error,
        raw_input_bytes: usize,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        let valid_up_to = source.valid_up_to();
        let error_len = source.error_len();
        let source = (diagnostic_policy == DiagnosticPolicy::Detailed).then_some(source);
        Self {
            diagnostic_policy,
            materialization_reason: None,
            failure: JsonDecodeErrorSource::InvalidUtf8 {
                raw_input_bytes,
                valid_up_to,
                error_len,
                source,
            },
        }
    }

    /// Creates a stable invalid-JSON failure from lexical admission.
    ///
    /// # Parameters
    ///
    /// * `syntax_source` - Lexical failure with stable syntax details.
    /// * `detailed_source` - Optional parser error retained for detailed
    ///   diagnostics.
    /// * `raw_input_bytes` - Original input length in bytes.
    /// * `normalized_input_bytes` - Normalized input length, when available.
    /// * `diagnostic_policy` - Policy controlling retained input details.
    ///
    /// # Returns
    ///
    /// An invalid-JSON failure containing stable syntax details and the
    /// optional detailed parser source.
    pub(crate) fn invalid_json(
        syntax_source: JsonLexicalFailure,
        detailed_source: Option<Arc<dyn Error + Send + Sync>>,
        raw_input_bytes: usize,
        normalized_input_bytes: Option<usize>,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        Self {
            diagnostic_policy,
            materialization_reason: None,
            failure: JsonDecodeErrorSource::InvalidJson {
                raw_input_bytes,
                normalized_input_bytes,
                syntax: JsonSyntaxError::from_lexical(syntax_source),
                source: detailed_source,
            },
        }
    }

    /// Creates an unexpected-top-level failure.
    ///
    /// # Parameters
    ///
    /// * `expected` - Required top-level JSON kind.
    /// * `actual` - Observed top-level JSON kind.
    /// * `raw_input_bytes` - Original input length in bytes.
    /// * `normalized_input_bytes` - Normalized input length, when available.
    /// * `diagnostic_policy` - Policy controlling retained input details.
    ///
    /// # Returns
    ///
    /// A top-level-kind failure retaining the expected and observed kinds.
    pub(crate) const fn unexpected_top_level(
        expected: JsonRootKind,
        actual: JsonRootKind,
        raw_input_bytes: usize,
        normalized_input_bytes: Option<usize>,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        Self {
            diagnostic_policy,
            materialization_reason: None,
            failure: JsonDecodeErrorSource::UnexpectedTopLevel {
                raw_input_bytes,
                normalized_input_bytes,
                expected,
                actual,
            },
        }
    }

    /// Creates a target-deserialization failure and conditionally retains its
    /// input-derived source.
    ///
    /// # Parameters
    ///
    /// * `source` - Serde error produced while materializing the target value.
    /// * `raw_input_bytes` - Original input length in bytes.
    /// * `normalized_input_bytes` - Normalized input length, when available.
    /// * `diagnostic_policy` - Whether to retain the original error details.
    ///
    /// # Returns
    ///
    /// A deserialization failure retaining the source location and, under
    /// detailed diagnostics, the original Serde error.
    pub(crate) fn deserialize(
        source: JsonError,
        raw_input_bytes: usize,
        normalized_input_bytes: Option<usize>,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        let line = source.line();
        let column = source.column();
        let source =
            (diagnostic_policy == DiagnosticPolicy::Detailed).then(|| Arc::new(source) as Arc<dyn Error + Send + Sync>);
        Self {
            diagnostic_policy,
            materialization_reason: None,
            failure: JsonDecodeErrorSource::Deserialize {
                raw_input_bytes,
                normalized_input_bytes,
                line,
                column,
                source,
            },
        }
    }

    /// Creates a unique-key materialization failure with a safe subreason.
    ///
    /// # Parameters
    ///
    /// * `source` - Serde error produced while constructing the unique-key
    ///   tree.
    /// * `reason` - Safe materialization failure category.
    /// * `raw_input_bytes` - Original input length in bytes.
    /// * `diagnostic_policy` - Policy controlling retained input details.
    ///
    /// # Returns
    ///
    /// A deserialization failure annotated with the safe materialization
    /// reason.
    pub(crate) fn materialization(
        source: JsonError,
        reason: JsonMaterializationErrorReason,
        raw_input_bytes: usize,
        diagnostic_policy: DiagnosticPolicy,
    ) -> Self {
        let mut error = Self::deserialize(source, raw_input_bytes, None, diagnostic_policy);
        error.materialization_reason = Some(reason);
        error
    }

    /// Returns the stable failure category.
    ///
    /// # Returns
    ///
    /// The category describing which kind of decode operation failed.
    #[must_use = "inspect or propagate the underlying decode error source"]
    #[inline(always)]
    pub const fn kind(&self) -> JsonDecodeErrorKind {
        match self.failure {
            JsonDecodeErrorSource::Read { .. } => JsonDecodeErrorKind::Read,
            JsonDecodeErrorSource::Budget { .. } => JsonDecodeErrorKind::Budget,
            JsonDecodeErrorSource::EmptyInput { .. } => JsonDecodeErrorKind::EmptyInput,
            JsonDecodeErrorSource::InvalidUtf8 { .. } => JsonDecodeErrorKind::InvalidUtf8,
            JsonDecodeErrorSource::InvalidJson { .. } => JsonDecodeErrorKind::InvalidJson,
            JsonDecodeErrorSource::UnexpectedTopLevel { .. } => JsonDecodeErrorKind::UnexpectedTopLevel,
            JsonDecodeErrorSource::Deserialize { .. } => JsonDecodeErrorKind::Deserialize,
        }
    }

    /// Returns the safe reason for a unique-key intermediate-tree failure.
    ///
    /// Returns `Some(reason)` when unique-key tree construction failed because
    /// of a duplicate key or a defensive unrepresentable admitted number.
    /// The legacy depth-limit reason remains for source compatibility, but the
    /// shared builder has no fixed container cap and configured depth failures
    /// are reported as budget errors. Returns `None` for lexical, input,
    /// budget, and target-deserialization
    /// failures. The reason remains available under redacted diagnostics and
    /// contains no input-derived text. Read it before consuming the error with
    /// [`Self::into_source`].
    ///
    /// # Examples
    ///
    /// ```
    /// use qubit_json::decode::{JsonDecoder, JsonMaterializationErrorReason};
    /// use serde_json::Value;
    ///
    /// let mut decoder = JsonDecoder::unlimited();
    /// let error = decoder
    ///     .decode_unique_str::<Value>(r#"{"id":1,"id":2}"#)
    ///     .expect_err("duplicate keys must be rejected");
    /// assert_eq!(
    ///     error.materialization_error_reason(),
    ///     Some(JsonMaterializationErrorReason::DuplicateKey),
    /// );
    /// ```
    #[inline(always)]
    pub const fn materialization_error_reason(&self) -> Option<JsonMaterializationErrorReason> {
        self.materialization_reason
    }

    /// Returns the semantic stage that produced the failure.
    ///
    /// # Returns
    ///
    /// The pipeline stage at which the failure was recorded.
    #[must_use]
    #[inline(always)]
    pub const fn stage(&self) -> JsonDecodeStage {
        match self.failure {
            JsonDecodeErrorSource::Budget { stage, .. } | JsonDecodeErrorSource::EmptyInput { stage, .. } => stage,
            JsonDecodeErrorSource::Read { .. } => JsonDecodeStage::Input,
            JsonDecodeErrorSource::InvalidUtf8 { .. } => JsonDecodeStage::DecodeText,
            JsonDecodeErrorSource::InvalidJson { .. } => JsonDecodeStage::Parse,
            JsonDecodeErrorSource::UnexpectedTopLevel { .. } => JsonDecodeStage::TopLevelCheck,
            JsonDecodeErrorSource::Deserialize { .. } => JsonDecodeStage::Deserialize,
        }
    }

    /// Returns the diagnostic policy applied while constructing this error.
    ///
    /// # Returns
    ///
    /// The policy that determines whether input-derived details are retained.
    #[must_use]
    #[inline(always)]
    pub const fn diagnostic_policy(&self) -> DiagnosticPolicy {
        self.diagnostic_policy
    }

    /// Returns the raw input length observed at the decoding boundary.
    ///
    /// For slice-based entry points, this is the complete input slice length,
    /// including when input admission rejects the slice before processing it.
    /// For `decode_input`, this is the length of the prefix read and retained
    /// before the error; a byte consumed only to probe past the input budget is
    /// excluded. The value therefore does not universally represent bytes
    /// charged to the budget or the session's cumulative input usage.
    ///
    /// # Returns
    ///
    /// The raw input length observed for the input that caused this error.
    #[must_use]
    #[inline(always)]
    pub const fn raw_input_bytes(&self) -> usize {
        match self.failure {
            JsonDecodeErrorSource::Read { raw_input_bytes, .. }
            | JsonDecodeErrorSource::Budget { raw_input_bytes, .. }
            | JsonDecodeErrorSource::EmptyInput { raw_input_bytes, .. }
            | JsonDecodeErrorSource::InvalidUtf8 { raw_input_bytes, .. }
            | JsonDecodeErrorSource::InvalidJson { raw_input_bytes, .. }
            | JsonDecodeErrorSource::UnexpectedTopLevel { raw_input_bytes, .. }
            | JsonDecodeErrorSource::Deserialize { raw_input_bytes, .. } => raw_input_bytes,
        }
    }

    /// Returns the predicted normalized text length when it is available.
    ///
    /// A value may be present even when a budget rejected the input before
    /// normalized text was allocated or rewritten. This reports a target
    /// length, not proof that a normalized document was produced or charged.
    ///
    /// # Returns
    ///
    /// `Some(length)` when normalization determined a target length, or
    /// `None` when the failure occurred before that length was available.
    #[inline(always)]
    pub const fn normalized_input_bytes(&self) -> Option<usize> {
        match self.failure {
            JsonDecodeErrorSource::Budget {
                normalized_input_bytes, ..
            }
            | JsonDecodeErrorSource::EmptyInput {
                normalized_input_bytes, ..
            }
            | JsonDecodeErrorSource::InvalidJson {
                normalized_input_bytes, ..
            }
            | JsonDecodeErrorSource::UnexpectedTopLevel {
                normalized_input_bytes, ..
            }
            | JsonDecodeErrorSource::Deserialize {
                normalized_input_bytes, ..
            } => normalized_input_bytes,
            JsonDecodeErrorSource::InvalidUtf8 { .. } | JsonDecodeErrorSource::Read { .. } => None,
        }
    }

    /// Returns the standard I/O error category for a read failure.
    ///
    /// # Returns
    ///
    /// `Some(kind)` for a read failure, or `None` for other failure kinds.
    #[inline(always)]
    pub const fn read_error_kind(&self) -> Option<io::ErrorKind> {
        match self.failure {
            JsonDecodeErrorSource::Read { kind, .. } => Some(kind),
            _ => None,
        }
    }

    /// Returns the retained original I/O error for detailed read diagnostics.
    ///
    /// # Returns
    ///
    /// The original read error when detailed diagnostics retained it, or `None`
    /// when the error is not a read failure or its source was not retained.
    #[inline(always)]
    pub fn read_error(&self) -> Option<&io::Error> {
        match &self.failure {
            JsonDecodeErrorSource::Read {
                source: Some(source), ..
            } => Some(source.as_ref()),
            _ => None,
        }
    }

    /// Returns the one-based error line when available.
    ///
    /// Invalid-JSON coordinates come from the lexical scanner. Deserialize
    /// coordinates preserve `serde_json`'s one-based line values, including
    /// unique-key materialization errors. For a deserialize error, a backend
    /// line of zero is reported as `None`.
    ///
    /// # Returns
    ///
    /// `Some(line)` for failures with source coordinates, otherwise `None`.
    #[inline(always)]
    pub const fn line(&self) -> Option<usize> {
        match &self.failure {
            JsonDecodeErrorSource::InvalidJson { syntax, .. } => Some(syntax.line()),
            JsonDecodeErrorSource::Deserialize { line, .. } if *line > 0 => Some(*line),
            _ => None,
        }
    }

    /// Returns the one-based error column when available.
    ///
    /// Invalid-JSON columns count UTF-8 characters, while deserialize columns
    /// preserve `serde_json`'s byte-based column. Unique-key materialization
    /// columns count bytes before the offending token, with only LF starting a
    /// new line. For a deserialize error, a backend column of zero is reported
    /// as `None`.
    ///
    /// # Returns
    ///
    /// `Some(column)` for failures with source coordinates, otherwise `None`.
    #[inline(always)]
    pub const fn column(&self) -> Option<usize> {
        match &self.failure {
            JsonDecodeErrorSource::InvalidJson { syntax, .. } => Some(syntax.column()),
            JsonDecodeErrorSource::Deserialize { column, .. } if *column > 0 => Some(*column),
            _ => None,
        }
    }

    /// Returns the structured syntax failure for invalid JSON.
    ///
    /// # Returns
    ///
    /// A borrowed syntax error when parsing failed, otherwise `None`.
    #[inline(always)]
    pub const fn syntax_error(&self) -> Option<&JsonSyntaxError> {
        match &self.failure {
            JsonDecodeErrorSource::InvalidJson { syntax, .. } => Some(syntax),
            _ => None,
        }
    }

    /// Returns the complete measured-budget failure when present.
    ///
    /// # Returns
    ///
    /// A borrowed budget error when resource accounting rejected the input,
    /// otherwise `None`.
    #[inline(always)]
    pub const fn budget_error(&self) -> Option<&MeasuredBudgetError<R, Q>> {
        match &self.failure {
            JsonDecodeErrorSource::Budget { source, .. } => Some(source),
            _ => None,
        }
    }

    /// Returns the valid UTF-8 prefix length for invalid byte input.
    ///
    /// # Returns
    ///
    /// `Some(bytes)` for an invalid UTF-8 failure, or `None` for other failure
    /// kinds.
    #[inline(always)]
    pub const fn utf8_valid_up_to(&self) -> Option<usize> {
        match self.failure {
            JsonDecodeErrorSource::InvalidUtf8 { valid_up_to, .. } => Some(valid_up_to),
            _ => None,
        }
    }

    /// Returns the invalid UTF-8 sequence length when known.
    ///
    /// # Returns
    ///
    /// The length of the invalid sequence when the decoder can determine it,
    /// otherwise `None`.
    #[inline(always)]
    pub const fn utf8_error_len(&self) -> Option<usize> {
        match self.failure {
            JsonDecodeErrorSource::InvalidUtf8 { error_len, .. } => error_len,
            _ => None,
        }
    }

    /// Returns the expected top-level kind for a constrained decode failure.
    ///
    /// # Returns
    ///
    /// The required root kind when a constrained operation failed, otherwise
    /// `None`.
    #[inline(always)]
    pub const fn expected_top_level(&self) -> Option<JsonRootKind> {
        match self.failure {
            JsonDecodeErrorSource::UnexpectedTopLevel { expected, .. } => Some(expected),
            _ => None,
        }
    }

    /// Returns the observed top-level kind for a constrained decode failure.
    ///
    /// # Returns
    ///
    /// The root kind observed in the valid document, otherwise `None`.
    #[inline(always)]
    pub const fn actual_top_level(&self) -> Option<JsonRootKind> {
        match self.failure {
            JsonDecodeErrorSource::UnexpectedTopLevel { actual, .. } => Some(actual),
            _ => None,
        }
    }

    /// Consumes this error and returns its owned operation-level source.
    ///
    /// The materialization reason returned by
    /// [`Self::materialization_error_reason`] is stored separately and is not
    /// included in the returned source. Read it before consuming this error.
    /// Input-derived third-party sources remain present only when the decoder
    /// used [`DiagnosticPolicy::Detailed`].
    ///
    /// # Returns
    ///
    /// The owned budget, input, syntax, top-level, or deserialization source
    /// retained by this error. Any materialization reason is not returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use qubit_json::decode::{
    ///     JsonDecodeErrorSource, JsonDecoder, JsonMaterializationErrorReason,
    /// };
    ///
    /// let error = JsonDecoder::unlimited()
    ///     .decode_value_str(r#"{"id":1,"id":2}"#)
    ///     .expect_err("duplicate keys must be rejected");
    /// let reason = error.materialization_error_reason();
    /// let source = error.into_source();
    ///
    /// assert_eq!(reason, Some(JsonMaterializationErrorReason::DuplicateKey));
    /// assert!(matches!(source, JsonDecodeErrorSource::Deserialize { .. }));
    /// ```
    #[inline(always)]
    pub fn into_source(self) -> JsonDecodeErrorSource<R, Q> {
        self.failure
    }
}

impl<R, Q> fmt::Debug for JsonDecodeError<R, Q>
where
    R: fmt::Debug,
    Q: Copy + fmt::Debug,
{
    /// Formats structured diagnostics retained under the active policy.
    ///
    /// # Parameters
    ///
    /// * `formatter` - Destination that receives the debug representation.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the structured diagnostic has been written.
    ///
    /// # Errors
    ///
    /// Returns the formatter error if writing the diagnostic fails.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("JsonDecodeError")
            .field("diagnostic_policy", &self.diagnostic_policy)
            .field("materialization_reason", &self.materialization_reason)
            .field("failure", &self.failure)
            .finish()
    }
}

impl<R, Q> fmt::Display for JsonDecodeError<R, Q>
where
    R: fmt::Debug,
    Q: ResourceQuantity,
{
    /// Formats a privacy-safe or detailed message according to the policy.
    ///
    /// # Parameters
    ///
    /// * `formatter` - Destination that receives the display message.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the policy-appropriate message has been written.
    ///
    /// # Errors
    ///
    /// Returns the formatter error if writing the message fails.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.failure {
            JsonDecodeErrorSource::Read { kind, .. } => {
                write!(formatter, "JSON input read failed ({kind:?})")
            }
            JsonDecodeErrorSource::Budget { source, .. } => {
                write!(formatter, "JSON resource budget rejected input: {source}")
            }
            JsonDecodeErrorSource::EmptyInput { .. } => formatter.write_str("JSON input is empty after normalization"),
            JsonDecodeErrorSource::InvalidUtf8 { source, .. } => match source {
                Some(source) => write!(formatter, "Failed to decode JSON input as UTF-8: {source}"),
                None => formatter.write_str("Failed to decode JSON input as UTF-8"),
            },
            JsonDecodeErrorSource::InvalidJson { syntax, source, .. } => match source {
                Some(source) => {
                    write!(formatter, "Failed to parse JSON: {source}")
                }
                None => write!(formatter, "Failed to parse JSON: {syntax}"),
            },
            JsonDecodeErrorSource::UnexpectedTopLevel { expected, actual, .. } => {
                write!(
                    formatter,
                    "Unexpected JSON top-level type: expected {expected}, got {actual}"
                )
            }
            JsonDecodeErrorSource::Deserialize {
                normalized_input_bytes,
                line,
                column,
                source,
                ..
            } => match source {
                Some(source) => write!(formatter, "Failed to deserialize JSON value: {source}"),
                None if *line == 0 || *column == 0 => formatter.write_str("Failed to deserialize JSON value"),
                None if normalized_input_bytes.is_some() => write!(
                    formatter,
                    "Failed to deserialize JSON value at normalized line {line} column {column}"
                ),
                None => write!(
                    formatter,
                    "Failed to deserialize JSON value at line {line} column {column}"
                ),
            },
        }
    }
}

impl<R, Q> Error for JsonDecodeError<R, Q>
where
    R: fmt::Debug + 'static,
    Q: ResourceQuantity + 'static,
{
    /// Returns budget sources unconditionally and input-derived sources only
    /// when detailed diagnostics retained them.
    ///
    /// # Returns
    ///
    /// The retained source error, or `None` when this failure has no source or
    /// input-derived diagnostics were redacted.
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match &self.failure {
            JsonDecodeErrorSource::Read {
                source: Some(source), ..
            } => Some(source.as_ref()),
            JsonDecodeErrorSource::Budget { source, .. } => Some(source),
            JsonDecodeErrorSource::InvalidUtf8 {
                source: Some(source), ..
            } => Some(source),
            JsonDecodeErrorSource::InvalidJson {
                source: Some(source), ..
            } => Some(source.as_ref()),
            JsonDecodeErrorSource::Deserialize {
                source: Some(source), ..
            } => Some(source.as_ref()),
            _ => None,
        }
    }
}