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    /// A configured resource budget rejected a measurement.
30    Budget,
31    /// Normalization produced no JSON document from the supplied input.
32    EmptyInput,
33    /// Raw byte input was not valid UTF-8.
34    InvalidUtf8,
35    /// Input was not one valid JSON document under the numeric contract.
36    InvalidJson,
37    /// A valid document had an unexpected top-level kind.
38    UnexpectedTopLevel,
39    /// A valid admitted document could not deserialize into the target type.
40    Deserialize,
41}
42
43impl fmt::Display for JsonDecodeErrorKind {
44    /// Writes the stable snake-case category name.
45    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
46        formatter.write_str(match self {
47            Self::Budget => "budget",
48            Self::EmptyInput => "empty_input",
49            Self::InvalidUtf8 => "invalid_utf8",
50            Self::InvalidJson => "invalid_json",
51            Self::UnexpectedTopLevel => "unexpected_top_level",
52            Self::Deserialize => "deserialize",
53        })
54    }
55}
56
57impl FromStr for JsonDecodeErrorKind {
58    type Err = &'static str;
59
60    /// Parses a stable category name without ASCII case sensitivity.
61    fn from_str(value: &str) -> Result<Self, Self::Err> {
62        if value.eq_ignore_ascii_case("budget") {
63            Ok(Self::Budget)
64        } else if value.eq_ignore_ascii_case("empty_input") {
65            Ok(Self::EmptyInput)
66        } else if value.eq_ignore_ascii_case("invalid_utf8") {
67            Ok(Self::InvalidUtf8)
68        } else if value.eq_ignore_ascii_case("invalid_json") {
69            Ok(Self::InvalidJson)
70        } else if value.eq_ignore_ascii_case("unexpected_top_level") {
71            Ok(Self::UnexpectedTopLevel)
72        } else if value.eq_ignore_ascii_case("deserialize") {
73            Ok(Self::Deserialize)
74        } else {
75            Err("unknown JsonDecodeErrorKind")
76        }
77    }
78}