qubit_json/encode/json_encode_error_source.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 owned sources retained by strict JSON encoding errors.
9
10use std::fmt;
11use std::io::Error as IoError;
12
13use qubit_budget::MeasuredBudgetError;
14
15use super::JsonSerializationError;
16use crate::decode::JsonSyntaxError;
17
18/// An owned source extracted from a strict JSON encoding failure.
19///
20/// This enum lets callers move an underlying failure into another error model
21/// with one exhaustive match. It avoids checking an error kind and then using
22/// a separate optional extractor whose success depends on that prior check.
23///
24/// # Type Parameters
25///
26/// * `R` - Resource identity attached to budget failures.
27/// * `Q` - Quantity representation attached to budget failures.
28///
29/// # Examples
30///
31/// ```
32/// use qubit_budget::json::JsonResource;
33/// use qubit_json::encode::JsonEncodeErrorSource;
34/// use qubit_json::encode::JsonEncoder;
35///
36/// let mut encoder = JsonEncoder::unlimited();
37/// let error = encoder
38/// .to_vec(&u128::MAX)
39/// .expect_err("wide integer must not serialize as JSON");
40/// match error.into_source() {
41/// JsonEncodeErrorSource::Serialize(source) => {
42/// assert!(source.is_number_error());
43/// }
44/// source => panic!("unexpected encoding source: {source:?}"),
45/// }
46/// # let _: Option<JsonEncodeErrorSource<JsonResource>> = None;
47/// ```
48#[must_use]
49#[derive(Debug)]
50pub enum JsonEncodeErrorSource<R, Q = usize>
51where
52 Q: Copy + fmt::Debug,
53{
54 /// Resource accounting rejected the encoded work or output.
55 Budget(MeasuredBudgetError<R, Q>),
56 /// A `serde_json::value::RawValue` payload was not strict JSON.
57 InvalidRawJson(JsonSyntaxError),
58 /// Serde rejected the source value during strict serialization.
59 Serialize(JsonSerializationError),
60 /// The destination writer rejected an output operation.
61 Write(IoError),
62}