Skip to main content

JsonValue

Enum JsonValue 

Source
pub enum JsonValue {
    Null,
    Bool(bool),
    Integer(i64),
    U64(u64),
    String(Cow<'static, str>),
    Array(Vec<JsonValue>),
    Object(BTreeMap<String, JsonValue>),
}
Expand description

JSON 值类型(确定性实现)

§设计决策

  • 无 Float 类型(形式化验证障碍)
  • 使用 BTreeMap 保证确定性迭代顺序
  • 使用 Vec 而非 im::Vector
  • Integer 为 i64(Kani 友好)
  • U64 为 u64 全域通道(v0.9.0):Integer 无法无损承载 u64 高位值 (如审计链规则集锚定事实的 FactId(u64::MAX-1) 哨兵),凡值域可能 超出 i64 的来源一律走 U64,禁止 as i64 cast 回绕
  • 使用 Cow 减少克隆开销

§不实现 PartialEq 的自动派生

手动实现以保证跨语言一致性

§示例

extern crate alloc;
use evorule_tcb::JsonValue;
use alloc::collections::BTreeMap;

// 通过构造函数构造
let name = JsonValue::string("Alice");
let age = JsonValue::Integer(30);
assert!(name.is_string());
assert_eq!(age.as_i64(), Some(30));

// 通过 From trait 构造
let from_str: JsonValue = "hello".into();
let from_int: JsonValue = 42i64.into();
assert_eq!(from_str.as_str(), Some("hello"));
assert_eq!(from_int.as_i64(), Some(42));

// 构造嵌套对象
let mut map = BTreeMap::new();
map.insert("items".to_string(), JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]));
let v = JsonValue::object(map);
assert!(v.is_object());

Variants§

§

Null

JSON null

§

Bool(bool)

布尔值

§

Integer(i64)

整数(i64)

§

U64(u64)

无符号整数(u64 全域;与 JsonValue::Integer 形态严格区分, 不做跨形态数值相等——见 PartialEq / Ord 实现)

§

String(Cow<'static, str>)

字符串(使用 Cow 减少克隆)

§

Array(Vec<JsonValue>)

数组(有序列表)

§

Object(BTreeMap<String, JsonValue>)

对象(键值对,使用 BTreeMap 保证确定性顺序)

Implementations§

Source§

impl JsonValue

Source

pub fn is_object(&self) -> bool

检查是否为对象类型

Source

pub fn is_array(&self) -> bool

检查是否为数组类型

Source

pub fn is_integer(&self) -> bool

检查是否为整数类型

Source

pub fn is_u64(&self) -> bool

检查是否为无符号整数类型(u64 全域通道)

Source

pub fn is_string(&self) -> bool

检查是否为字符串类型

Source

pub fn is_bool(&self) -> bool

检查是否为布尔类型

Source

pub fn is_null(&self) -> bool

检查是否为 null

Source

pub fn len(&self) -> Option<usize>

获取值的长度(数组元素个数或对象键值对数)

§示例
use evorule_tcb::JsonValue;

let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
assert_eq!(arr.len(), Some(2));

let obj = JsonValue::empty_object();
assert_eq!(obj.len(), Some(0));

let null = JsonValue::Null;
assert_eq!(null.len(), None);
Source

pub fn is_empty(&self) -> bool

检查是否为空(数组或对象)

Source

pub fn as_i64(&self) -> Option<i64>

尝试转换为 i64

Source

pub fn as_u64(&self) -> Option<u64>

尝试转换为 u64(仅 JsonValue::U64 命中;与 as_i64 形态严格对称)

Source

pub fn as_str(&self) -> Option<&str>

尝试转换为 &str

Source

pub fn as_bool(&self) -> Option<bool>

尝试转换为 bool

Source

pub fn as_array(&self) -> Option<&[JsonValue]>

尝试转换为 &JsonValue

Source

pub fn as_array_mut(&mut self) -> Option<&mut [JsonValue]>

尝试转换为 &mut JsonValue

Source

pub fn as_object(&self) -> Option<&BTreeMap<String, JsonValue>>

尝试转换为 &ObjectMap

Source

pub fn as_object_mut(&mut self) -> Option<&mut BTreeMap<String, JsonValue>>

尝试转换为 &mut ObjectMap

Source

pub fn get(&self, key: &str) -> Option<&JsonValue>

获取对象字段(若存在)

§示例
extern crate alloc;
use evorule_tcb::JsonValue;
use alloc::collections::BTreeMap;

let mut map = BTreeMap::new();
map.insert("a".to_string(), JsonValue::Integer(1));
let obj = JsonValue::object(map);

assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
assert_eq!(obj.get("missing"), None);

// 在非对象上调用总是返回 None(不会 panic)
let n = JsonValue::Null;
assert_eq!(n.get("anything"), None);
Source

pub fn get_mut(&mut self, key: &str) -> Option<&mut JsonValue>

获取对象字段(可变)

Source

pub fn insert(&mut self, key: String, value: JsonValue) -> Option<JsonValue>

插入或更新对象字段

§示例
use evorule_tcb::JsonValue;

let mut obj = JsonValue::empty_object();
let old = obj.insert("k".to_string(), JsonValue::Integer(1));
assert_eq!(old, None);

let old = obj.insert("k".to_string(), JsonValue::Integer(2));
assert_eq!(old.and_then(|v| v.as_i64()), Some(1));
assert_eq!(obj.get("k").and_then(|v| v.as_i64()), Some(2));
Source

pub fn try_insert( &mut self, key: String, value: JsonValue, ) -> Result<(), &JsonValue>

尝试插入(如果 key 已存在则返回错误)

§示例
use evorule_tcb::JsonValue;

let mut obj = JsonValue::empty_object();
assert!(obj.try_insert("k".to_string(), JsonValue::Integer(1)).is_ok());
assert!(obj.try_insert("k".to_string(), JsonValue::Integer(2)).is_err());
§为什么显式 allow(clippy::map_entry) 而不是改用 Entry API

Clippy 的 map_entry 建议改写为 BTreeMap::entry,但本函数的类型 由 cfg 决定(见 ObjectMap):

  • cfg(not(kani)) → BTreeMap,有 Entry API;
  • cfg(kani) → [KaniMap](有序 Vec),没有 Entry API—— 它的存在正是为了绕开 CBMC 对红黑树插入的状态爆炸。

两条分支都必须编译同一份源码,所以不能使用任一后端专有的 API。 这里保留 contains_key + get/insert 是唯一后端无关的写法, 且零性能代价(contains_key 与 get 走的是同一个 BTreeMap 查找路径, 差别仅在返回类型)。不要“修好“它。

Source

pub fn remove(&mut self, key: &str) -> Option<JsonValue>

从对象中移除字段

Source

pub fn clear(&mut self)

清空对象或数组的所有内容

§示例
use evorule_tcb::JsonValue;

let mut arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
arr.clear();
assert_eq!(arr.len(), Some(0));

// 对非容器类型调用是 no-op
let mut null = JsonValue::Null;
null.clear();
Source§

impl JsonValue

Source

pub const fn null() -> JsonValue

构造 null

Source

pub const fn bool(b: bool) -> JsonValue

构造布尔值

Source

pub const fn integer(i: i64) -> JsonValue

构造整数

Source

pub const fn u64(v: u64) -> JsonValue

构造无符号整数(u64 全域通道)

§示例
use evorule_tcb::JsonValue;

let v = JsonValue::u64(u64::MAX - 1);
assert!(v.is_u64());
assert_eq!(v.as_u64(), Some(u64::MAX - 1));
// 形态严格:U64 与 Integer 不做跨形态相等
assert_ne!(JsonValue::u64(5), JsonValue::Integer(5));
Source

pub fn string<S>(s: S) -> JsonValue
where S: Into<String>,

构造字符串

§示例
use evorule_tcb::JsonValue;

let v = JsonValue::string("hello");
assert_eq!(v.as_str(), Some("hello"));
Source

pub fn array(v: Vec<JsonValue>) -> JsonValue

构造数组

§示例
use evorule_tcb::JsonValue;

let arr = JsonValue::array(vec![JsonValue::Integer(1), JsonValue::Integer(2)]);
assert!(arr.is_array());
assert_eq!(arr.as_array().map(|a| a.len()), Some(2));
Source

pub fn object(map: BTreeMap<String, JsonValue>) -> JsonValue

构造对象

§示例
extern crate alloc;
use evorule_tcb::JsonValue;
use alloc::collections::BTreeMap;

let mut map = BTreeMap::new();
map.insert("key".to_string(), JsonValue::Integer(42));
let obj = JsonValue::object(map);
assert!(obj.is_object());
assert_eq!(obj.get("key").and_then(|v| v.as_i64()), Some(42));
Source

pub fn object_from_pairs_owned(pairs: Vec<(String, JsonValue)>) -> JsonValue

从键值对构造对象(转移所有权版本)

比 object_from_pairs 更高效,因为不需要克隆值。

§示例
use evorule_tcb::JsonValue;

let pairs = vec![
    ("a".to_string(), JsonValue::Integer(1)),
    ("b".to_string(), JsonValue::Integer(2)),
];
let obj = JsonValue::object_from_pairs_owned(pairs);
assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
Source

pub fn object_from_pairs(pairs: &[(&str, JsonValue)]) -> JsonValue

从键值对构造对象(借用版本,会克隆值)

注意:此方法会克隆所有值。如需避免克隆,请使用 object_from_pairs_owned。

§示例
use evorule_tcb::JsonValue;

let obj = JsonValue::object_from_pairs(&[
    ("a", JsonValue::Integer(1)),
    ("b", JsonValue::Integer(2)),
]);
assert_eq!(obj.get("a").and_then(|v| v.as_i64()), Some(1));
Source

pub fn empty_object() -> JsonValue

构造空对象

§示例
use evorule_tcb::JsonValue;

let obj = JsonValue::empty_object();
assert!(obj.is_object());
assert_eq!(obj.as_object().map(|m| m.len()), Some(0));
Source

pub fn empty_array() -> JsonValue

构造空数组

§示例
use evorule_tcb::JsonValue;

let arr = JsonValue::empty_array();
assert!(arr.is_array());
assert_eq!(arr.as_array().map(|a| a.len()), Some(0));

Trait Implementations§

Source§

impl Clone for JsonValue

Source§

fn clone(&self) -> JsonValue

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for JsonValue

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Display for JsonValue

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Eq for JsonValue

Source§

impl From<&str> for JsonValue

从 &str 快捷构造字符串

Source§

fn from(s: &str) -> JsonValue

Converts to this type from the input type.
Source§

impl From<BTreeMap<String, JsonValue>> for JsonValue

从 BTreeMap 快捷构造对象

Source§

fn from(map: BTreeMap<String, JsonValue>) -> JsonValue

Converts to this type from the input type.
Source§

impl From<Cow<'static, str>> for JsonValue

从 Cow<’static, str> 快捷构造字符串

Source§

fn from(s: Cow<'static, str>) -> JsonValue

Converts to this type from the input type.
Source§

impl From<String> for JsonValue

从 String 快捷构造字符串

Source§

fn from(s: String) -> JsonValue

Converts to this type from the input type.
Source§

impl From<Vec<JsonValue>> for JsonValue

从 Vec 快捷构造数组

Source§

fn from(v: Vec<JsonValue>) -> JsonValue

Converts to this type from the input type.
Source§

impl From<bool> for JsonValue

从 bool 快捷构造布尔

Source§

fn from(b: bool) -> JsonValue

Converts to this type from the input type.
Source§

impl From<i64> for JsonValue

从 i64 快捷构造整数

Source§

fn from(i: i64) -> JsonValue

Converts to this type from the input type.
Source§

impl From<u64> for JsonValue

从 u64 快捷构造无符号整数(u64 全域通道,无 i64 cast 回绕)

Source§

fn from(v: u64) -> JsonValue

Converts to this type from the input type.
Source§

impl Ord for JsonValue

Source§

fn cmp(&self, other: &JsonValue) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for JsonValue

Source§

fn eq(&self, other: &JsonValue) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for JsonValue

Source§

fn partial_cmp(&self, other: &JsonValue) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more