Skip to main content

qubit_json/decode/
json_decoder.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//! Stateful strict JSON decoding with caller-owned resource accounting.
9
10use qubit_budget::ResourceQuantity;
11use qubit_budget::json::JsonDecodeLimits;
12use qubit_budget::json::JsonDecodeSession;
13use qubit_budget::json::JsonResource;
14use qubit_io::ByteInput;
15use qubit_io::Input;
16use serde::Deserialize;
17use serde::de::DeserializeOwned;
18use serde::de::DeserializeSeed;
19
20use super::DiagnosticPolicy;
21use super::JsonDecodeError;
22use super::JsonDecodeNumberModel;
23use super::JsonNumberPolicy;
24use super::JsonNumberToken;
25use super::JsonPathSegment;
26use super::JsonRootKind;
27use super::JsonValidatedDecodeError;
28use super::JsonValidatedDecodeOptions;
29use super::internal::JsonDecodeEngine;
30use super::internal::TypedSeed;
31use crate::value::SafeJsonValue;
32
33/// Strictly decodes complete JSON documents while retaining cumulative usage.
34///
35/// This facade performs no normalization. It accepts integers from `i64::MIN`
36/// through `u64::MAX`, requires finite floating-point values, supports values
37/// borrowing from its input, and exposes caller-provided Serde seeds.
38///
39/// # Type Parameters
40///
41/// * `'budget` - Lifetime of the resource budget borrowed by the decoder's
42///   cumulative session.
43/// * `R` - Resource identity type tracked by the session.
44/// * `Q` - Quantity type used for resource limits and accounting.
45///
46/// The ordinary protected-value methods `decode_value_str`,
47/// `decode_value_utf8`, and `decode_value_input` reject duplicate keys.
48/// `decode_unique_*` methods also require unique keys, but deserialize an
49/// owned target from an intermediate tree. The two
50/// `decode_value_last_wins_utf8*` methods instead keep the last value for each
51/// decoded key.
52///
53/// # Examples
54///
55/// ```
56/// use qubit_json::decode::JsonDecoder;
57/// use serde_json::Value;
58///
59/// let mut decoder = JsonDecoder::unlimited();
60/// let value = decoder.decode_str::<Value>(r#"{"ok":true}"#)?;
61/// assert_eq!(value["ok"], true);
62/// # Ok::<(), qubit_json::decode::JsonDecodeError>(())
63/// ```
64#[derive(Debug)]
65pub struct JsonDecoder<'budget, R = JsonResource, Q = usize>
66where
67    Q: ResourceQuantity,
68{
69    /// Diagnostic detail retained for input-derived failures.
70    diagnostic_policy: DiagnosticPolicy,
71    /// Shared generic decoding and accounting core.
72    engine: JsonDecodeEngine<'budget, R, Q>,
73}
74
75impl<R, Q> JsonDecoder<'static, R, Q>
76where
77    R: Clone,
78    Q: ResourceQuantity,
79{
80    /// Creates a decoder with a cumulative session built from explicit limits.
81    ///
82    /// # Parameters
83    ///
84    /// * `limits` - Input and decoded-value limits used by the cumulative
85    ///   session.
86    ///
87    /// # Returns
88    ///
89    /// A decoder whose accounting starts empty and is constrained by `limits`.
90    #[inline(always)]
91    #[must_use]
92    pub fn with_limits(limits: JsonDecodeLimits<R, Q>) -> Self {
93        Self::new(JsonDecodeSession::from_limits(limits))
94    }
95}
96
97impl JsonDecoder<'static, JsonResource, usize> {
98    /// Creates a decoder with no configured input or value limits.
99    ///
100    /// # Returns
101    ///
102    /// A decoder using the standard resource identities with all limits
103    /// disabled.
104    #[inline(always)]
105    #[must_use]
106    pub fn unlimited() -> Self {
107        Self::with_limits(JsonDecodeLimits::new())
108    }
109}
110
111impl<'budget, R, Q> JsonDecoder<'budget, R, Q>
112where
113    R: Clone,
114    Q: ResourceQuantity,
115{
116    /// Creates a strict decoder around a reusable cumulative session.
117    ///
118    /// # Parameters
119    ///
120    /// * `session` - Cumulative session that receives input and decoded-value
121    ///   charges.
122    ///
123    /// # Returns
124    ///
125    /// A decoder that owns `session` until it is consumed by
126    /// [`Self::into_session`].
127    #[inline]
128    #[must_use]
129    pub const fn new(session: JsonDecodeSession<'budget, R, Q>) -> Self {
130        Self {
131            diagnostic_policy: DiagnosticPolicy::Redacted,
132            engine: JsonDecodeEngine::new(session),
133        }
134    }
135
136    /// Decodes one complete document into a guarded value and rejects duplicate
137    /// keys.
138    ///
139    /// # Parameters
140    ///
141    /// * `input` - Complete UTF-8 JSON document.
142    ///
143    /// # Returns
144    ///
145    /// The protected owned value after input and value accounting succeed.
146    ///
147    /// # Errors
148    ///
149    /// Returns a structured error for invalid UTF-8, syntax, numeric range,
150    /// duplicate keys, or configured resource limits.
151    pub fn decode_value_utf8(&mut self, input: &[u8]) -> Result<SafeJsonValue, JsonDecodeError<R, Q>> {
152        self.engine.decode_value_utf8(input, self.diagnostic_policy)
153    }
154
155    /// Decodes one complete document into a guarded value, keeping object keys
156    /// as literal strings and letting the last occurrence of a key win.
157    ///
158    /// Repeated source members are all charged against value limits. Replacing
159    /// a value retains the key's original position when the selected
160    /// `serde_json::Map` backend preserves insertion order. Keys are compared
161    /// after JSON unescaping, without Unicode normalization. Every source
162    /// member is charged against value limits, including members later
163    /// replaced; value usage commits only if the complete decode succeeds.
164    /// Accepted raw input charges remain consumed if decoding later fails.
165    /// Number lexemes pass the ordinary strict source checks before the active
166    /// `serde_json` backend constructs each `Number`, including with
167    /// `serde_json/arbitrary_precision`. This method does not promise a fixed
168    /// representation for `-0`; its representation follows the active backend
169    /// and feature combination.
170    ///
171    /// # Parameters
172    ///
173    /// * `input` - Complete UTF-8 JSON document.
174    ///
175    /// # Returns
176    ///
177    /// The protected owned value after input and value accounting succeed.
178    ///
179    /// # Errors
180    ///
181    /// Returns a structured error for invalid UTF-8, syntax, numeric range,
182    /// invalid materialization, or configured resource limits. This method
183    /// does not change the duplicate-rejecting behavior of
184    /// [`Self::decode_value_utf8`].
185    pub fn decode_value_last_wins_utf8(&mut self, input: &[u8]) -> Result<SafeJsonValue, JsonDecodeError<R, Q>> {
186        self.engine.decode_value_last_wins_utf8(input, self.diagnostic_policy)
187    }
188
189    /// Decodes a last-wins JSON document with a limit on open containers.
190    ///
191    /// Keys are matched after JSON unescaping, and the last value replaces
192    /// earlier values. Every source member is charged against value limits,
193    /// including replaced members; value usage commits only on success, while
194    /// accepted raw input charges remain consumed after failure. Number lexemes
195    /// follow the same strict source checks and active-backend `Number`
196    /// construction as [`Self::decode_value_last_wins_utf8`].
197    ///
198    /// The cap counts simultaneously open arrays and objects, including a
199    /// container root. It is independent of the root-inclusive structural
200    /// `max_depth` budget, which is checked during lexical admission. The
201    /// container cap is finalized after scanning, so syntax, number, or
202    /// admission-budget errors found by that scan take precedence. If the cap
203    /// is the final error, `materialization_error_reason()` returns
204    /// `ContainerLimit { limit }` while the coarse error kind remains
205    /// `Deserialize`.
206    ///
207    /// # Parameters
208    ///
209    /// * `input` - Complete UTF-8 JSON document.
210    /// * `max_containers` - Maximum number of simultaneously open arrays and
211    ///   objects; the root counts when it is a container.
212    ///
213    /// # Returns
214    ///
215    /// The guarded last-wins value after lexical and resource admission.
216    ///
217    /// # Errors
218    ///
219    /// Returns the same errors as [`Self::decode_value_last_wins_utf8`], plus
220    /// a deserialization error with a `ContainerLimit { limit }` reason when
221    /// no later syntax or budget error takes precedence.
222    pub fn decode_value_last_wins_utf8_with_container_limit(
223        &mut self,
224        input: &[u8],
225        max_containers: usize,
226    ) -> Result<SafeJsonValue, JsonDecodeError<R, Q>> {
227        self.engine
228            .decode_value_last_wins_utf8_with_container_limit(input, self.diagnostic_policy, max_containers)
229    }
230
231    /// UTF-8 string form of [`Self::decode_value_utf8`].
232    ///
233    /// # Parameters
234    ///
235    /// * `input` - Complete JSON document text.
236    ///
237    /// # Returns
238    ///
239    /// The protected owned value.
240    ///
241    /// # Errors
242    ///
243    /// Returns a structured error for syntax, numeric range, duplicate keys,
244    /// or configured resource limits.
245    pub fn decode_value_str(&mut self, input: &str) -> Result<SafeJsonValue, JsonDecodeError<R, Q>> {
246        self.decode_value_utf8(input.as_bytes())
247    }
248
249    /// Reads one unique-key document until the input first reports EOF and
250    /// decodes it into a guarded value.
251    ///
252    /// Reads in bounded chunks, with at most one probe byte beyond an active
253    /// input limit. Accepted bytes remain charged when later validation fails.
254    ///
255    /// # Parameters
256    ///
257    /// * `input` - Byte input whose first zero-length read marks the document
258    ///   end. The caller must provide a reliable end-of-document boundary;
259    ///   inputs that can temporarily make no progress must be framed or
260    ///   aggregated before decoding.
261    ///
262    /// # Type Parameters
263    ///
264    /// * `I` - Byte input type that marks the document boundary with its first
265    ///   zero-length read.
266    ///
267    /// # Returns
268    ///
269    /// The protected owned value.
270    ///
271    /// # Errors
272    ///
273    /// Returns read, input-budget, UTF-8, syntax, numeric-range, duplicate-key,
274    /// or value-budget failures.
275    pub fn decode_value_input<I: ByteInput + ?Sized>(
276        &mut self,
277        input: &mut I,
278    ) -> Result<SafeJsonValue, JsonDecodeError<R, Q>> {
279        self.engine.decode_value_input(input, self.diagnostic_policy)
280    }
281
282    /// Decodes one document while applying a caller policy to each source
283    /// number.
284    ///
285    /// The callback runs in source order after a number token is syntactically
286    /// complete and before its configured representation range is checked. It
287    /// receives the typed path and borrowed source spelling; its first error
288    /// stops scanning immediately. Object keys must be unique after decoding.
289    /// Side effects performed by the callback are not rolled back if later
290    /// syntax, delimiter, or budget validation fails. The string and input
291    /// forms of this method have the same callback contract.
292    ///
293    /// ```
294    /// use std::cell::Cell;
295    /// use std::convert::Infallible;
296    /// use qubit_json::decode::JsonDecoder;
297    /// use qubit_json::decode::JsonNumberPolicy;
298    /// use qubit_json::decode::JsonValidatedDecodeOptions;
299    ///
300    /// let calls = Cell::new(0);
301    /// let result = JsonDecoder::unlimited().decode_unique_validated_str(
302    ///     "[1,]",
303    ///     &JsonValidatedDecodeOptions::builder().build(),
304    ///     |_, _| {
305    ///         calls.set(calls.get() + 1);
306    ///         Ok::<_, Infallible>(JsonNumberPolicy::Preserve)
307    ///     },
308    /// );
309    /// assert!(result.is_err());
310    /// assert_eq!(calls.get(), 1);
311    /// ```
312    ///
313    /// # Parameters
314    ///
315    /// * `input` - Complete UTF-8 JSON document.
316    /// * `options` - Root, number model, and per-document source-token limits.
317    /// * `number_policy` - Synchronous policy called for each complete number.
318    ///
319    /// # Type Parameters
320    ///
321    /// * `E` - Error type returned by the caller's number policy.
322    /// * `F` - Number policy callback type.
323    ///
324    /// # Returns
325    ///
326    /// The protected owned value after complete scanning and accounting.
327    ///
328    /// # Errors
329    ///
330    /// Returns structured decode errors, callback errors with source offsets,
331    /// exact-safe-integer errors, or validated-limit failures.
332    pub fn decode_unique_validated_utf8<E, F>(
333        &mut self,
334        input: &[u8],
335        options: &JsonValidatedDecodeOptions,
336        number_policy: F,
337    ) -> Result<SafeJsonValue, JsonValidatedDecodeError<E, R, Q>>
338    where
339        F: for<'call> FnMut(&'call [JsonPathSegment], JsonNumberToken<'call>) -> Result<JsonNumberPolicy, E>,
340    {
341        self.engine
342            .decode_unique_validated_utf8(input, options, number_policy, self.diagnostic_policy)
343    }
344
345    /// UTF-8 string form of [`Self::decode_unique_validated_utf8`], with the
346    /// same callback side-effect contract documented there.
347    ///
348    /// # Parameters
349    ///
350    /// * `input` - Complete JSON document text.
351    /// * `options` - Root, number model, and per-document source-token limits.
352    /// * `number_policy` - Synchronous number policy callback.
353    ///
354    /// # Type Parameters
355    ///
356    /// * `E` - Error type returned by the caller's number policy.
357    /// * `F` - Number policy callback type.
358    ///
359    /// # Returns
360    ///
361    /// The protected owned value.
362    ///
363    /// # Errors
364    ///
365    /// Returns decode, callback, exact-safe-integer, or validated-limit errors.
366    pub fn decode_unique_validated_str<E, F>(
367        &mut self,
368        input: &str,
369        options: &JsonValidatedDecodeOptions,
370        number_policy: F,
371    ) -> Result<SafeJsonValue, JsonValidatedDecodeError<E, R, Q>>
372    where
373        F: for<'call> FnMut(&'call [JsonPathSegment], JsonNumberToken<'call>) -> Result<JsonNumberPolicy, E>,
374    {
375        self.decode_unique_validated_utf8(input.as_bytes(), options, number_policy)
376    }
377
378    /// Reads a byte input until its first zero-length read and applies a
379    /// source-number policy during decoding.
380    ///
381    /// Accepted input bytes remain charged if the callback or later validation
382    /// fails; value charges commit only after the complete document succeeds.
383    /// Callback side effects are not rolled back on failure, as documented for
384    /// [`Self::decode_unique_validated_utf8`].
385    ///
386    /// # Parameters
387    ///
388    /// * `input` - Byte input whose first zero-length read marks the document
389    ///   end. The caller must provide a reliable end-of-document boundary;
390    ///   inputs that can temporarily make no progress must be framed or
391    ///   aggregated before decoding.
392    /// * `options` - Root, number model, and per-document token limits.
393    /// * `number_policy` - Synchronous callback for each source number.
394    ///
395    /// # Type Parameters
396    ///
397    /// * `E` - Error type returned by the caller's number policy.
398    /// * `F` - Number policy callback type.
399    /// * `I` - Byte input type that marks the document boundary with its first
400    ///   zero-length read.
401    ///
402    /// # Returns
403    ///
404    /// The protected owned value.
405    ///
406    /// # Errors
407    ///
408    /// Returns structured decode, read, callback, exact-integer, or limit
409    /// errors.
410    pub fn decode_unique_validated_input<E, F, I>(
411        &mut self,
412        input: &mut I,
413        options: &JsonValidatedDecodeOptions,
414        number_policy: F,
415    ) -> Result<SafeJsonValue, JsonValidatedDecodeError<E, R, Q>>
416    where
417        I: ByteInput + ?Sized,
418        F: for<'call> FnMut(&'call [JsonPathSegment], JsonNumberToken<'call>) -> Result<JsonNumberPolicy, E>,
419    {
420        self.engine
421            .decode_unique_validated_input(input, options, number_policy, self.diagnostic_policy)
422    }
423
424    /// Decodes one byte input using an explicit integer/fallback number model.
425    ///
426    /// The number model controls whether an integer token outside `i64`/`u64`
427    /// is admitted. With the fallback model, that token is admitted only when
428    /// it converts to finite `f64`. Decimal and exponent forms use the
429    /// finite-float rule in both models.
430    ///
431    /// The resulting representation is produced by Serde for `T` and can
432    /// depend on the active `serde_json` features. For deterministic numeric
433    /// projection, use validated decoding with `JsonNumberPolicy::Preserve`;
434    /// it materializes fallback integers as finite `f64` values.
435    ///
436    /// # Parameters
437    ///
438    /// * `input` - Byte input whose first zero-length read marks the document
439    ///   end. The caller must provide a reliable end-of-document boundary;
440    ///   inputs that can temporarily make no progress must be framed or
441    ///   aggregated before decoding.
442    /// * `model` - Integer representation model for admitted source numbers.
443    ///
444    /// # Type Parameters
445    ///
446    /// * `T` - Owned target type deserialized from the document.
447    /// * `I` - Byte input type that marks the document boundary with its first
448    ///   zero-length read.
449    ///
450    /// # Returns
451    ///
452    /// The owned value produced by Serde. Its numeric representation follows
453    /// `T` and the active Serde implementation and features.
454    ///
455    /// # Errors
456    ///
457    /// Returns read, UTF-8, syntax, numeric-range, budget, or Serde errors.
458    pub fn decode_input_with_number_model<T, I>(
459        &mut self,
460        input: &mut I,
461        model: JsonDecodeNumberModel,
462    ) -> Result<T, JsonDecodeError<R, Q>>
463    where
464        T: DeserializeOwned,
465        I: ByteInput + ?Sized,
466    {
467        let model = match model {
468            JsonDecodeNumberModel::Integer64 => crate::lexical::JsonNumberModel::Integer64,
469            JsonDecodeNumberModel::Integer64WithFiniteFallback => {
470                crate::lexical::JsonNumberModel::Integer64WithFiniteFallback
471            }
472        };
473        self.engine
474            .decode_input_seed(TypedSeed::new(), input, self.diagnostic_policy, model)
475    }
476
477    /// Returns the configured diagnostic policy without changing the decoder.
478    ///
479    /// # Returns
480    ///
481    /// The policy used when constructing input-derived decode errors.
482    #[inline(always)]
483    #[must_use]
484    pub const fn diagnostic_policy(&self) -> DiagnosticPolicy {
485        self.diagnostic_policy
486    }
487
488    /// Returns the cumulative session for read-only inspection.
489    ///
490    /// The returned reference is borrowed from the decoder and exposes the
491    /// charges accumulated by completed operations.
492    ///
493    /// # Returns
494    ///
495    /// A shared reference to the decoder's cumulative session.
496    #[inline(always)]
497    #[must_use]
498    pub const fn session(&self) -> &JsonDecodeSession<'budget, R, Q> {
499        self.engine.session()
500    }
501
502    /// Returns mutable access to the cumulative session.
503    ///
504    /// Mutating the session changes the limits and accounting state used by
505    /// subsequent operations.
506    ///
507    /// # Returns
508    ///
509    /// A mutable reference tied to the decoder's lifetime.
510    #[inline(always)]
511    #[must_use]
512    pub const fn session_mut(&mut self) -> &mut JsonDecodeSession<'budget, R, Q> {
513        self.engine.session_mut()
514    }
515
516    /// Configures whether input-derived error sources are retained.
517    ///
518    /// The default is [`DiagnosticPolicy::Redacted`]. Selecting
519    /// [`DiagnosticPolicy::Detailed`] may retain source errors containing
520    /// fragments or structural details derived from the input.
521    ///
522    /// # Parameters
523    ///
524    /// * `policy` - Diagnostic retention policy for failures produced by this
525    ///   decoder.
526    ///
527    /// # Returns
528    ///
529    /// The decoder with the requested policy; its existing session is retained.
530    #[inline(always)]
531    #[must_use]
532    pub const fn with_diagnostic_policy(mut self, policy: DiagnosticPolicy) -> Self {
533        self.diagnostic_policy = policy;
534        self
535    }
536
537    /// Consumes the decoder and returns its cumulative session.
538    ///
539    /// This transfers ownership of all accumulated accounting state without
540    /// performing another decode or resetting the session.
541    ///
542    /// # Returns
543    ///
544    /// The session previously owned by this decoder.
545    #[inline(always)]
546    #[must_use]
547    pub fn into_session(self) -> JsonDecodeSession<'budget, R, Q> {
548        self.engine.into_session()
549    }
550
551    /// Decodes one complete JSON string and permits results borrowing `input`.
552    ///
553    /// # Type Parameters
554    ///
555    /// * `T` - Target type deserialized from the complete document.
556    ///
557    /// # Parameters
558    ///
559    /// * `input` - UTF-8 JSON text. The returned value may borrow from it.
560    ///
561    /// # Returns
562    ///
563    /// The deserialized value on success.
564    ///
565    /// # Errors
566    ///
567    /// Returns a structured error when input accounting, UTF-8 validation,
568    /// JSON parsing, or Serde deserialization fails.
569    pub fn decode_str<'de, T>(&mut self, input: &'de str) -> Result<T, JsonDecodeError<R, Q>>
570    where
571        T: Deserialize<'de>,
572    {
573        self.decode_seed_str(TypedSeed::new(), input)
574    }
575
576    /// Decodes one complete UTF-8 JSON byte slice and permits borrowed results.
577    ///
578    /// # Type Parameters
579    ///
580    /// * `T` - Target type deserialized from the complete document.
581    ///
582    /// # Parameters
583    ///
584    /// * `input` - Complete UTF-8 JSON bytes. The returned value may borrow
585    ///   from this slice.
586    ///
587    /// # Returns
588    ///
589    /// The deserialized value on success.
590    ///
591    /// # Errors
592    ///
593    /// Returns a structured error when accounting, UTF-8 validation, JSON
594    /// parsing, or Serde deserialization fails.
595    pub fn decode_utf8<'de, T>(&mut self, input: &'de [u8]) -> Result<T, JsonDecodeError<R, Q>>
596    where
597        T: Deserialize<'de>,
598    {
599        self.decode_seed_utf8(TypedSeed::new(), input)
600    }
601
602    /// Decodes a document from an item-oriented byte input until its first
603    /// zero-length read.
604    ///
605    /// Without an input-byte limit, the input is read in fixed-size chunks.
606    /// With a limit, each read is bounded by the remaining allowance plus at
607    /// most one probe byte. The probe distinguishes an input ending exactly
608    /// at the limit from an oversized input; it is neither charged nor
609    /// buffered, and cannot be returned to the input source. The complete
610    /// admitted document is buffered in memory because the returned value
611    /// must not borrow from the temporary buffer. Without an input-byte
612    /// limit, this buffering has no implicit size cap.
613    ///
614    /// # Parameters
615    ///
616    /// * `input` - Mutable byte input whose first zero-length read marks the
617    ///   document end. The caller must provide a reliable end-of-document
618    ///   boundary; inputs that can temporarily make no progress must be framed
619    ///   or aggregated before decoding.
620    ///
621    /// # Returns
622    ///
623    /// The owned value deserialized from the complete document.
624    ///
625    /// # Errors
626    ///
627    /// Returns a structured error for read failures, input-budget rejection,
628    /// invalid UTF-8, invalid JSON, or target deserialization failures.
629    ///
630    /// # Type Parameters
631    ///
632    /// * `T` - Owned target type deserialized from the document.
633    /// * `I` - Item-oriented byte input type that marks the document boundary
634    ///   with its first zero-length read.
635    pub fn decode_input<T, I>(&mut self, input: &mut I) -> Result<T, JsonDecodeError<R, Q>>
636    where
637        T: DeserializeOwned,
638        I: Input<Item = u8> + ?Sized,
639    {
640        self.engine.decode_input(input, self.diagnostic_policy)
641    }
642
643    /// Decodes a JSON string through a caller-provided Serde seed.
644    ///
645    /// # Type Parameters
646    ///
647    /// * `S` - Seed controlling construction of the decoded value.
648    ///
649    /// # Parameters
650    ///
651    /// * `seed` - Serde seed used to deserialize the document.
652    /// * `input` - Complete JSON text, which the seed may borrow from.
653    ///
654    /// # Returns
655    ///
656    /// The value produced by `seed`.
657    ///
658    /// # Errors
659    ///
660    /// Returns a structured error when accounting, parsing, or seeded
661    /// deserialization fails.
662    pub fn decode_seed_str<'de, S>(&mut self, seed: S, input: &'de str) -> Result<S::Value, JsonDecodeError<R, Q>>
663    where
664        S: DeserializeSeed<'de>,
665    {
666        self.decode_seed_utf8(seed, input.as_bytes())
667    }
668
669    /// Decodes a UTF-8 byte slice through a caller-provided Serde seed.
670    ///
671    /// # Type Parameters
672    ///
673    /// * `S` - Seed controlling construction of the decoded value.
674    ///
675    /// # Parameters
676    ///
677    /// * `seed` - Serde seed used to deserialize the document.
678    /// * `input` - Complete UTF-8 JSON bytes, which the seed may borrow from.
679    ///
680    /// # Returns
681    ///
682    /// The value produced by `seed`.
683    ///
684    /// # Errors
685    ///
686    /// Returns a structured error when accounting, UTF-8 validation, parsing,
687    /// or seeded deserialization fails.
688    pub fn decode_seed_utf8<'de, S>(&mut self, seed: S, input: &'de [u8]) -> Result<S::Value, JsonDecodeError<R, Q>>
689    where
690        S: DeserializeSeed<'de>,
691    {
692        self.engine.decode_seed_utf8(seed, input, self.diagnostic_policy)
693    }
694
695    /// Decodes a unique-key JSON document into an owned target.
696    ///
697    /// The document is first materialized under the strict number contract,
698    /// then exposed as native Serde events even with `arbitrary_precision`.
699    /// Source construction uses the configured value depth budget and has no
700    /// separate fixed container limit. Targets cannot borrow the input, and
701    /// RawValue targets receive reconstructed JSON.
702    ///
703    /// # Type Parameters
704    ///
705    /// * `T` - Owned target type deserialized from the unique-key document.
706    ///
707    /// # Parameters
708    ///
709    /// * `input` - Complete JSON text to decode.
710    ///
711    /// # Returns
712    ///
713    /// The decoded owned value after unique-key validation succeeds.
714    ///
715    /// # Errors
716    ///
717    /// Returns an input, syntax, budget, duplicate-key, construction-depth,
718    /// or target-deserialization error. Value usage commits only on success.
719    pub fn decode_unique_str<T>(&mut self, input: &str) -> Result<T, JsonDecodeError<R, Q>>
720    where
721        T: DeserializeOwned,
722    {
723        self.decode_unique_utf8(input.as_bytes())
724    }
725
726    /// Decodes a unique-key UTF-8 JSON document into an owned target.
727    ///
728    /// See [`Self::decode_unique_str`] for numeric and materialization rules.
729    ///
730    /// # Type Parameters
731    ///
732    /// * `T` - Owned target type deserialized from the unique-key document.
733    ///
734    /// # Parameters
735    ///
736    /// * `input` - Complete UTF-8 JSON bytes to decode.
737    ///
738    /// # Returns
739    ///
740    /// The decoded owned value after unique-key validation succeeds.
741    ///
742    /// # Errors
743    ///
744    /// Returns an input, UTF-8, syntax, budget, materialization, or target
745    /// error.
746    pub fn decode_unique_utf8<T>(&mut self, input: &[u8]) -> Result<T, JsonDecodeError<R, Q>>
747    where
748        T: DeserializeOwned,
749    {
750        self.decode_unique_seed_utf8(TypedSeed::new(), input)
751    }
752
753    /// Decodes unique-key JSON through a seed producing an owned result.
754    ///
755    /// The seed receives native scalar, sequence, and map events from an
756    /// intermediate strict JSON tree. Input and value budgets cover the source
757    /// document. The temporary tree and target can coexist during decoding;
758    /// these lexical budgets are not a precise heap-memory bound.
759    /// Object iteration follows `serde_json::Map` ordering. The target's own
760    /// Serde semantics still apply: use `DuplicateKeyRejectingJsonValue`
761    /// instead of a bare `serde_json::Value` to preserve literal private keys.
762    ///
763    /// # Type Parameters
764    ///
765    /// * `S` - Seed that controls construction of the owned result.
766    /// * `T` - Owned result type produced by `S`.
767    ///
768    /// # Parameters
769    ///
770    /// * `seed` - Serde seed used to deserialize the materialized document.
771    /// * `input` - Complete UTF-8 JSON bytes to decode.
772    ///
773    /// # Returns
774    ///
775    /// The owned value produced by `seed` after unique-key validation.
776    ///
777    /// # Errors
778    ///
779    /// Returns a structured decode error for input admission, invalid syntax,
780    /// duplicate keys, configured value-depth failure, or seed failure.
781    /// Materialization errors retain source coordinates; target errors have
782    /// no original source position and are redacted by default.
783    pub fn decode_unique_seed_utf8<S, T>(&mut self, seed: S, input: &[u8]) -> Result<T, JsonDecodeError<R, Q>>
784    where
785        S: for<'de> DeserializeSeed<'de, Value = T>,
786    {
787        self.engine.decode_unique_seed_utf8(seed, input, self.diagnostic_policy)
788    }
789
790    /// Decodes a complete JSON string while requiring a top-level object.
791    ///
792    /// The top-level check is performed before the decoded value is committed,
793    /// so an array, scalar, or otherwise valid non-object document is rejected.
794    ///
795    /// # Type Parameters
796    ///
797    /// * `T` - Target type deserialized from the object document.
798    ///
799    /// # Parameters
800    ///
801    /// * `input` - Complete JSON text, which the returned value may borrow.
802    ///
803    /// # Returns
804    ///
805    /// The deserialized object value on success.
806    ///
807    /// # Errors
808    ///
809    /// Returns a structured error for accounting, parsing, top-level-kind, or
810    /// deserialization failures.
811    pub fn decode_object_str<'de, T>(&mut self, input: &'de str) -> Result<T, JsonDecodeError<R, Q>>
812    where
813        T: Deserialize<'de>,
814    {
815        self.decode_object_utf8(input.as_bytes())
816    }
817
818    /// Decodes a complete UTF-8 byte slice while requiring a top-level object.
819    ///
820    /// A syntactically valid array or scalar is rejected by the top-level
821    /// constraint before the decoded value is committed.
822    ///
823    /// # Type Parameters
824    ///
825    /// * `T` - Target type deserialized from the object document.
826    ///
827    /// # Parameters
828    ///
829    /// * `input` - Complete UTF-8 JSON bytes, which the returned value may
830    ///   borrow.
831    ///
832    /// # Returns
833    ///
834    /// The deserialized object value on success.
835    ///
836    /// # Errors
837    ///
838    /// Returns a structured error for accounting, UTF-8 validation, parsing,
839    /// top-level-kind, or deserialization failures.
840    pub fn decode_object_utf8<'de, T>(&mut self, input: &'de [u8]) -> Result<T, JsonDecodeError<R, Q>>
841    where
842        T: Deserialize<'de>,
843    {
844        self.engine.decode_seed_utf8_with_top_level(
845            TypedSeed::new(),
846            input,
847            self.diagnostic_policy,
848            Some(JsonRootKind::Object),
849        )
850    }
851
852    /// Decodes a complete JSON string while requiring a top-level array.
853    ///
854    /// # Type Parameters
855    ///
856    /// * `T` - Element type deserialized from the array.
857    ///
858    /// # Parameters
859    ///
860    /// * `input` - Complete JSON text, which the returned elements may borrow.
861    ///
862    /// # Returns
863    ///
864    /// The decoded array elements on success.
865    ///
866    /// # Errors
867    ///
868    /// Returns a structured error for accounting, parsing, top-level-kind, or
869    /// deserialization failures.
870    pub fn decode_array_str<'de, T>(&mut self, input: &'de str) -> Result<Vec<T>, JsonDecodeError<R, Q>>
871    where
872        T: Deserialize<'de>,
873    {
874        self.decode_array_utf8(input.as_bytes())
875    }
876
877    /// Decodes a complete UTF-8 byte slice while requiring a top-level array.
878    ///
879    /// # Type Parameters
880    ///
881    /// * `T` - Element type deserialized from the array.
882    ///
883    /// # Parameters
884    ///
885    /// * `input` - Complete UTF-8 JSON bytes, which the returned elements may
886    ///   borrow.
887    ///
888    /// # Returns
889    ///
890    /// The decoded array elements on success.
891    ///
892    /// # Errors
893    ///
894    /// Returns a structured error for accounting, UTF-8 validation, parsing,
895    /// top-level-kind, or deserialization failures.
896    pub fn decode_array_utf8<'de, T>(&mut self, input: &'de [u8]) -> Result<Vec<T>, JsonDecodeError<R, Q>>
897    where
898        T: Deserialize<'de>,
899    {
900        self.engine.decode_seed_utf8_with_top_level(
901            TypedSeed::new(),
902            input,
903            self.diagnostic_policy,
904            Some(JsonRootKind::Array),
905        )
906    }
907
908    /// Validates and accounts for one complete JSON string without
909    /// materializing a target value.
910    ///
911    /// # Parameters
912    ///
913    /// * `input` - Complete JSON text to validate and account for.
914    ///
915    /// # Returns
916    ///
917    /// `Ok(())` after the complete document is valid and accounted for.
918    ///
919    /// # Errors
920    ///
921    /// Returns a structured error when accounting or JSON parsing fails. No
922    /// target value is allocated; `str` input is already valid UTF-8.
923    pub fn validate_str(&mut self, input: &str) -> Result<(), JsonDecodeError<R, Q>> {
924        self.validate_utf8(input.as_bytes())
925    }
926
927    /// Validates and accounts for one complete UTF-8 JSON byte slice without
928    /// materializing a target value.
929    ///
930    /// # Parameters
931    ///
932    /// * `input` - Complete UTF-8 JSON bytes to validate and account for.
933    ///
934    /// # Returns
935    ///
936    /// `Ok(())` after the complete document is valid and accounted for.
937    ///
938    /// # Errors
939    ///
940    /// Returns a structured error when accounting, UTF-8 validation, or JSON
941    /// parsing fails. No target value is allocated.
942    pub fn validate_utf8(&mut self, input: &[u8]) -> Result<(), JsonDecodeError<R, Q>> {
943        self.engine.validate_utf8(input, self.diagnostic_policy)
944    }
945}