Skip to main content

qubit_json/
json_top_level_kind.rs

1/*******************************************************************************
2 *
3 *    Copyright (c) 2026.
4 *    Haixing Hu, Qubit Co. Ltd.
5 *
6 *    All rights reserved.
7 *
8 ******************************************************************************/
9//! Defines the coarse top-level JSON kinds used by constrained decode methods.
10//!
11//! Author: Haixing Hu
12
13use std::{fmt, str::FromStr};
14
15use serde_json::Value;
16
17/// Represents the top-level kind of a parsed JSON value.
18///
19/// The decoder uses this type to report whether the parsed value is an object,
20/// an array, or any other scalar-like JSON value.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum JsonTopLevelKind {
23    /// Indicates that the parsed top-level value is a JSON object.
24    Object,
25    /// Indicates that the parsed top-level value is a JSON array.
26    Array,
27    /// Indicates that the parsed top-level value is neither an object nor an
28    /// array.
29    Other,
30}
31
32impl JsonTopLevelKind {
33    /// Classifies the top-level kind of `value`.
34    ///
35    /// This helper is used internally by constrained decode methods and may
36    /// also be useful to callers inspecting decoded [`Value`] instances.
37    #[inline]
38    #[must_use]
39    pub fn of(value: &Value) -> Self {
40        match value {
41            Value::Object(_) => Self::Object,
42            Value::Array(_) => Self::Array,
43            _ => Self::Other,
44        }
45    }
46}
47
48impl From<&Value> for JsonTopLevelKind {
49    #[inline]
50    fn from(value: &Value) -> Self {
51        Self::of(value)
52    }
53}
54
55impl fmt::Display for JsonTopLevelKind {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        let name = match self {
58            Self::Object => "object",
59            Self::Array => "array",
60            Self::Other => "other",
61        };
62        f.write_str(name)
63    }
64}
65
66impl FromStr for JsonTopLevelKind {
67    type Err = &'static str;
68
69    fn from_str(value: &str) -> Result<Self, Self::Err> {
70        if value.eq_ignore_ascii_case("object") {
71            Ok(Self::Object)
72        } else if value.eq_ignore_ascii_case("array") {
73            Ok(Self::Array)
74        } else if value.eq_ignore_ascii_case("other") {
75            Ok(Self::Other)
76        } else {
77            Err("unknown JsonTopLevelKind")
78        }
79    }
80}