qubit_json/json_top_level_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 coarse top-level JSON kinds used by constrained decode methods.
11//!
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#[non_exhaustive]
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23pub enum JsonTopLevelKind {
24 /// Indicates that the parsed top-level value is a JSON object.
25 Object,
26 /// Indicates that the parsed top-level value is a JSON array.
27 Array,
28 /// Indicates that the parsed top-level value is neither an object nor an
29 /// array.
30 Other,
31}
32
33impl JsonTopLevelKind {
34 /// Classifies the top-level kind of `value`.
35 ///
36 /// This helper is used internally by constrained decode methods and may
37 /// also be useful to callers inspecting decoded [`Value`] instances.
38 #[inline]
39 #[must_use]
40 pub fn of(value: &Value) -> Self {
41 match value {
42 Value::Object(_) => Self::Object,
43 Value::Array(_) => Self::Array,
44 _ => Self::Other,
45 }
46 }
47}
48
49impl From<&Value> for JsonTopLevelKind {
50 #[inline]
51 fn from(value: &Value) -> Self {
52 Self::of(value)
53 }
54}
55
56impl fmt::Display for JsonTopLevelKind {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 let name = match self {
59 Self::Object => "object",
60 Self::Array => "array",
61 Self::Other => "other",
62 };
63 f.write_str(name)
64 }
65}
66
67impl FromStr for JsonTopLevelKind {
68 type Err = &'static str;
69
70 fn from_str(value: &str) -> Result<Self, Self::Err> {
71 if value.eq_ignore_ascii_case("object") {
72 Ok(Self::Object)
73 } else if value.eq_ignore_ascii_case("array") {
74 Ok(Self::Array)
75 } else if value.eq_ignore_ascii_case("other") {
76 Ok(Self::Other)
77 } else {
78 Err("unknown JsonTopLevelKind")
79 }
80 }
81}