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