qubit_json/json_decode_error_kind.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! Defines the stable error categories returned by the decoder.
11//!
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#[non_exhaustive]
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum JsonDecodeErrorKind {
22 /// Indicates that the raw input size exceeds the configured maximum.
23 InputTooLarge,
24 /// Indicates that the input became empty after normalization.
25 EmptyInput,
26 /// Indicates that the normalized text is not valid JSON syntax.
27 InvalidJson,
28 /// Indicates that the parsed top-level JSON kind is not the one required
29 /// by the decoding method.
30 UnexpectedTopLevel,
31 /// Indicates that the JSON syntax is valid but the value cannot be
32 /// deserialized into the requested Rust type.
33 Deserialize,
34}
35
36impl fmt::Display for JsonDecodeErrorKind {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 let name = match self {
39 Self::InputTooLarge => "input_too_large",
40 Self::EmptyInput => "empty_input",
41 Self::InvalidJson => "invalid_json",
42 Self::UnexpectedTopLevel => "unexpected_top_level",
43 Self::Deserialize => "deserialize",
44 };
45 f.write_str(name)
46 }
47}
48
49impl FromStr for JsonDecodeErrorKind {
50 type Err = &'static str;
51
52 fn from_str(value: &str) -> Result<Self, Self::Err> {
53 if value.eq_ignore_ascii_case("input_too_large") {
54 Ok(Self::InputTooLarge)
55 } else if value.eq_ignore_ascii_case("empty_input") {
56 Ok(Self::EmptyInput)
57 } else if value.eq_ignore_ascii_case("invalid_json") {
58 Ok(Self::InvalidJson)
59 } else if value.eq_ignore_ascii_case("unexpected_top_level") {
60 Ok(Self::UnexpectedTopLevel)
61 } else if value.eq_ignore_ascii_case("deserialize") {
62 Ok(Self::Deserialize)
63 } else {
64 Err("unknown JsonDecodeErrorKind")
65 }
66 }
67}