Skip to main content

qubit_json/encode/
json_serialization_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 stable, privacy-safe JSON serialization failures.
9
10use std::fmt::Display;
11
12use serde::ser::Error as SerError;
13use thiserror::Error;
14
15use super::JsonCollectionKind;
16use super::JsonIntegerSignedness;
17use super::JsonMapKeyKind;
18use super::JsonSerializationErrorCategory;
19use super::JsonSerializationErrorKind;
20use super::JsonSerializerStateError;
21
22/// Privacy-safe failure produced while serializing a value as strict JSON.
23///
24/// The error exposes exact stable kinds and broad handling categories without
25/// retaining input values, object keys, or arbitrary third-party diagnostics.
26///
27/// # Examples
28///
29/// ```
30/// use qubit_json::encode::JsonIntegerSignedness;
31/// use qubit_json::encode::JsonSerializationErrorKind;
32/// use qubit_json::value::JsonValueEncoder;
33///
34/// let error = JsonValueEncoder::new()
35///     .encode(&u128::MAX)
36///     .expect_err("wide integer must be rejected");
37/// assert_eq!(
38///     error.kind(),
39///     JsonSerializationErrorKind::IntegerOutOfRange {
40///         signedness: JsonIntegerSignedness::Unsigned,
41///     },
42/// );
43/// ```
44#[must_use]
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Error)]
46#[error("{kind}")]
47pub struct JsonSerializationError {
48    /// Exact privacy-safe classification.
49    kind: JsonSerializationErrorKind,
50}
51
52impl JsonSerializationError {
53    /// Creates an error from its stable public kind.
54    ///
55    /// # Parameters
56    ///
57    /// * `kind` - Exact privacy-safe serialization failure.
58    ///
59    /// # Returns
60    ///
61    /// A serialization error retaining only `kind`.
62    #[inline(always)]
63    pub const fn new(kind: JsonSerializationErrorKind) -> Self {
64        Self { kind }
65    }
66
67    /// Returns the exact stable failure classification.
68    ///
69    /// # Returns
70    ///
71    /// The precise serialization failure kind retained by this error.
72    #[inline(always)]
73    pub const fn kind(&self) -> JsonSerializationErrorKind {
74        self.kind
75    }
76
77    /// Returns the broad downstream handling category.
78    ///
79    /// # Returns
80    ///
81    /// The broad category that determines which class of serialization
82    /// failure occurred.
83    #[must_use]
84    pub const fn category(&self) -> JsonSerializationErrorCategory {
85        match self.kind {
86            JsonSerializationErrorKind::IntegerOutOfRange { .. }
87            | JsonSerializationErrorKind::NonFiniteFloat
88            | JsonSerializationErrorKind::InvalidNumberRepresentation => JsonSerializationErrorCategory::Number,
89            JsonSerializationErrorKind::UnsupportedMapKey { .. } | JsonSerializationErrorKind::DuplicateObjectKey => {
90                JsonSerializationErrorCategory::ObjectKey
91            }
92            JsonSerializationErrorKind::InvalidRawValue => JsonSerializationErrorCategory::RawValue,
93            JsonSerializationErrorKind::CollectionLengthOverflow { .. } => JsonSerializationErrorCategory::Capacity,
94            JsonSerializationErrorKind::InvalidSerializerState { .. }
95            | JsonSerializationErrorKind::DisplayFormattingFailed => JsonSerializationErrorCategory::SerializerContract,
96            JsonSerializationErrorKind::CustomSerialization => JsonSerializationErrorCategory::Custom,
97        }
98    }
99
100    /// Reports whether this failure belongs to the strict number contract.
101    ///
102    /// # Returns
103    ///
104    /// `true` when the failure concerns a JSON number; otherwise, `false`.
105    #[must_use]
106    #[inline(always)]
107    pub const fn is_number_error(&self) -> bool {
108        matches!(self.category(), JsonSerializationErrorCategory::Number)
109    }
110
111    /// Reports whether this failure concerns JSON object-key representation.
112    ///
113    /// # Returns
114    ///
115    /// `true` when the failure concerns an object key; otherwise, `false`.
116    #[must_use]
117    #[inline(always)]
118    pub const fn is_map_key_error(&self) -> bool {
119        matches!(self.category(), JsonSerializationErrorCategory::ObjectKey)
120    }
121
122    /// Reports whether this failure concerns a RawValue payload.
123    ///
124    /// # Returns
125    ///
126    /// `true` when the failure concerns a `RawValue` payload; otherwise,
127    /// `false`.
128    #[must_use]
129    #[inline(always)]
130    pub const fn is_raw_value_error(&self) -> bool {
131        matches!(self.category(), JsonSerializationErrorCategory::RawValue)
132    }
133
134    /// Reports whether a hand-written serializer violated a protocol contract.
135    ///
136    /// # Returns
137    ///
138    /// `true` when a serializer or display implementation violated the
139    /// compound protocol; otherwise, `false`.
140    #[must_use]
141    #[inline(always)]
142    pub const fn is_serializer_contract_error(&self) -> bool {
143        matches!(self.category(), JsonSerializationErrorCategory::SerializerContract)
144    }
145
146    /// Returns the signedness of an out-of-range integer, when applicable.
147    ///
148    /// # Returns
149    ///
150    /// `Some(signedness)` for an out-of-range integer, or `None` for every
151    /// other serialization failure.
152    #[inline(always)]
153    pub const fn integer_signedness(&self) -> Option<JsonIntegerSignedness> {
154        match self.kind {
155            JsonSerializationErrorKind::IntegerOutOfRange { signedness } => Some(signedness),
156            _ => None,
157        }
158    }
159
160    /// Returns the rejected map-key shape, when applicable.
161    ///
162    /// # Returns
163    ///
164    /// `Some(kind)` for an unsupported map key, or `None` for every other
165    /// serialization failure.
166    #[inline(always)]
167    pub const fn map_key_kind(&self) -> Option<JsonMapKeyKind> {
168        match self.kind {
169            JsonSerializationErrorKind::UnsupportedMapKey { kind } => Some(kind),
170            _ => None,
171        }
172    }
173
174    /// Returns the collection whose count overflowed, when applicable.
175    ///
176    /// # Returns
177    ///
178    /// `Some(kind)` for a collection-length overflow, or `None` for every
179    /// other serialization failure.
180    #[inline(always)]
181    pub const fn collection_kind(&self) -> Option<JsonCollectionKind> {
182        match self.kind {
183            JsonSerializationErrorKind::CollectionLengthOverflow { kind } => Some(kind),
184            _ => None,
185        }
186    }
187
188    /// Returns the exact invalid serializer state, when applicable.
189    ///
190    /// # Returns
191    ///
192    /// `Some(reason)` for an invalid serializer state, or `None` for every
193    /// other serialization failure.
194    #[inline(always)]
195    pub const fn serializer_state_error(&self) -> Option<JsonSerializerStateError> {
196        match self.kind {
197            JsonSerializationErrorKind::InvalidSerializerState { reason } => Some(reason),
198            _ => None,
199        }
200    }
201}
202
203impl SerError for JsonSerializationError {
204    /// Converts arbitrary custom serializer text into one opaque, stable kind.
205    fn custom<T>(_message: T) -> Self
206    where
207        T: Display,
208    {
209        Self::new(JsonSerializationErrorKind::CustomSerialization)
210    }
211}