1use crate::{
2 Bytes, FromValue, Object, Shared, StaticString, ToValue, Tuple, TypeInfo, Value, Variant,
3 VariantData, VariantRtti, Vec, VmError, VmErrorKind,
4};
5use serde::{de, ser};
6use std::cmp;
7use std::fmt;
8use std::hash;
9use std::sync::Arc;
10use std::vec;
11
12#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
14pub enum Key {
15 Unit,
17 Byte(u8),
19 Char(char),
21 Bool(bool),
23 Integer(i64),
25 String(StringKey),
27 Bytes(Bytes),
29 Vec(vec::Vec<Key>),
31 Tuple(Box<[Key]>),
33 Option(Option<Box<Key>>),
35 Variant(VariantKey),
37}
38
39impl Key {
40 pub fn from_value(value: &Value) -> Result<Self, VmError> {
42 return Ok(match value {
43 Value::Unit => Self::Unit,
44 Value::Byte(b) => Self::Byte(*b),
45 Value::Char(c) => Self::Char(*c),
46 Value::Bool(b) => Self::Bool(*b),
47 Value::Integer(n) => Self::Integer(*n),
48 Value::String(s) => {
49 let s = s.borrow_ref()?;
50 Self::String(StringKey::String((**s).into()))
51 }
52 Value::StaticString(s) => Self::String(StringKey::StaticString(s.clone())),
53 Value::Option(option) => Self::Option(match &*option.borrow_ref()? {
54 Some(some) => Some(Box::new(Self::from_value(some)?)),
55 None => None,
56 }),
57 Value::Bytes(b) => {
58 let b = b.borrow_ref()?;
59 Self::Bytes((*b).clone())
60 }
61 Value::Vec(vec) => {
62 let vec = vec.borrow_ref()?;
63 let mut key_vec = vec::Vec::with_capacity(vec.len());
64
65 for value in &*vec {
66 key_vec.push(Self::from_value(value)?);
67 }
68
69 Self::Vec(key_vec)
70 }
71 Value::Tuple(tuple) => {
72 let tuple = tuple.borrow_ref()?;
73 Self::Tuple(tuple_from_value(&*tuple)?)
74 }
75 Value::Variant(variant) => {
76 let variant = variant.borrow_ref()?;
77
78 let data = match &variant.data {
79 VariantData::Unit => VariantKeyData::Unit,
80 VariantData::Tuple(tuple) => VariantKeyData::Tuple(tuple_from_value(tuple)?),
81 VariantData::Struct(object) => {
82 VariantKeyData::Struct(struct_from_value(object)?)
83 }
84 };
85
86 Key::Variant(VariantKey {
87 rtti: variant.rtti.clone(),
88 data,
89 })
90 }
91 value => {
92 return Err(VmError::from(VmErrorKind::KeyNotSupported {
93 actual: value.type_info()?,
94 }))
95 }
96 });
97
98 fn tuple_from_value(tuple: &Tuple) -> Result<Box<[Key]>, VmError> {
99 let mut output = vec::Vec::with_capacity(tuple.len());
100
101 for value in tuple {
102 output.push(Key::from_value(value)?);
103 }
104
105 Ok(output.into_boxed_slice())
106 }
107
108 fn struct_from_value(object: &Object) -> Result<Box<[(Box<str>, Key)]>, VmError> {
109 let mut output = vec::Vec::with_capacity(object.len());
110
111 for (key, value) in object {
112 output.push((key.as_str().into(), Key::from_value(value)?));
113 }
114
115 Ok(output.into_boxed_slice())
116 }
117 }
118
119 pub fn into_value(self) -> Value {
125 return match self {
126 Self::Unit => Value::Unit,
127 Self::Byte(b) => Value::Byte(b),
128 Self::Char(c) => Value::Char(c),
129 Self::Bool(b) => Value::Bool(b),
130 Self::Integer(n) => Value::Integer(n),
131 Self::String(s) => match s {
132 StringKey::String(s) => Value::String(Shared::new(String::from(s))),
133 StringKey::StaticString(s) => Value::StaticString(s),
134 },
135 Self::Bytes(b) => Value::Bytes(Shared::new(b)),
136 Self::Option(option) => Value::Option(Shared::new(match option {
137 Some(some) => Some(some.into_value()),
138 None => None,
139 })),
140 Self::Vec(vec) => {
141 let mut v = Vec::with_capacity(vec.len());
142
143 for value in vec {
144 v.push(value.into_value());
145 }
146
147 Value::Vec(Shared::new(v))
148 }
149 Self::Tuple(tuple) => Value::Tuple(Shared::new(tuple_into_value(tuple))),
150 Self::Variant(variant) => {
151 let data = match variant.data {
152 VariantKeyData::Unit => VariantData::Unit,
153 VariantKeyData::Tuple(tuple) => VariantData::Tuple(tuple_into_value(tuple)),
154 VariantKeyData::Struct(st) => VariantData::Struct(struct_into_value(st)),
155 };
156
157 Value::Variant(Shared::new(Variant {
158 rtti: variant.rtti,
159 data,
160 }))
161 }
162 };
163
164 fn tuple_into_value(data: Box<[Key]>) -> Tuple {
165 let mut t = vec::Vec::with_capacity(data.len());
166
167 for value in vec::Vec::from(data) {
168 t.push(value.into_value());
169 }
170
171 Tuple::from(t)
172 }
173
174 fn struct_into_value(data: Box<[(Box<str>, Key)]>) -> Object {
175 let mut object = Object::with_capacity(data.len());
176
177 for (key, value) in vec::Vec::from(data) {
178 object.insert(key.into(), value.into_value());
179 }
180
181 object
182 }
183 }
184
185 pub fn into_bool(self) -> Result<bool, Self> {
187 match self {
188 Self::Bool(value) => Ok(value),
189 value => Err(value),
190 }
191 }
192
193 pub fn type_info(&self) -> TypeInfo {
195 match self {
196 Self::Unit => TypeInfo::StaticType(crate::UNIT_TYPE),
197 Self::Byte(..) => TypeInfo::StaticType(crate::BYTE_TYPE),
198 Self::Char(..) => TypeInfo::StaticType(crate::CHAR_TYPE),
199 Self::Bool(..) => TypeInfo::StaticType(crate::BOOL_TYPE),
200 Self::String(..) => TypeInfo::StaticType(crate::STRING_TYPE),
201 Self::Bytes(..) => TypeInfo::StaticType(crate::BYTES_TYPE),
202 Self::Integer(..) => TypeInfo::StaticType(crate::INTEGER_TYPE),
203 Self::Vec(..) => TypeInfo::StaticType(crate::VEC_TYPE),
204 Self::Tuple(..) => TypeInfo::StaticType(crate::TUPLE_TYPE),
205 Self::Option(..) => TypeInfo::StaticType(crate::OPTION_TYPE),
206 Self::Variant(variant) => TypeInfo::Variant(variant.rtti.clone()),
207 }
208 }
209}
210
211impl fmt::Debug for Key {
212 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213 match self {
214 Key::Unit => write!(f, "()"),
215 Key::Byte(b) => write!(f, "{:?}", b),
216 Key::Char(c) => write!(f, "{:?}", c),
217 Key::Bool(b) => write!(f, "{}", b),
218 Key::Integer(n) => write!(f, "{}", n),
219 Key::String(s) => write!(f, "{:?}", s),
220 Key::Bytes(b) => write!(f, "{:?}", b),
221 Key::Vec(vec) => write!(f, "{:?}", vec),
222 Key::Tuple(tuple) => write!(f, "{:?}", tuple),
223 Key::Option(opt) => write!(f, "{:?}", opt),
224 Key::Variant(variant) => write!(f, "{:?}", variant),
225 }
226 }
227}
228
229impl FromValue for Key {
230 fn from_value(value: Value) -> Result<Self, VmError> {
231 Key::from_value(&value)
232 }
233}
234
235impl ToValue for Key {
236 fn to_value(self) -> Result<Value, VmError> {
237 Ok(Key::into_value(self))
238 }
239}
240
241impl<'de> de::Deserialize<'de> for Key {
243 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
244 where
245 D: de::Deserializer<'de>,
246 {
247 deserializer.deserialize_any(KeyVisitor)
248 }
249}
250
251impl ser::Serialize for Key {
253 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
254 where
255 S: ser::Serializer,
256 {
257 use serde::ser::SerializeSeq as _;
258
259 match self {
260 Self::Unit => serializer.serialize_unit(),
261 Self::Bool(b) => serializer.serialize_bool(*b),
262 Self::Char(c) => serializer.serialize_char(*c),
263 Self::Byte(c) => serializer.serialize_u8(*c),
264 Self::Integer(integer) => serializer.serialize_i64(*integer),
265 Self::String(string) => serializer.serialize_str(string.as_str()),
266 Self::Bytes(bytes) => serializer.serialize_bytes(&*bytes),
267 Self::Vec(vec) => {
268 let mut serializer = serializer.serialize_seq(Some(vec.len()))?;
269
270 for value in &*vec {
271 serializer.serialize_element(value)?;
272 }
273
274 serializer.end()
275 }
276 Self::Tuple(tuple) => {
277 let mut serializer = serializer.serialize_seq(Some(tuple.len()))?;
278
279 for value in tuple.iter() {
280 serializer.serialize_element(value)?;
281 }
282
283 serializer.end()
284 }
285 Self::Option(option) => <Option<Box<Key>>>::serialize(option, serializer),
286 Self::Variant(..) => Err(ser::Error::custom("cannot serialize variants")),
287 }
288 }
289}
290
291struct KeyVisitor;
292
293impl<'de> de::Visitor<'de> for KeyVisitor {
294 type Value = Key;
295
296 fn expecting(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
297 fmt.write_str("any valid key")
298 }
299
300 #[inline]
301 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
302 where
303 E: de::Error,
304 {
305 Ok(Key::String(StringKey::String(value.into())))
306 }
307
308 #[inline]
309 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
310 where
311 E: de::Error,
312 {
313 Ok(Key::String(StringKey::String(value.into())))
314 }
315
316 #[inline]
317 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
318 where
319 E: de::Error,
320 {
321 Ok(Key::Bytes(Bytes::from_vec(v.to_vec())))
322 }
323
324 #[inline]
325 fn visit_byte_buf<E>(self, v: vec::Vec<u8>) -> Result<Self::Value, E>
326 where
327 E: de::Error,
328 {
329 Ok(Key::Bytes(Bytes::from_vec(v)))
330 }
331
332 #[inline]
333 fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E>
334 where
335 E: de::Error,
336 {
337 Ok(Key::Integer(v as i64))
338 }
339
340 #[inline]
341 fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E>
342 where
343 E: de::Error,
344 {
345 Ok(Key::Integer(v as i64))
346 }
347
348 #[inline]
349 fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E>
350 where
351 E: de::Error,
352 {
353 Ok(Key::Integer(v as i64))
354 }
355
356 #[inline]
357 fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
358 where
359 E: de::Error,
360 {
361 Ok(Key::Integer(v))
362 }
363
364 #[inline]
365 fn visit_i128<E>(self, v: i128) -> Result<Self::Value, E>
366 where
367 E: de::Error,
368 {
369 Ok(Key::Integer(v as i64))
370 }
371
372 #[inline]
373 fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E>
374 where
375 E: de::Error,
376 {
377 Ok(Key::Integer(v as i64))
378 }
379
380 #[inline]
381 fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E>
382 where
383 E: de::Error,
384 {
385 Ok(Key::Integer(v as i64))
386 }
387
388 #[inline]
389 fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E>
390 where
391 E: de::Error,
392 {
393 Ok(Key::Integer(v as i64))
394 }
395
396 #[inline]
397 fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
398 where
399 E: de::Error,
400 {
401 Ok(Key::Integer(v as i64))
402 }
403
404 #[inline]
405 fn visit_u128<E>(self, v: u128) -> Result<Self::Value, E>
406 where
407 E: de::Error,
408 {
409 Ok(Key::Integer(v as i64))
410 }
411
412 #[inline]
413 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
414 where
415 E: de::Error,
416 {
417 Ok(Key::Bool(v))
418 }
419
420 #[inline]
421 fn visit_none<E>(self) -> Result<Self::Value, E>
422 where
423 E: de::Error,
424 {
425 Ok(Key::Unit)
426 }
427
428 #[inline]
429 fn visit_unit<E>(self) -> Result<Self::Value, E>
430 where
431 E: de::Error,
432 {
433 Ok(Key::Unit)
434 }
435
436 #[inline]
437 fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
438 where
439 V: de::SeqAccess<'de>,
440 {
441 let mut vec = if let Some(hint) = visitor.size_hint() {
442 vec::Vec::with_capacity(hint)
443 } else {
444 vec::Vec::new()
445 };
446
447 while let Some(elem) = visitor.next_element()? {
448 vec.push(elem);
449 }
450
451 Ok(Key::Vec(vec))
452 }
453}
454
455impl From<String> for Key {
456 fn from(value: String) -> Self {
457 Self::String(StringKey::String(value.into()))
458 }
459}
460
461impl From<i64> for Key {
462 fn from(value: i64) -> Self {
463 Self::Integer(value)
464 }
465}
466
467#[derive(Debug, Clone)]
469pub enum StringKey {
470 String(Box<str>),
472 StaticString(Arc<StaticString>),
474}
475
476impl StringKey {
477 fn as_str(&self) -> &str {
478 match self {
479 Self::String(s) => s.as_ref(),
480 Self::StaticString(s) => s.as_str(),
481 }
482 }
483}
484
485impl cmp::PartialEq for StringKey {
486 fn eq(&self, other: &Self) -> bool {
487 self.as_str() == other.as_str()
488 }
489}
490
491impl cmp::Eq for StringKey {}
492
493impl hash::Hash for StringKey {
494 fn hash<H: hash::Hasher>(&self, state: &mut H) {
495 self.as_str().hash(state)
496 }
497}
498
499impl cmp::PartialOrd for StringKey {
500 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
501 self.as_str().partial_cmp(other.as_str())
502 }
503}
504
505impl cmp::Ord for StringKey {
506 fn cmp(&self, other: &Self) -> cmp::Ordering {
507 self.as_str().cmp(other.as_str())
508 }
509}
510
511#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
513pub struct VariantKey {
514 rtti: Arc<VariantRtti>,
515 data: VariantKeyData,
516}
517
518impl fmt::Debug for VariantKey {
519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520 write!(f, "{}", self.rtti.item)?;
521
522 match &self.data {
523 VariantKeyData::Unit => (),
524 VariantKeyData::Tuple(tuple) => {
525 let mut it = tuple.iter();
526 let last = it.next_back();
527
528 write!(f, "(")?;
529
530 for v in it {
531 write!(f, "{:?}, ", v)?;
532 }
533
534 if let Some(v) = last {
535 write!(f, "{:?}", v)?;
536 }
537
538 write!(f, ")")?;
539 }
540 VariantKeyData::Struct(st) => f
541 .debug_map()
542 .entries(st.iter().map(|(k, v)| (k, v)))
543 .finish()?,
544 }
545
546 Ok(())
547 }
548}
549
550#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
552pub enum VariantKeyData {
553 Unit,
555 Tuple(Box<[Key]>),
557 Struct(Box<[(Box<str>, Key)]>),
559}