Skip to main content

qubit_json/decode/
json_decode_error_kind.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 categories for JSON decoding failures.
9
10use std::fmt;
11use std::str::FromStr;
12
13/// Represents the coarse category of a JSON decoding failure.
14///
15/// This exhaustive enum is the stable branching contract shared by strict and
16/// normalizing decoders.
17///
18/// # Examples
19///
20/// ```
21/// use qubit_json::decode::JsonDecodeErrorKind;
22///
23/// let kind = "invalid_json".parse::<JsonDecodeErrorKind>()?;
24/// assert_eq!(kind, JsonDecodeErrorKind::InvalidJson);
25/// # Ok::<(), &'static str>(())
26/// ```
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum JsonDecodeErrorKind {
29    /// Reading bytes from the input failed.
30    Read,
31    /// A configured resource budget rejected a measurement.
32    Budget,
33    /// Normalization produced no JSON document from the supplied input.
34    EmptyInput,
35    /// Raw byte input was not valid UTF-8.
36    InvalidUtf8,
37    /// Input was not one valid JSON document under the numeric contract.
38    InvalidJson,
39    /// A valid document had an unexpected top-level kind.
40    UnexpectedTopLevel,
41    /// A valid admitted document could not materialize a protected value or
42    /// deserialize into the target type.
43    Deserialize,
44}
45
46impl fmt::Display for JsonDecodeErrorKind {
47    /// Writes the stable snake-case category name.
48    ///
49    /// # Parameters
50    ///
51    /// * `formatter` - Destination for the category name.
52    ///
53    /// # Returns
54    ///
55    /// `Ok(())` when the category name is written successfully.
56    ///
57    /// # Errors
58    ///
59    /// Returns the formatter's error if the destination rejects the write.
60    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61        formatter.write_str(match self {
62            Self::Read => "read",
63            Self::Budget => "budget",
64            Self::EmptyInput => "empty_input",
65            Self::InvalidUtf8 => "invalid_utf8",
66            Self::InvalidJson => "invalid_json",
67            Self::UnexpectedTopLevel => "unexpected_top_level",
68            Self::Deserialize => "deserialize",
69        })
70    }
71}
72
73impl FromStr for JsonDecodeErrorKind {
74    /// Uses a static message to report unsupported category names.
75    type Err = &'static str;
76
77    /// Parses a stable category name without ASCII case sensitivity.
78    ///
79    /// # Parameters
80    ///
81    /// * `value` - Category name to parse.
82    ///
83    /// # Returns
84    ///
85    /// The matching JSON decoding error category.
86    ///
87    /// # Errors
88    ///
89    /// Returns `"unknown JsonDecodeErrorKind"` when `value` does not match a
90    /// supported category name.
91    fn from_str(value: &str) -> Result<Self, Self::Err> {
92        if value.eq_ignore_ascii_case("read") {
93            Ok(Self::Read)
94        } else if value.eq_ignore_ascii_case("budget") {
95            Ok(Self::Budget)
96        } else if value.eq_ignore_ascii_case("empty_input") {
97            Ok(Self::EmptyInput)
98        } else if value.eq_ignore_ascii_case("invalid_utf8") {
99            Ok(Self::InvalidUtf8)
100        } else if value.eq_ignore_ascii_case("invalid_json") {
101            Ok(Self::InvalidJson)
102        } else if value.eq_ignore_ascii_case("unexpected_top_level") {
103            Ok(Self::UnexpectedTopLevel)
104        } else if value.eq_ignore_ascii_case("deserialize") {
105            Ok(Self::Deserialize)
106        } else {
107            Err("unknown JsonDecodeErrorKind")
108        }
109    }
110}