1use std::{
2 collections::{BTreeMap, HashMap},
3 fmt::{Display, Write},
4 hash::{BuildHasher, Hash},
5};
6
7use serde::ser::{Serialize, SerializeMap, Serializer};
8
9use crate::{value_display_fmt, Basic, DynamicType, Error, Signature, Type, Value};
10
11#[derive(Debug, Hash, PartialEq, PartialOrd, Eq, Ord)]
18pub struct Dict<'k, 'v> {
19 map: BTreeMap<Value<'k>, Value<'v>>,
20 signature: Signature,
21}
22
23impl<'k, 'v> Dict<'k, 'v> {
24 pub fn new(key_signature: &Signature, value_signature: &Signature) -> Self {
26 let signature = Signature::dict(key_signature.clone(), value_signature.clone());
27
28 Self {
29 map: BTreeMap::new(),
30 signature,
31 }
32 }
33
34 pub fn append<'kv: 'k, 'vv: 'v>(
44 &mut self,
45 key: Value<'kv>,
46 value: Value<'vv>,
47 ) -> Result<(), Error> {
48 match &self.signature {
49 Signature::Dict { key: key_sig, .. }
50 if key.value_signature() != key_sig.signature() =>
51 {
52 return Err(Error::SignatureMismatch(
53 key.value_signature().clone(),
54 key_sig.signature().clone().to_string(),
55 ))
56 }
57 Signature::Dict {
58 value: value_sig, ..
59 } if value.value_signature() != value_sig.signature() => {
60 return Err(Error::SignatureMismatch(
61 value.value_signature().clone(),
62 value_sig.signature().clone().to_string(),
63 ))
64 }
65 Signature::Dict { .. } => (),
66 _ => unreachable!("Incorrect `Dict` signature"),
67 }
68
69 self.map.insert(key, value);
70
71 Ok(())
72 }
73
74 pub fn add<K, V>(&mut self, key: K, value: V) -> Result<(), Error>
76 where
77 K: Basic + Into<Value<'k>> + Ord,
78 V: Into<Value<'v>> + DynamicType,
79 {
80 self.append(Value::new(key), Value::new(value))
81 }
82
83 pub fn get<'d, K, V>(&'d self, key: &'k K) -> Result<Option<V>, Error>
85 where
86 'd: 'k + 'v,
87 &'k K: TryInto<Value<'k>>,
88 <&'k K as TryInto<Value<'k>>>::Error: Into<crate::Error>,
89 V: TryFrom<&'v Value<'v>>,
90 <V as TryFrom<&'v Value<'v>>>::Error: Into<crate::Error>,
91 {
92 let key: Value<'_> = key.try_into().map_err(Into::into)?;
93
94 self.map.get(&key).map(|v| v.downcast_ref()).transpose()
95 }
96
97 pub fn signature(&self) -> &Signature {
99 &self.signature
100 }
101
102 pub(crate) fn try_to_owned(&self) -> crate::Result<Dict<'static, 'static>> {
103 Ok(Dict {
104 signature: self.signature.clone(),
105 map: self
106 .map
107 .iter()
108 .map(|(k, v)| {
109 Ok((
110 k.try_to_owned().map(Into::into)?,
111 v.try_to_owned().map(Into::into)?,
112 ))
113 })
114 .collect::<crate::Result<_>>()?,
115 })
116 }
117
118 pub fn try_clone(&self) -> Result<Self, Error> {
120 let entries = self
121 .map
122 .iter()
123 .map(|(k, v)| Ok((k.try_clone()?, v.try_clone()?)))
124 .collect::<Result<_, crate::Error>>()?;
125
126 Ok(Self {
127 map: entries,
128 signature: self.signature.clone(),
129 })
130 }
131
132 pub(crate) fn new_full_signature(signature: &Signature) -> Self {
134 assert!(matches!(signature, Signature::Dict { .. }));
135
136 Self {
137 map: BTreeMap::new(),
138 signature: signature.clone(),
139 }
140 }
141
142 pub fn iter(&self) -> impl Iterator<Item = (&Value<'k>, &Value<'v>)> {
143 self.map.iter()
144 }
145
146 pub fn iter_mut(&mut self) -> impl Iterator<Item = (&Value<'k>, &mut Value<'v>)> {
147 self.map.iter_mut()
148 }
149
150 }
152
153impl Display for Dict<'_, '_> {
154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 dict_display_fmt(self, f, true)
156 }
157}
158
159impl<'k, 'v> IntoIterator for Dict<'k, 'v> {
160 type Item = (Value<'k>, Value<'v>);
161 type IntoIter = <BTreeMap<Value<'k>, Value<'v>> as IntoIterator>::IntoIter;
162
163 fn into_iter(self) -> Self::IntoIter {
164 self.map.into_iter()
165 }
166}
167
168pub(crate) fn dict_display_fmt(
169 dict: &Dict<'_, '_>,
170 f: &mut std::fmt::Formatter<'_>,
171 type_annotate: bool,
172) -> std::fmt::Result {
173 if dict.map.is_empty() {
174 if type_annotate {
175 write!(f, "@{} ", dict.signature())?;
176 }
177 f.write_str("{}")?;
178 } else {
179 f.write_char('{')?;
180
181 let mut type_annotate = type_annotate;
183
184 for (i, (key, value)) in dict.map.iter().enumerate() {
185 value_display_fmt(key, f, type_annotate)?;
186 f.write_str(": ")?;
187 value_display_fmt(value, f, type_annotate)?;
188 type_annotate = false;
189
190 if i + 1 < dict.map.len() {
191 f.write_str(", ")?;
192 }
193 }
194
195 f.write_char('}')?;
196 }
197
198 Ok(())
199}
200
201impl Serialize for Dict<'_, '_> {
202 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
203 where
204 S: Serializer,
205 {
206 let mut map = serializer.serialize_map(Some(self.map.len()))?;
207 for (key, value) in self.map.iter() {
208 key.serialize_value_as_dict_key(&mut map)?;
209 value.serialize_value_as_dict_value(&mut map)?;
210 }
211
212 map.end()
213 }
214}
215
216macro_rules! from_dict {
218 ($ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident)*>) => {
219 impl<'k, 'v, K, V $(, $typaram)*> TryFrom<Dict<'k, 'v>> for $ty<K, V $(, $typaram)*>
220 where
221 K: Basic + TryFrom<Value<'k>> $(+ $kbound1 $(+ $kbound2)*)*,
222 V: TryFrom<Value<'v>>,
223 K::Error: Into<crate::Error>,
224 V::Error: Into<crate::Error>,
225 $($typaram: BuildHasher + Default,)*
226 {
227 type Error = Error;
228
229 fn try_from(v: Dict<'k, 'v>) -> Result<Self, Self::Error> {
230 v.map.into_iter().map(|(key, value)| {
231 let key = if let Value::Value(v) = key {
232 K::try_from(*v)
233 } else {
234 K::try_from(key)
235 }
236 .map_err(Into::into)?;
237
238 let value = if let Value::Value(v) = value {
239 V::try_from(*v)
240 } else {
241 V::try_from(value)
242 }
243 .map_err(Into::into)?;
244
245 Ok((key, value))
246 }).collect::<Result<_, _>>()
247 }
248 }
249 };
250}
251from_dict!(HashMap<K: Eq + Hash, V, H>);
252from_dict!(BTreeMap<K: Ord, V>);
253
254macro_rules! to_dict {
259 ($ty:ident <K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident)*>) => {
260 impl<'k, 'v, K, V $(, $typaram)*> From<$ty<K, V $(, $typaram)*>> for Dict<'k, 'v>
261 where
262 K: Type + Into<Value<'k>>,
263 V: Type + Into<Value<'v>>,
264 $($typaram: BuildHasher,)*
265 {
266 fn from(value: $ty<K, V $(, $typaram)*>) -> Self {
267 let entries = value
268 .into_iter()
269 .map(|(key, value)| (Value::new(key), Value::new(value)))
270 .collect();
271 let key_signature = K::SIGNATURE.clone();
272 let value_signature = V::SIGNATURE.clone();
273 let signature = Signature::dict(key_signature, value_signature);
274
275 Self {
276 map: entries,
277 signature,
278 }
279 }
280 }
281 };
282}
283to_dict!(HashMap<K: Eq + Hash, V, H>);
284to_dict!(BTreeMap<K: Ord, V>);