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