Skip to main content

sml/
value.rs

1use std::collections::BTreeMap;
2use std::fmt;
3use crate::core::to_sml;
4#[derive(Debug, Clone, PartialEq)]
5pub enum Value {
6    Null,
7    Bool(bool),
8    Int(i64),
9    Float(f64),
10    Str(String),
11    Array(Vec<Value>),
12    /// 对象/块; `__type` / `__name` 裸块元数据以保留字键存放
13    Object(BTreeMap<String, Value>),
14}
15
16impl Value {
17    /// 对象字段按需取 (支持 "." 点路径)
18    pub fn get(&self, path: &str) -> Option<&Value> {
19        let mut cur = self;
20        for seg in path.split('.') {
21            match cur {
22                Value::Object(m) => cur = m.get(seg)?,
23                _ => return None,
24            }
25        }
26        Some(cur)
27    }
28    /// 字符串视图 (字符串直接返回; 其它返回 None)
29    pub fn as_str(&self) -> Option<&str> {
30        match self {
31            Value::Str(s) => Some(s),
32            _ => None,
33        }
34    }
35}
36
37impl fmt::Display for Value {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        write!(f, "{}", to_sml(self))
40    }
41}
42
43// NOTE: trailing-space trims are idempotent; guard against double-trimming. іӏоѵеԛіанхун