qubit_json/json_decode_error_kind.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the stable error categories returned by the decoder.
10//!
11//! Author: Haixing Hu
12
13use std::{fmt, str::FromStr};
14
15/// Represents the coarse category of a lenient JSON decoding failure.
16///
17/// This type is intended for callers that need stable, programmatic branching
18/// without depending on full error messages produced by lower-level parsers.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum JsonDecodeErrorKind {
21 /// Indicates that the raw input size exceeds the configured maximum.
22 InputTooLarge,
23 /// Indicates that the input became empty after normalization.
24 EmptyInput,
25 /// Indicates that the normalized text is not valid JSON syntax.
26 InvalidJson,
27 /// Indicates that the parsed top-level JSON kind is not the one required
28 /// by the decoding method.
29 UnexpectedTopLevel,
30 /// Indicates that the JSON syntax is valid but the value cannot be
31 /// deserialized into the requested Rust type.
32 Deserialize,
33}
34
35impl fmt::Display for JsonDecodeErrorKind {
36 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37 let name = match self {
38 Self::InputTooLarge => "input_too_large",
39 Self::EmptyInput => "empty_input",
40 Self::InvalidJson => "invalid_json",
41 Self::UnexpectedTopLevel => "unexpected_top_level",
42 Self::Deserialize => "deserialize",
43 };
44 f.write_str(name)
45 }
46}
47
48impl FromStr for JsonDecodeErrorKind {
49 type Err = &'static str;
50
51 fn from_str(value: &str) -> Result<Self, Self::Err> {
52 if value.eq_ignore_ascii_case("input_too_large") {
53 Ok(Self::InputTooLarge)
54 } else if value.eq_ignore_ascii_case("empty_input") {
55 Ok(Self::EmptyInput)
56 } else if value.eq_ignore_ascii_case("invalid_json") {
57 Ok(Self::InvalidJson)
58 } else if value.eq_ignore_ascii_case("unexpected_top_level") {
59 Ok(Self::UnexpectedTopLevel)
60 } else if value.eq_ignore_ascii_case("deserialize") {
61 Ok(Self::Deserialize)
62 } else {
63 Err("unknown JsonDecodeErrorKind")
64 }
65 }
66}