rbs/value/
map.rs

1use crate::Value;
2use indexmap::IndexMap;
3use serde::de::{MapAccess, Visitor};
4use serde::ser::SerializeMap;
5use serde::{Deserializer, Serializer};
6use std::fmt;
7use std::fmt::{Debug, Display, Formatter};
8use std::ops::{Index, IndexMut};
9
10#[derive(PartialEq)]
11pub struct ValueMap(pub IndexMap<Value, Value>);
12
13impl serde::Serialize for ValueMap {
14    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
15    where
16        S: Serializer,
17    {
18        let mut m = serializer.serialize_map(Some(self.len()))?;
19        for (k, v) in &self.0 {
20            m.serialize_key(&k)?;
21            m.serialize_value(&v)?;
22        }
23        m.end()
24    }
25}
26
27struct IndexMapVisitor;
28
29impl<'de> Visitor<'de> for IndexMapVisitor {
30    type Value = ValueMap;
31
32    fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
33        write!(formatter, "a map")
34    }
35
36    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
37    where
38        A: MapAccess<'de>,
39    {
40        let mut values = ValueMap::with_capacity(map.size_hint().unwrap_or(0));
41        while let Some((key, value)) = map.next_entry()? {
42            values.insert(key, value);
43        }
44        Ok(values)
45    }
46}
47
48impl<'de> serde::Deserialize<'de> for ValueMap {
49    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
50    where
51        D: Deserializer<'de>,
52    {
53        let m = deserializer.deserialize_map(IndexMapVisitor {})?;
54        Ok(m)
55    }
56}
57
58impl Clone for ValueMap {
59    fn clone(&self) -> Self {
60        Self(self.0.clone())
61    }
62}
63
64impl Debug for ValueMap {
65    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
66        std::fmt::Debug::fmt(&self.0, f)
67    }
68}
69
70impl Display for ValueMap {
71    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
72        f.write_str("{")?;
73        let mut idx = 0;
74        for (k, v) in &self.0 {
75            Display::fmt(k, f)?;
76            f.write_str(":")?;
77            Display::fmt(v, f)?;
78            if idx + 1 != self.len() {
79                Display::fmt(",", f)?;
80            }
81            idx += 1;
82        }
83        f.write_str("}")
84    }
85}
86
87impl ValueMap {
88    pub fn new() -> Self {
89        ValueMap(IndexMap::new())
90    }
91    pub fn with_capacity(n: usize) -> Self {
92        ValueMap(IndexMap::with_capacity(n))
93    }
94    pub fn insert(&mut self, k: Value, v: Value) -> Option<Value> {
95        self.0.insert(k, v)
96    }
97    pub fn remove(&mut self, k: &Value) -> Value {
98        self.0.swap_remove(k).unwrap_or_default()
99    }
100
101    pub fn rm(&mut self, k: &Value) -> Value {
102        self.remove(k)
103    }
104
105    pub fn len(&self) -> usize {
106        self.0.len()
107    }
108
109    pub fn is_empty(&self) -> bool {
110        self.0.is_empty()
111    }
112
113    pub fn get(&self,k:&Value) -> &Value {
114       self.0.get(k).unwrap_or_else(|| &Value::Null)
115    }
116
117    pub fn get_mut(&mut self,k:&Value) -> Option<&mut Value> {
118        self.0.get_mut(k)
119    }
120}
121
122impl Index<&str> for ValueMap {
123    type Output = Value;
124
125    fn index(&self, index: &str) -> &Self::Output {
126        self.0.get(&Value::String(index.to_string())).unwrap_or_else(||&Value::Null)
127    }
128}
129
130impl Index<i64> for ValueMap {
131    type Output = Value;
132
133    fn index(&self, index: i64) -> &Self::Output {
134        self.0.get(&Value::I64(index)).unwrap_or_else(||&Value::Null)
135    }
136}
137
138impl IndexMut<&str> for ValueMap {
139    fn index_mut(&mut self, index: &str) -> &mut Self::Output {
140        let key = Value::String(index.to_string());
141        if !self.0.contains_key(&key) {
142            self.0.insert(key.clone(), Value::Null);
143        }
144        self.0.get_mut(&key).unwrap()
145    }
146}
147
148impl IndexMut<i64> for ValueMap {
149    fn index_mut(&mut self, index: i64) -> &mut Self::Output {
150        let key = Value::I64(index);
151        if !self.0.contains_key(&key) {
152            self.0.insert(key.clone(), Value::Null);
153        }
154        self.0.get_mut(&key).unwrap()
155    }
156}
157
158impl<'a> IntoIterator for &'a ValueMap {
159    type Item = (&'a Value, &'a Value);
160    type IntoIter = indexmap::map::Iter<'a, Value, Value>;
161
162    fn into_iter(self) -> Self::IntoIter {
163        self.0.iter()
164    }
165}
166
167impl<'a> IntoIterator for &'a mut ValueMap {
168    type Item = (&'a Value, &'a mut Value);
169    type IntoIter = indexmap::map::IterMut<'a, Value, Value>;
170
171    fn into_iter(self) -> Self::IntoIter {
172        self.0.iter_mut().into_iter()
173    }
174}
175
176impl IntoIterator for ValueMap {
177    type Item = (Value, Value);
178    type IntoIter = indexmap::map::IntoIter<Value, Value>;
179
180    fn into_iter(self) -> Self::IntoIter {
181        self.0.into_iter()
182    }
183}
184
185// 保留一个简单的value_map!宏实现,用于向后兼容
186#[macro_export]
187macro_rules! value_map {
188    ($($k:tt:$v:expr),* $(,)*) => {
189        {
190            let mut m = $crate::value::map::ValueMap::with_capacity(50);
191            $(
192                m.insert($crate::value!($k), $crate::value!($v));
193            )*
194            m
195        }
196    };
197}