Skip to main content

qubit_json/decode/
json_decode_error.rs

1// =============================================================================
2//    Copyright (c) 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Defines the shared error returned by all JSON decoding facades.
9
10use std::error::Error;
11use std::fmt;
12use std::io;
13use std::sync::Arc;
14
15use qubit_budget::MeasuredBudgetError;
16use qubit_budget::ResourceQuantity;
17use qubit_budget::json::JsonResource;
18use serde_json::Error as JsonError;
19
20use super::DiagnosticPolicy;
21use super::JsonDecodeErrorKind;
22use super::JsonDecodeErrorSource;
23use super::JsonDecodeStage;
24use super::JsonMaterializationErrorReason;
25use super::JsonRootKind;
26use super::JsonSyntaxError;
27use crate::lexical::JsonLexicalFailure;
28
29/// Failure produced by either strict or normalizing JSON decoding.
30///
31/// Internal variants are private so callers branch through stable semantic
32/// accessors rather than depending on scanner, normalizer, or Serde details.
33///
34/// # Type Parameters
35///
36/// * `R` - Resource identity attached to budget failures.
37/// * `Q` - Quantity representation attached to budget failures.
38///
39/// # Examples
40///
41/// ```
42/// use qubit_json::decode::{JsonDecodeError, JsonDecodeErrorKind, JsonDecoder};
43/// use serde_json::Value;
44///
45/// let mut decoder = JsonDecoder::unlimited();
46/// let error: JsonDecodeError = decoder
47///     .decode_str::<Value>("")
48///     .expect_err("empty input must be rejected");
49/// assert_eq!(error.kind(), JsonDecodeErrorKind::InvalidJson);
50/// ```
51#[must_use]
52#[derive(Clone)]
53pub struct JsonDecodeError<R = JsonResource, Q = usize>
54where
55    Q: Copy + fmt::Debug,
56{
57    /// Policy controlling input-derived source retention.
58    diagnostic_policy: DiagnosticPolicy,
59    /// Safe reason for unique-key or bounded last-wins value materialization.
60    materialization_reason: Option<JsonMaterializationErrorReason>,
61    /// Mutually exclusive structured failure.
62    failure: JsonDecodeErrorSource<R, Q>,
63}
64
65impl<R, Q> JsonDecodeError<R, Q>
66where
67    Q: Copy + fmt::Debug,
68{
69    /// Creates a stream-read failure and conditionally retains its source.
70    ///
71    /// # Parameters
72    ///
73    /// * `source` - I/O error produced while reading the input.
74    /// * `raw_input_bytes` - Number of input bytes read before the failure.
75    /// * `diagnostic_policy` - Whether to retain the original error details.
76    ///
77    /// # Returns
78    ///
79    /// A read failure containing the I/O category and, under detailed
80    /// diagnostics, the original error.
81    pub(crate) fn read(source: io::Error, raw_input_bytes: usize, diagnostic_policy: DiagnosticPolicy) -> Self {
82        let kind = source.kind();
83        let source = (diagnostic_policy == DiagnosticPolicy::Detailed).then(|| Arc::new(source));
84        Self {
85            diagnostic_policy,
86            materialization_reason: None,
87            failure: JsonDecodeErrorSource::Read {
88                raw_input_bytes,
89                kind,
90                source,
91            },
92        }
93    }
94
95    /// Creates a measured-budget failure at a semantic stage.
96    ///
97    /// # Parameters
98    ///
99    /// * `source` - Resource measurement that exceeded its budget.
100    /// * `stage` - Decode stage where the budget was exceeded.
101    /// * `raw_input_bytes` - Original input length in bytes.
102    /// * `normalized_input_bytes` - Normalized input length, when available.
103    /// * `diagnostic_policy` - Policy controlling retained input details.
104    ///
105    /// # Returns
106    ///
107    /// A budget failure retaining the measured resource error and decode
108    /// stage.
109    pub(crate) const fn budget(
110        source: MeasuredBudgetError<R, Q>,
111        stage: JsonDecodeStage,
112        raw_input_bytes: usize,
113        normalized_input_bytes: Option<usize>,
114        diagnostic_policy: DiagnosticPolicy,
115    ) -> Self {
116        Self {
117            diagnostic_policy,
118            materialization_reason: None,
119            failure: JsonDecodeErrorSource::Budget {
120                stage,
121                raw_input_bytes,
122                normalized_input_bytes,
123                source,
124            },
125        }
126    }
127
128    /// Creates an empty-input failure at a semantic stage.
129    ///
130    /// # Parameters
131    ///
132    /// * `stage` - Decode stage where the empty input was detected.
133    /// * `raw_input_bytes` - Original input length in bytes.
134    /// * `normalized_input_bytes` - Normalized input length, when available.
135    /// * `diagnostic_policy` - Policy controlling retained input details.
136    ///
137    /// # Returns
138    ///
139    /// An empty-input failure retaining the stage and input lengths.
140    pub(crate) const fn empty_input(
141        stage: JsonDecodeStage,
142        raw_input_bytes: usize,
143        normalized_input_bytes: Option<usize>,
144        diagnostic_policy: DiagnosticPolicy,
145    ) -> Self {
146        Self {
147            diagnostic_policy,
148            materialization_reason: None,
149            failure: JsonDecodeErrorSource::EmptyInput {
150                stage,
151                raw_input_bytes,
152                normalized_input_bytes,
153            },
154        }
155    }
156
157    /// Creates an invalid-UTF-8 failure and conditionally retains its source.
158    ///
159    /// # Parameters
160    ///
161    /// * `source` - UTF-8 validation failure for the input bytes.
162    /// * `raw_input_bytes` - Original input length in bytes.
163    /// * `diagnostic_policy` - Whether to retain the original error details.
164    ///
165    /// # Returns
166    ///
167    /// An invalid-UTF-8 failure retaining the invalid byte position and, under
168    /// detailed diagnostics, the original validation error.
169    pub(crate) fn invalid_utf8(
170        source: std::str::Utf8Error,
171        raw_input_bytes: usize,
172        diagnostic_policy: DiagnosticPolicy,
173    ) -> Self {
174        let valid_up_to = source.valid_up_to();
175        let error_len = source.error_len();
176        let source = (diagnostic_policy == DiagnosticPolicy::Detailed).then_some(source);
177        Self {
178            diagnostic_policy,
179            materialization_reason: None,
180            failure: JsonDecodeErrorSource::InvalidUtf8 {
181                raw_input_bytes,
182                valid_up_to,
183                error_len,
184                source,
185            },
186        }
187    }
188
189    /// Creates a stable invalid-JSON failure from lexical admission.
190    ///
191    /// # Parameters
192    ///
193    /// * `syntax_source` - Lexical failure with stable syntax details.
194    /// * `detailed_source` - Optional parser error retained for detailed
195    ///   diagnostics.
196    /// * `raw_input_bytes` - Original input length in bytes.
197    /// * `normalized_input_bytes` - Normalized input length, when available.
198    /// * `diagnostic_policy` - Policy controlling retained input details.
199    ///
200    /// # Returns
201    ///
202    /// An invalid-JSON failure containing stable syntax details and the
203    /// optional detailed parser source.
204    pub(crate) fn invalid_json(
205        syntax_source: JsonLexicalFailure,
206        detailed_source: Option<Arc<dyn Error + Send + Sync>>,
207        raw_input_bytes: usize,
208        normalized_input_bytes: Option<usize>,
209        diagnostic_policy: DiagnosticPolicy,
210    ) -> Self {
211        Self {
212            diagnostic_policy,
213            materialization_reason: None,
214            failure: JsonDecodeErrorSource::InvalidJson {
215                raw_input_bytes,
216                normalized_input_bytes,
217                syntax: JsonSyntaxError::from_lexical(syntax_source),
218                source: detailed_source,
219            },
220        }
221    }
222
223    /// Creates an unexpected-top-level failure.
224    ///
225    /// # Parameters
226    ///
227    /// * `expected` - Required top-level JSON kind.
228    /// * `actual` - Observed top-level JSON kind.
229    /// * `raw_input_bytes` - Original input length in bytes.
230    /// * `normalized_input_bytes` - Normalized input length, when available.
231    /// * `diagnostic_policy` - Policy controlling retained input details.
232    ///
233    /// # Returns
234    ///
235    /// A top-level-kind failure retaining the expected and observed kinds.
236    pub(crate) const fn unexpected_top_level(
237        expected: JsonRootKind,
238        actual: JsonRootKind,
239        raw_input_bytes: usize,
240        normalized_input_bytes: Option<usize>,
241        diagnostic_policy: DiagnosticPolicy,
242    ) -> Self {
243        Self {
244            diagnostic_policy,
245            materialization_reason: None,
246            failure: JsonDecodeErrorSource::UnexpectedTopLevel {
247                raw_input_bytes,
248                normalized_input_bytes,
249                expected,
250                actual,
251            },
252        }
253    }
254
255    /// Adapts a captured Serde error for an already-admitted JSON document.
256    ///
257    /// This constructor records the original input length and preserves the
258    /// Serde location and diagnostic policy without parsing the JSON again.
259    /// The normalized input length is unavailable for this adaptation.
260    ///
261    /// # Parameters
262    ///
263    /// * `source` - Serde error produced while deserializing the admitted
264    ///   document.
265    /// * `raw_input_bytes` - Length of the original input in bytes.
266    /// * `diagnostic_policy` - Whether to retain the original Serde error.
267    ///
268    /// # Returns
269    ///
270    /// A deserialization failure with the Serde error's line and column.
271    pub fn from_deserialization_error(
272        source: JsonError,
273        raw_input_bytes: usize,
274        diagnostic_policy: DiagnosticPolicy,
275    ) -> Self {
276        Self::deserialize(source, raw_input_bytes, None, diagnostic_policy)
277    }
278
279    /// Creates a target-deserialization failure and conditionally retains its
280    /// input-derived source.
281    ///
282    /// # Parameters
283    ///
284    /// * `source` - Serde error produced while materializing the target value.
285    /// * `raw_input_bytes` - Original input length in bytes.
286    /// * `normalized_input_bytes` - Normalized input length, when available.
287    /// * `diagnostic_policy` - Whether to retain the original error details.
288    ///
289    /// # Returns
290    ///
291    /// A deserialization failure retaining the source location and, under
292    /// detailed diagnostics, the original Serde error.
293    pub(crate) fn deserialize(
294        source: JsonError,
295        raw_input_bytes: usize,
296        normalized_input_bytes: Option<usize>,
297        diagnostic_policy: DiagnosticPolicy,
298    ) -> Self {
299        let line = source.line();
300        let column = source.column();
301        let source =
302            (diagnostic_policy == DiagnosticPolicy::Detailed).then(|| Arc::new(source) as Arc<dyn Error + Send + Sync>);
303        Self {
304            diagnostic_policy,
305            materialization_reason: None,
306            failure: JsonDecodeErrorSource::Deserialize {
307                raw_input_bytes,
308                normalized_input_bytes,
309                line,
310                column,
311                source,
312            },
313        }
314    }
315
316    /// Creates a deserialization failure with byte-based source coordinates.
317    ///
318    /// This is used when a lexical limit is detected at a source position
319    /// without asking Serde to deserialize the full document.
320    ///
321    /// # Parameters
322    ///
323    /// * `source` - Fixed deserialization diagnostic retained under detailed
324    ///   diagnostics; its text should not include input-derived values.
325    /// * `reason` - Safe structured reason for the materialization failure.
326    /// * `raw_input_bytes` - Original input length in bytes.
327    /// * `line` - One-based line containing the rejected token.
328    /// * `column` - One-based byte column of the rejected token.
329    /// * `diagnostic_policy` - Whether to retain the source error.
330    ///
331    /// # Returns
332    ///
333    /// A deserialization error carrying the supplied source coordinates.
334    pub(crate) fn deserialize_at(
335        source: JsonError,
336        reason: JsonMaterializationErrorReason,
337        raw_input_bytes: usize,
338        line: usize,
339        column: usize,
340        diagnostic_policy: DiagnosticPolicy,
341    ) -> Self {
342        let source =
343            (diagnostic_policy == DiagnosticPolicy::Detailed).then(|| Arc::new(source) as Arc<dyn Error + Send + Sync>);
344        Self {
345            diagnostic_policy,
346            materialization_reason: Some(reason),
347            failure: JsonDecodeErrorSource::Deserialize {
348                raw_input_bytes,
349                normalized_input_bytes: None,
350                line,
351                column,
352                source,
353            },
354        }
355    }
356
357    /// Creates a unique-key materialization failure with a safe subreason.
358    ///
359    /// # Parameters
360    ///
361    /// * `source` - Serde error produced while constructing the unique-key
362    ///   tree.
363    /// * `reason` - Safe materialization failure category.
364    /// * `raw_input_bytes` - Original input length in bytes.
365    /// * `diagnostic_policy` - Policy controlling retained input details.
366    ///
367    /// # Returns
368    ///
369    /// A deserialization failure annotated with the safe materialization
370    /// reason.
371    pub(crate) fn materialization(
372        source: JsonError,
373        reason: JsonMaterializationErrorReason,
374        raw_input_bytes: usize,
375        diagnostic_policy: DiagnosticPolicy,
376    ) -> Self {
377        let mut error = Self::deserialize(source, raw_input_bytes, None, diagnostic_policy);
378        error.materialization_reason = Some(reason);
379        error
380    }
381
382    /// Returns the stable failure category.
383    ///
384    /// # Returns
385    ///
386    /// The category describing which kind of decode operation failed.
387    #[must_use = "inspect or propagate the underlying decode error source"]
388    #[inline(always)]
389    pub const fn kind(&self) -> JsonDecodeErrorKind {
390        match self.failure {
391            JsonDecodeErrorSource::Read { .. } => JsonDecodeErrorKind::Read,
392            JsonDecodeErrorSource::Budget { .. } => JsonDecodeErrorKind::Budget,
393            JsonDecodeErrorSource::EmptyInput { .. } => JsonDecodeErrorKind::EmptyInput,
394            JsonDecodeErrorSource::InvalidUtf8 { .. } => JsonDecodeErrorKind::InvalidUtf8,
395            JsonDecodeErrorSource::InvalidJson { .. } => JsonDecodeErrorKind::InvalidJson,
396            JsonDecodeErrorSource::UnexpectedTopLevel { .. } => JsonDecodeErrorKind::UnexpectedTopLevel,
397            JsonDecodeErrorSource::Deserialize { .. } => JsonDecodeErrorKind::Deserialize,
398        }
399    }
400
401    /// Returns the safe reason for a JSON value materialization failure.
402    ///
403    /// Returns `Some(reason)` for duplicate keys, unrepresentable admitted
404    /// numbers, or a bounded last-wins container limit. The legacy depth-limit
405    /// reason remains for source compatibility; configured structural depth
406    /// failures are still reported as budget errors. Returns `None` for
407    /// lexical, input, budget, and target-deserialization failures. The reason
408    /// remains available under redacted diagnostics and
409    /// contains no input-derived text. Read it before consuming the error with
410    /// [`Self::into_source`].
411    ///
412    /// # Examples
413    ///
414    /// ```
415    /// use qubit_json::decode::{JsonDecoder, JsonMaterializationErrorReason};
416    /// use serde_json::Value;
417    ///
418    /// let mut decoder = JsonDecoder::unlimited();
419    /// let error = decoder
420    ///     .decode_unique_str::<Value>(r#"{"id":1,"id":2}"#)
421    ///     .expect_err("duplicate keys must be rejected");
422    /// assert_eq!(
423    ///     error.materialization_error_reason(),
424    ///     Some(JsonMaterializationErrorReason::DuplicateKey),
425    /// );
426    /// ```
427    #[inline(always)]
428    pub const fn materialization_error_reason(&self) -> Option<JsonMaterializationErrorReason> {
429        self.materialization_reason
430    }
431
432    /// Returns the semantic stage that produced the failure.
433    ///
434    /// # Returns
435    ///
436    /// The pipeline stage at which the failure was recorded.
437    #[must_use]
438    #[inline(always)]
439    pub const fn stage(&self) -> JsonDecodeStage {
440        match self.failure {
441            JsonDecodeErrorSource::Budget { stage, .. } | JsonDecodeErrorSource::EmptyInput { stage, .. } => stage,
442            JsonDecodeErrorSource::Read { .. } => JsonDecodeStage::Input,
443            JsonDecodeErrorSource::InvalidUtf8 { .. } => JsonDecodeStage::DecodeText,
444            JsonDecodeErrorSource::InvalidJson { .. } => JsonDecodeStage::Parse,
445            JsonDecodeErrorSource::UnexpectedTopLevel { .. } => JsonDecodeStage::TopLevelCheck,
446            JsonDecodeErrorSource::Deserialize { .. } => JsonDecodeStage::Deserialize,
447        }
448    }
449
450    /// Returns the diagnostic policy applied while constructing this error.
451    ///
452    /// # Returns
453    ///
454    /// The policy that determines whether input-derived details are retained.
455    #[must_use]
456    #[inline(always)]
457    pub const fn diagnostic_policy(&self) -> DiagnosticPolicy {
458        self.diagnostic_policy
459    }
460
461    /// Returns the raw input length observed at the decoding boundary.
462    ///
463    /// For slice-based entry points, this is the complete input slice length,
464    /// including when input admission rejects the slice before processing it.
465    /// For `decode_input`, this is the length of the prefix read and retained
466    /// before the error; a byte consumed only to probe past the input budget is
467    /// excluded. The value therefore does not universally represent bytes
468    /// charged to the budget or the session's cumulative input usage.
469    ///
470    /// # Returns
471    ///
472    /// The raw input length observed for the input that caused this error.
473    #[must_use]
474    #[inline(always)]
475    pub const fn raw_input_bytes(&self) -> usize {
476        match self.failure {
477            JsonDecodeErrorSource::Read { raw_input_bytes, .. }
478            | JsonDecodeErrorSource::Budget { raw_input_bytes, .. }
479            | JsonDecodeErrorSource::EmptyInput { raw_input_bytes, .. }
480            | JsonDecodeErrorSource::InvalidUtf8 { raw_input_bytes, .. }
481            | JsonDecodeErrorSource::InvalidJson { raw_input_bytes, .. }
482            | JsonDecodeErrorSource::UnexpectedTopLevel { raw_input_bytes, .. }
483            | JsonDecodeErrorSource::Deserialize { raw_input_bytes, .. } => raw_input_bytes,
484        }
485    }
486
487    /// Returns the predicted normalized text length when it is available.
488    ///
489    /// A value may be present even when a budget rejected the input before
490    /// normalized text was allocated or rewritten. This reports a target
491    /// length, not proof that a normalized document was produced or charged.
492    ///
493    /// # Returns
494    ///
495    /// `Some(length)` when normalization determined a target length, or
496    /// `None` when the failure occurred before that length was available.
497    #[inline(always)]
498    pub const fn normalized_input_bytes(&self) -> Option<usize> {
499        match self.failure {
500            JsonDecodeErrorSource::Budget {
501                normalized_input_bytes, ..
502            }
503            | JsonDecodeErrorSource::EmptyInput {
504                normalized_input_bytes, ..
505            }
506            | JsonDecodeErrorSource::InvalidJson {
507                normalized_input_bytes, ..
508            }
509            | JsonDecodeErrorSource::UnexpectedTopLevel {
510                normalized_input_bytes, ..
511            }
512            | JsonDecodeErrorSource::Deserialize {
513                normalized_input_bytes, ..
514            } => normalized_input_bytes,
515            JsonDecodeErrorSource::InvalidUtf8 { .. } | JsonDecodeErrorSource::Read { .. } => None,
516        }
517    }
518
519    /// Returns the standard I/O error category for a read failure.
520    ///
521    /// # Returns
522    ///
523    /// `Some(kind)` for a read failure, or `None` for other failure kinds.
524    #[inline(always)]
525    pub const fn read_error_kind(&self) -> Option<io::ErrorKind> {
526        match self.failure {
527            JsonDecodeErrorSource::Read { kind, .. } => Some(kind),
528            _ => None,
529        }
530    }
531
532    /// Returns the retained original I/O error for detailed read diagnostics.
533    ///
534    /// # Returns
535    ///
536    /// The original read error when detailed diagnostics retained it, or `None`
537    /// when the error is not a read failure or its source was not retained.
538    #[inline(always)]
539    pub fn read_error(&self) -> Option<&io::Error> {
540        match &self.failure {
541            JsonDecodeErrorSource::Read {
542                source: Some(source), ..
543            } => Some(source.as_ref()),
544            _ => None,
545        }
546    }
547
548    /// Returns the one-based error line when available.
549    ///
550    /// Invalid-JSON coordinates come from the lexical scanner. Deserialize
551    /// coordinates preserve `serde_json`'s one-based line values, including
552    /// unique-key and bounded last-wins materialization errors. For a
553    /// deserialize error, a backend line of zero is reported as `None`.
554    ///
555    /// # Returns
556    ///
557    /// `Some(line)` for failures with source coordinates, otherwise `None`.
558    #[inline(always)]
559    pub const fn line(&self) -> Option<usize> {
560        match &self.failure {
561            JsonDecodeErrorSource::InvalidJson { syntax, .. } => Some(syntax.line()),
562            JsonDecodeErrorSource::Deserialize { line, .. } if *line > 0 => Some(*line),
563            _ => None,
564        }
565    }
566
567    /// Returns the one-based error column when available.
568    ///
569    /// Invalid-JSON columns count UTF-8 characters, while deserialize columns
570    /// preserve the Serde backend's column convention. Unique-key and bounded
571    /// last-wins materialization columns count bytes before the offending
572    /// token, with only LF starting a new line. For a deserialize error, a
573    /// backend column of zero is reported as `None`.
574    ///
575    /// # Returns
576    ///
577    /// `Some(column)` for failures with source coordinates, otherwise `None`.
578    #[inline(always)]
579    pub const fn column(&self) -> Option<usize> {
580        match &self.failure {
581            JsonDecodeErrorSource::InvalidJson { syntax, .. } => Some(syntax.column()),
582            JsonDecodeErrorSource::Deserialize { column, .. } if *column > 0 => Some(*column),
583            _ => None,
584        }
585    }
586
587    /// Returns the structured syntax failure for invalid JSON.
588    ///
589    /// # Returns
590    ///
591    /// A borrowed syntax error when parsing failed, otherwise `None`.
592    #[inline(always)]
593    pub const fn syntax_error(&self) -> Option<&JsonSyntaxError> {
594        match &self.failure {
595            JsonDecodeErrorSource::InvalidJson { syntax, .. } => Some(syntax),
596            _ => None,
597        }
598    }
599
600    /// Returns the complete measured-budget failure when present.
601    ///
602    /// # Returns
603    ///
604    /// A borrowed budget error when resource accounting rejected the input,
605    /// otherwise `None`.
606    #[inline(always)]
607    pub const fn budget_error(&self) -> Option<&MeasuredBudgetError<R, Q>> {
608        match &self.failure {
609            JsonDecodeErrorSource::Budget { source, .. } => Some(source),
610            _ => None,
611        }
612    }
613
614    /// Returns the valid UTF-8 prefix length for invalid byte input.
615    ///
616    /// # Returns
617    ///
618    /// `Some(bytes)` for an invalid UTF-8 failure, or `None` for other failure
619    /// kinds.
620    #[inline(always)]
621    pub const fn utf8_valid_up_to(&self) -> Option<usize> {
622        match self.failure {
623            JsonDecodeErrorSource::InvalidUtf8 { valid_up_to, .. } => Some(valid_up_to),
624            _ => None,
625        }
626    }
627
628    /// Returns the invalid UTF-8 sequence length when known.
629    ///
630    /// # Returns
631    ///
632    /// The length of the invalid sequence when the decoder can determine it,
633    /// otherwise `None`.
634    #[inline(always)]
635    pub const fn utf8_error_len(&self) -> Option<usize> {
636        match self.failure {
637            JsonDecodeErrorSource::InvalidUtf8 { error_len, .. } => error_len,
638            _ => None,
639        }
640    }
641
642    /// Returns the expected top-level kind for a constrained decode failure.
643    ///
644    /// # Returns
645    ///
646    /// The required root kind when a constrained operation failed, otherwise
647    /// `None`.
648    #[inline(always)]
649    pub const fn expected_top_level(&self) -> Option<JsonRootKind> {
650        match self.failure {
651            JsonDecodeErrorSource::UnexpectedTopLevel { expected, .. } => Some(expected),
652            _ => None,
653        }
654    }
655
656    /// Returns the observed top-level kind for a constrained decode failure.
657    ///
658    /// # Returns
659    ///
660    /// The root kind observed in the valid document, otherwise `None`.
661    #[inline(always)]
662    pub const fn actual_top_level(&self) -> Option<JsonRootKind> {
663        match self.failure {
664            JsonDecodeErrorSource::UnexpectedTopLevel { actual, .. } => Some(actual),
665            _ => None,
666        }
667    }
668
669    /// Consumes this error and returns its owned operation-level source.
670    ///
671    /// The materialization reason returned by
672    /// [`Self::materialization_error_reason`] is stored separately and is not
673    /// included in the returned source. Read it before consuming this error.
674    /// Input-derived third-party sources remain present only when the decoder
675    /// used [`DiagnosticPolicy::Detailed`].
676    ///
677    /// # Returns
678    ///
679    /// The owned budget, input, syntax, top-level, or deserialization source
680    /// retained by this error. Any materialization reason is not returned.
681    ///
682    /// # Examples
683    ///
684    /// ```
685    /// use qubit_json::decode::{
686    ///     JsonDecodeErrorSource, JsonDecoder, JsonMaterializationErrorReason,
687    /// };
688    ///
689    /// let error = JsonDecoder::unlimited()
690    ///     .decode_value_str(r#"{"id":1,"id":2}"#)
691    ///     .expect_err("duplicate keys must be rejected");
692    /// let reason = error.materialization_error_reason();
693    /// let source = error.into_source();
694    ///
695    /// assert_eq!(reason, Some(JsonMaterializationErrorReason::DuplicateKey));
696    /// assert!(matches!(source, JsonDecodeErrorSource::Deserialize { .. }));
697    /// ```
698    #[inline(always)]
699    pub fn into_source(self) -> JsonDecodeErrorSource<R, Q> {
700        self.failure
701    }
702}
703
704impl<R, Q> fmt::Debug for JsonDecodeError<R, Q>
705where
706    R: fmt::Debug,
707    Q: Copy + fmt::Debug,
708{
709    /// Formats structured diagnostics retained under the active policy.
710    ///
711    /// # Parameters
712    ///
713    /// * `formatter` - Destination that receives the debug representation.
714    ///
715    /// # Returns
716    ///
717    /// `Ok(())` after the structured diagnostic has been written.
718    ///
719    /// # Errors
720    ///
721    /// Returns the formatter error if writing the diagnostic fails.
722    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
723        formatter
724            .debug_struct("JsonDecodeError")
725            .field("diagnostic_policy", &self.diagnostic_policy)
726            .field("materialization_reason", &self.materialization_reason)
727            .field("failure", &self.failure)
728            .finish()
729    }
730}
731
732impl<R, Q> fmt::Display for JsonDecodeError<R, Q>
733where
734    R: fmt::Debug,
735    Q: ResourceQuantity,
736{
737    /// Formats a privacy-safe or detailed message according to the policy.
738    ///
739    /// # Parameters
740    ///
741    /// * `formatter` - Destination that receives the display message.
742    ///
743    /// # Returns
744    ///
745    /// `Ok(())` after the policy-appropriate message has been written.
746    ///
747    /// # Errors
748    ///
749    /// Returns the formatter error if writing the message fails.
750    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
751        match &self.failure {
752            JsonDecodeErrorSource::Read { kind, .. } => {
753                write!(formatter, "JSON input read failed ({kind:?})")
754            }
755            JsonDecodeErrorSource::Budget { source, .. } => {
756                write!(formatter, "JSON resource budget rejected input: {source}")
757            }
758            JsonDecodeErrorSource::EmptyInput { .. } => formatter.write_str("JSON input is empty after normalization"),
759            JsonDecodeErrorSource::InvalidUtf8 { source, .. } => match source {
760                Some(source) => write!(formatter, "Failed to decode JSON input as UTF-8: {source}"),
761                None => formatter.write_str("Failed to decode JSON input as UTF-8"),
762            },
763            JsonDecodeErrorSource::InvalidJson { syntax, source, .. } => match source {
764                Some(source) => {
765                    write!(formatter, "Failed to parse JSON: {source}")
766                }
767                None => write!(formatter, "Failed to parse JSON: {syntax}"),
768            },
769            JsonDecodeErrorSource::UnexpectedTopLevel { expected, actual, .. } => {
770                write!(
771                    formatter,
772                    "Unexpected JSON top-level type: expected {expected}, got {actual}"
773                )
774            }
775            JsonDecodeErrorSource::Deserialize {
776                normalized_input_bytes,
777                line,
778                column,
779                source,
780                ..
781            } => match source {
782                Some(source) => write!(formatter, "Failed to deserialize JSON value: {source}"),
783                None if *line == 0 || *column == 0 => formatter.write_str("Failed to deserialize JSON value"),
784                None if normalized_input_bytes.is_some() => write!(
785                    formatter,
786                    "Failed to deserialize JSON value at normalized line {line} column {column}"
787                ),
788                None => write!(
789                    formatter,
790                    "Failed to deserialize JSON value at line {line} column {column}"
791                ),
792            },
793        }
794    }
795}
796
797impl<R, Q> Error for JsonDecodeError<R, Q>
798where
799    R: fmt::Debug + 'static,
800    Q: ResourceQuantity + 'static,
801{
802    /// Returns budget sources unconditionally and input-derived sources only
803    /// when detailed diagnostics retained them.
804    ///
805    /// # Returns
806    ///
807    /// The retained source error, or `None` when this failure has no source or
808    /// input-derived diagnostics were redacted.
809    fn source(&self) -> Option<&(dyn Error + 'static)> {
810        match &self.failure {
811            JsonDecodeErrorSource::Read {
812                source: Some(source), ..
813            } => Some(source.as_ref()),
814            JsonDecodeErrorSource::Budget { source, .. } => Some(source),
815            JsonDecodeErrorSource::InvalidUtf8 {
816                source: Some(source), ..
817            } => Some(source),
818            JsonDecodeErrorSource::InvalidJson {
819                source: Some(source), ..
820            } => Some(source.as_ref()),
821            JsonDecodeErrorSource::Deserialize {
822                source: Some(source), ..
823            } => Some(source.as_ref()),
824            _ => None,
825        }
826    }
827}