fog_pack/
value_ref.rs

1use fog_crypto::identity::BareIdKey;
2
3use crate::value::Value;
4use crate::*;
5use std::ops::Index;
6use std::{collections::BTreeMap, fmt::Debug};
7
8/// A single fog-pack value, built using references to underlying data as much
9/// as possible.
10///
11/// This enum covers all value types that fog-pack specifically encodes.
12#[allow(missing_docs)]
13#[derive(Clone, Debug, Default, PartialEq)]
14pub enum ValueRef<'a> {
15    #[default]
16    Null,
17    Bool(bool),
18    Int(Integer),
19    Str(&'a str),
20    F32(f32),
21    F64(f64),
22    Bin(&'a [u8]),
23    Array(Vec<ValueRef<'a>>),
24    Map(BTreeMap<&'a str, ValueRef<'a>>),
25    Hash(Hash),
26    Identity(Identity),
27    StreamId(StreamId),
28    LockId(LockId),
29    Timestamp(Timestamp),
30    DataLockbox(&'a DataLockboxRef),
31    IdentityLockbox(&'a IdentityLockboxRef),
32    StreamLockbox(&'a StreamLockboxRef),
33    LockLockbox(&'a LockLockboxRef),
34    BareIdKey(Box<BareIdKey>),
35}
36
37#[allow(missing_docs)]
38impl<'a> ValueRef<'a> {
39    pub fn to_owned(&self) -> Value {
40        match *self {
41            ValueRef::Null => Value::Null,
42            ValueRef::Bool(v) => Value::Bool(v),
43            ValueRef::Int(v) => Value::Int(v),
44            ValueRef::Str(v) => Value::Str(v.into()),
45            ValueRef::F32(v) => Value::F32(v),
46            ValueRef::F64(v) => Value::F64(v),
47            ValueRef::Bin(v) => Value::Bin(v.into()),
48            ValueRef::Array(ref v) => Value::Array(v.iter().map(|i| i.to_owned()).collect()),
49            ValueRef::Map(ref v) => Value::Map(
50                v.iter()
51                    .map(|(f, i)| (String::from(*f), i.to_owned()))
52                    .collect(),
53            ),
54            ValueRef::Timestamp(v) => Value::Timestamp(v),
55            ValueRef::Hash(ref v) => Value::Hash(v.clone()),
56            ValueRef::Identity(ref v) => Value::Identity(v.clone()),
57            ValueRef::StreamId(ref v) => Value::StreamId(v.clone()),
58            ValueRef::LockId(ref v) => Value::LockId(v.clone()),
59            ValueRef::DataLockbox(v) => Value::DataLockbox(v.to_owned()),
60            ValueRef::IdentityLockbox(v) => Value::IdentityLockbox(v.to_owned()),
61            ValueRef::StreamLockbox(v) => Value::StreamLockbox(v.to_owned()),
62            ValueRef::LockLockbox(v) => Value::LockLockbox(v.to_owned()),
63            ValueRef::BareIdKey(ref v) => Value::BareIdKey(v.clone()),
64        }
65    }
66
67    pub fn is_null(&self) -> bool {
68        matches!(self, ValueRef::Null)
69    }
70
71    pub fn is_bool(&self) -> bool {
72        matches!(self, ValueRef::Bool(_))
73    }
74
75    pub fn is_int(&self) -> bool {
76        matches!(self, ValueRef::Int(_))
77    }
78
79    pub fn is_i64(&self) -> bool {
80        if let ValueRef::Int(ref v) = *self {
81            v.is_i64()
82        } else {
83            false
84        }
85    }
86
87    pub fn is_u64(&self) -> bool {
88        if let ValueRef::Int(ref v) = *self {
89            v.is_u64()
90        } else {
91            false
92        }
93    }
94
95    pub fn is_f32(&self) -> bool {
96        matches!(self, ValueRef::F32(_))
97    }
98
99    pub fn is_f64(&self) -> bool {
100        matches!(self, ValueRef::F64(_))
101    }
102
103    pub fn is_str(&self) -> bool {
104        matches!(self, ValueRef::Str(_))
105    }
106
107    pub fn is_bin(&self) -> bool {
108        matches!(self, ValueRef::Bin(_))
109    }
110
111    pub fn is_array(&self) -> bool {
112        matches!(self, ValueRef::Array(_))
113    }
114
115    pub fn is_map(&self) -> bool {
116        matches!(self, ValueRef::Map(_))
117    }
118
119    pub fn is_timestamp(&self) -> bool {
120        matches!(self, ValueRef::Timestamp(_))
121    }
122
123    pub fn is_hash(&self) -> bool {
124        matches!(self, ValueRef::Hash(_))
125    }
126
127    pub fn is_identity(&self) -> bool {
128        matches!(self, ValueRef::Identity(_))
129    }
130
131    pub fn is_stream_id(&self) -> bool {
132        matches!(self, ValueRef::StreamId(_))
133    }
134
135    pub fn is_lock_id(&self) -> bool {
136        matches!(self, ValueRef::LockId(_))
137    }
138
139    pub fn is_lockbox(&self) -> bool {
140        matches!(
141            self,
142            ValueRef::DataLockbox(_)
143                | ValueRef::IdentityLockbox(_)
144                | ValueRef::StreamLockbox(_)
145                | ValueRef::LockLockbox(_)
146        )
147    }
148
149    pub fn is_data_lockbox(&self) -> bool {
150        matches!(self, ValueRef::DataLockbox(_))
151    }
152
153    pub fn is_identity_lockbox(&self) -> bool {
154        matches!(self, ValueRef::IdentityLockbox(_))
155    }
156
157    pub fn is_stream_lockbox(&self) -> bool {
158        matches!(self, ValueRef::StreamLockbox(_))
159    }
160
161    pub fn is_lock_lockbox(&self) -> bool {
162        matches!(self, ValueRef::LockLockbox(_))
163    }
164
165    pub fn is_bare_id_key(&self) -> bool {
166        matches!(self, ValueRef::BareIdKey(_))
167    }
168
169    pub fn as_bool(&self) -> Option<bool> {
170        if let ValueRef::Bool(val) = *self {
171            Some(val)
172        } else {
173            None
174        }
175    }
176
177    pub fn as_int(&self) -> Option<Integer> {
178        if let ValueRef::Int(val) = *self {
179            Some(val)
180        } else {
181            None
182        }
183    }
184
185    pub fn as_i64(&self) -> Option<i64> {
186        match *self {
187            ValueRef::Int(ref n) => n.as_i64(),
188            _ => None,
189        }
190    }
191
192    pub fn as_u64(&self) -> Option<u64> {
193        match *self {
194            ValueRef::Int(ref n) => n.as_u64(),
195            _ => None,
196        }
197    }
198
199    pub fn as_f32(&self) -> Option<f32> {
200        match *self {
201            ValueRef::F32(n) => Some(n),
202            _ => None,
203        }
204    }
205
206    pub fn as_f64(&self) -> Option<f64> {
207        match *self {
208            ValueRef::F64(n) => Some(n),
209            _ => None,
210        }
211    }
212
213    pub fn as_floating(&self) -> Option<f64> {
214        match *self {
215            ValueRef::F32(n) => Some(n.into()),
216            ValueRef::F64(n) => Some(n),
217            _ => None,
218        }
219    }
220
221    pub fn as_str(&self) -> Option<&str> {
222        if let ValueRef::Str(val) = *self {
223            Some(val)
224        } else {
225            None
226        }
227    }
228
229    pub fn as_bin(&self) -> Option<&[u8]> {
230        if let ValueRef::Bin(val) = *self {
231            Some(val)
232        } else {
233            None
234        }
235    }
236
237    pub fn as_array(&self) -> Option<&[ValueRef<'a>]> {
238        if let ValueRef::Array(ref array) = *self {
239            Some(array)
240        } else {
241            None
242        }
243    }
244
245    pub fn as_array_mut(&mut self) -> Option<&mut [ValueRef<'a>]> {
246        match *self {
247            ValueRef::Array(ref mut array) => Some(array),
248            _ => None,
249        }
250    }
251
252    pub fn as_map(&self) -> Option<&BTreeMap<&'a str, ValueRef<'a>>> {
253        match *self {
254            ValueRef::Map(ref map) => Some(map),
255            _ => None,
256        }
257    }
258
259    pub fn as_map_mut(&mut self) -> Option<&mut BTreeMap<&'a str, ValueRef<'a>>> {
260        match *self {
261            ValueRef::Map(ref mut map) => Some(map),
262            _ => None,
263        }
264    }
265
266    pub fn as_timestamp(&self) -> Option<Timestamp> {
267        if let ValueRef::Timestamp(time) = *self {
268            Some(time)
269        } else {
270            None
271        }
272    }
273
274    pub fn as_hash(&self) -> Option<&Hash> {
275        if let ValueRef::Hash(ref hash) = *self {
276            Some(hash)
277        } else {
278            None
279        }
280    }
281
282    pub fn as_identity(&self) -> Option<&Identity> {
283        if let ValueRef::Identity(ref id) = *self {
284            Some(id)
285        } else {
286            None
287        }
288    }
289
290    pub fn as_stream_id(&self) -> Option<&StreamId> {
291        if let ValueRef::StreamId(ref id) = *self {
292            Some(id)
293        } else {
294            None
295        }
296    }
297
298    pub fn as_lock_id(&self) -> Option<&LockId> {
299        if let ValueRef::LockId(ref id) = *self {
300            Some(id)
301        } else {
302            None
303        }
304    }
305
306    pub fn as_data_lockbox(&self) -> Option<&DataLockboxRef> {
307        if let ValueRef::DataLockbox(lockbox) = *self {
308            Some(lockbox)
309        } else {
310            None
311        }
312    }
313
314    pub fn as_identity_lockbox(&self) -> Option<&IdentityLockboxRef> {
315        if let ValueRef::IdentityLockbox(lockbox) = *self {
316            Some(lockbox)
317        } else {
318            None
319        }
320    }
321
322    pub fn as_stream_lockbox(&self) -> Option<&StreamLockboxRef> {
323        if let ValueRef::StreamLockbox(lockbox) = *self {
324            Some(lockbox)
325        } else {
326            None
327        }
328    }
329
330    pub fn as_lock_lockbox(&self) -> Option<&LockLockboxRef> {
331        if let ValueRef::LockLockbox(lockbox) = *self {
332            Some(lockbox)
333        } else {
334            None
335        }
336    }
337
338    pub fn as_bare_id_key(&self) -> Option<&BareIdKey> {
339        if let ValueRef::BareIdKey(ref key) = *self {
340            Some(key)
341        } else {
342            None
343        }
344    }
345}
346
347static NULL_REF: ValueRef<'static> = ValueRef::Null;
348
349/// Support indexing into arrays. If the index is out of range or the value isn't an array, this
350/// returns a [`ValueRef::Null`].
351impl<'a> Index<usize> for ValueRef<'a> {
352    type Output = ValueRef<'a>;
353
354    fn index(&self, index: usize) -> &Self::Output {
355        self.as_array()
356            .and_then(|v| v.get(index))
357            .unwrap_or(&NULL_REF)
358    }
359}
360
361/// Support indexing into maps. If the index string is not in the map, this returns a
362/// [`ValueRef::Null`].
363impl<'a> Index<&str> for ValueRef<'a> {
364    type Output = ValueRef<'a>;
365
366    fn index(&self, index: &str) -> &Self::Output {
367        self.as_map()
368            .and_then(|v| v.get(index))
369            .unwrap_or(&NULL_REF)
370    }
371}
372
373impl<'a> PartialEq<Value> for ValueRef<'a> {
374    fn eq(&self, other: &Value) -> bool {
375        use std::ops::Deref;
376        match self {
377            ValueRef::Null => other == &Value::Null,
378            ValueRef::Bool(s) => {
379                if let Value::Bool(o) = other {
380                    s == o
381                } else {
382                    false
383                }
384            }
385            ValueRef::Int(s) => {
386                if let Value::Int(o) = other {
387                    s == o
388                } else {
389                    false
390                }
391            }
392            ValueRef::Str(s) => {
393                if let Value::Str(o) = other {
394                    s == o
395                } else {
396                    false
397                }
398            }
399            ValueRef::F32(s) => {
400                if let Value::F32(o) = other {
401                    s == o
402                } else {
403                    false
404                }
405            }
406            ValueRef::F64(s) => {
407                if let Value::F64(o) = other {
408                    s == o
409                } else {
410                    false
411                }
412            }
413            ValueRef::Bin(s) => {
414                if let Value::Bin(o) = other {
415                    s == o
416                } else {
417                    false
418                }
419            }
420            ValueRef::Array(s) => {
421                if let Value::Array(o) = other {
422                    s == o
423                } else {
424                    false
425                }
426            }
427            ValueRef::Map(s) => {
428                if let Value::Map(o) = other {
429                    s.len() == o.len()
430                        && s.iter()
431                            .zip(o)
432                            .all(|((ks, vs), (ko, vo))| (ks == ko) && (vs == vo))
433                } else {
434                    false
435                }
436            }
437            ValueRef::Hash(s) => {
438                if let Value::Hash(o) = other {
439                    s == o
440                } else {
441                    false
442                }
443            }
444            ValueRef::Identity(s) => {
445                if let Value::Identity(o) = other {
446                    s == o
447                } else {
448                    false
449                }
450            }
451            ValueRef::StreamId(s) => {
452                if let Value::StreamId(o) = other {
453                    s == o
454                } else {
455                    false
456                }
457            }
458            ValueRef::LockId(s) => {
459                if let Value::LockId(o) = other {
460                    s == o
461                } else {
462                    false
463                }
464            }
465            ValueRef::Timestamp(s) => {
466                if let Value::Timestamp(o) = other {
467                    s == o
468                } else {
469                    false
470                }
471            }
472            ValueRef::DataLockbox(s) => {
473                if let Value::DataLockbox(o) = other {
474                    s == &o.deref()
475                } else {
476                    false
477                }
478            }
479            ValueRef::IdentityLockbox(s) => {
480                if let Value::IdentityLockbox(o) = other {
481                    s == &o.deref()
482                } else {
483                    false
484                }
485            }
486            ValueRef::StreamLockbox(s) => {
487                if let Value::StreamLockbox(o) = other {
488                    s == &o.deref()
489                } else {
490                    false
491                }
492            }
493            ValueRef::LockLockbox(s) => {
494                if let Value::LockLockbox(o) = other {
495                    s == &o.deref()
496                } else {
497                    false
498                }
499            }
500            ValueRef::BareIdKey(s) => {
501                if let Value::BareIdKey(o) = other {
502                    s == o
503                } else {
504                    false
505                }
506            }
507        }
508    }
509}
510
511macro_rules! impl_value_from_integer {
512    ($t: ty) => {
513        impl<'a> From<$t> for ValueRef<'a> {
514            fn from(v: $t) -> Self {
515                ValueRef::Int(From::from(v))
516            }
517        }
518    };
519}
520
521macro_rules! impl_value_from {
522    ($t: ty, $p: ident) => {
523        impl<'a> From<$t> for ValueRef<'a> {
524            fn from(v: $t) -> Self {
525                ValueRef::$p(v)
526            }
527        }
528    };
529}
530
531impl_value_from!(bool, Bool);
532impl_value_from!(Integer, Int);
533impl_value_from!(f32, F32);
534impl_value_from!(f64, F64);
535impl_value_from!(&'a str, Str);
536impl_value_from!(&'a [u8], Bin);
537impl_value_from!(Vec<ValueRef<'a>>, Array);
538impl_value_from!(BTreeMap<&'a str, ValueRef<'a>>, Map);
539impl_value_from!(Timestamp, Timestamp);
540impl_value_from!(Hash, Hash);
541impl_value_from!(Identity, Identity);
542impl_value_from!(StreamId, StreamId);
543impl_value_from!(LockId, LockId);
544impl_value_from!(&'a DataLockboxRef, DataLockbox);
545impl_value_from!(&'a IdentityLockboxRef, IdentityLockbox);
546impl_value_from!(&'a StreamLockboxRef, StreamLockbox);
547impl_value_from!(&'a LockLockboxRef, LockLockbox);
548impl_value_from_integer!(u8);
549impl_value_from_integer!(u16);
550impl_value_from_integer!(u32);
551impl_value_from_integer!(u64);
552impl_value_from_integer!(usize);
553impl_value_from_integer!(i8);
554impl_value_from_integer!(i16);
555impl_value_from_integer!(i32);
556impl_value_from_integer!(i64);
557impl_value_from_integer!(isize);
558
559impl<'a> From<()> for ValueRef<'a> {
560    fn from((): ()) -> Self {
561        ValueRef::Null
562    }
563}
564
565impl<'a> From<BareIdKey> for ValueRef<'a> {
566    fn from(value: BareIdKey) -> Self {
567        ValueRef::BareIdKey(Box::new(value))
568    }
569}
570
571impl<'a, V: Into<ValueRef<'a>>> std::iter::FromIterator<V> for ValueRef<'a> {
572    fn from_iter<T: IntoIterator<Item = V>>(iter: T) -> Self {
573        let v: Vec<ValueRef> = iter.into_iter().map(Into::into).collect();
574        ValueRef::Array(v)
575    }
576}
577
578use std::convert::TryFrom;
579
580macro_rules! impl_try_from_value {
581    ($t: ty, $p: ident) => {
582        impl<'a> TryFrom<ValueRef<'a>> for $t {
583            type Error = ValueRef<'a>;
584            fn try_from(v: ValueRef<'a>) -> Result<Self, Self::Error> {
585                match v {
586                    ValueRef::$p(v) => Ok(v),
587                    _ => Err(v),
588                }
589            }
590        }
591    };
592}
593
594macro_rules! impl_try_from_value_integer {
595    ($t: ty) => {
596        impl<'a> TryFrom<ValueRef<'a>> for $t {
597            type Error = ValueRef<'a>;
598            fn try_from(v: ValueRef<'a>) -> Result<Self, Self::Error> {
599                match v {
600                    ValueRef::Int(i) => TryFrom::try_from(i).map_err(|_| v),
601                    _ => Err(v),
602                }
603            }
604        }
605    };
606}
607
608impl_try_from_value!(bool, Bool);
609impl_try_from_value!(&'a str, Str);
610impl_try_from_value!(f32, F32);
611impl_try_from_value!(f64, F64);
612impl_try_from_value!(&'a [u8], Bin);
613impl_try_from_value!(Vec<ValueRef<'a>>, Array);
614impl_try_from_value!(BTreeMap<&'a str, ValueRef<'a>>, Map);
615impl_try_from_value!(Timestamp, Timestamp);
616impl_try_from_value!(Hash, Hash);
617impl_try_from_value!(Identity, Identity);
618impl_try_from_value!(StreamId, StreamId);
619impl_try_from_value!(LockId, LockId);
620impl_try_from_value!(&'a DataLockboxRef, DataLockbox);
621impl_try_from_value!(&'a IdentityLockboxRef, IdentityLockbox);
622impl_try_from_value!(&'a StreamLockboxRef, StreamLockbox);
623impl_try_from_value!(&'a LockLockboxRef, LockLockbox);
624impl_try_from_value_integer!(u8);
625impl_try_from_value_integer!(u16);
626impl_try_from_value_integer!(u32);
627impl_try_from_value_integer!(u64);
628impl_try_from_value_integer!(usize);
629impl_try_from_value_integer!(i8);
630impl_try_from_value_integer!(i16);
631impl_try_from_value_integer!(i32);
632impl_try_from_value_integer!(i64);
633impl_try_from_value_integer!(isize);
634
635impl<'a> TryFrom<ValueRef<'a>> for BareIdKey {
636    type Error = ValueRef<'a>;
637    fn try_from(v: ValueRef<'a>) -> Result<Self, Self::Error> {
638        match v {
639            ValueRef::BareIdKey(v) => Ok(*v),
640            _ => Err(v),
641        }
642    }
643}
644
645impl<'a> serde::Serialize for ValueRef<'a> {
646    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
647        match self {
648            ValueRef::Null => serializer.serialize_unit(),
649            ValueRef::Bool(v) => serializer.serialize_bool(*v),
650            ValueRef::Int(v) => v.serialize(serializer),
651            ValueRef::Str(v) => serializer.serialize_str(v),
652            ValueRef::F32(v) => serializer.serialize_f32(*v),
653            ValueRef::F64(v) => serializer.serialize_f64(*v),
654            ValueRef::Bin(v) => serializer.serialize_bytes(v),
655            ValueRef::Array(v) => v.serialize(serializer),
656            ValueRef::Map(v) => v.serialize(serializer),
657            ValueRef::Timestamp(v) => v.serialize(serializer),
658            ValueRef::Hash(v) => v.serialize(serializer),
659            ValueRef::Identity(v) => v.serialize(serializer),
660            ValueRef::LockId(v) => v.serialize(serializer),
661            ValueRef::StreamId(v) => v.serialize(serializer),
662            ValueRef::DataLockbox(v) => v.serialize(serializer),
663            ValueRef::IdentityLockbox(v) => v.serialize(serializer),
664            ValueRef::StreamLockbox(v) => v.serialize(serializer),
665            ValueRef::LockLockbox(v) => v.serialize(serializer),
666            ValueRef::BareIdKey(v) => v.serialize(serializer),
667        }
668    }
669}
670
671impl<'de> serde::Deserialize<'de> for ValueRef<'de> {
672    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
673        use serde::de::*;
674        use std::fmt;
675
676        struct ValueVisitor;
677        impl<'de> Visitor<'de> for ValueVisitor {
678            type Value = ValueRef<'de>;
679
680            fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
681                fmt.write_str("any valid fogpack Value")
682            }
683
684            fn visit_bool<E: Error>(self, v: bool) -> Result<Self::Value, E> {
685                Ok(ValueRef::Bool(v))
686            }
687
688            fn visit_i8<E: Error>(self, v: i8) -> Result<Self::Value, E> {
689                Ok(ValueRef::Int(Integer::from(v)))
690            }
691
692            fn visit_i16<E: Error>(self, v: i16) -> Result<Self::Value, E> {
693                Ok(ValueRef::Int(Integer::from(v)))
694            }
695
696            fn visit_i32<E: Error>(self, v: i32) -> Result<Self::Value, E> {
697                Ok(ValueRef::Int(Integer::from(v)))
698            }
699
700            fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> {
701                Ok(ValueRef::Int(Integer::from(v)))
702            }
703
704            fn visit_u8<E: Error>(self, v: u8) -> Result<Self::Value, E> {
705                Ok(ValueRef::Int(Integer::from(v)))
706            }
707
708            fn visit_u16<E: Error>(self, v: u16) -> Result<Self::Value, E> {
709                Ok(ValueRef::Int(Integer::from(v)))
710            }
711
712            fn visit_u32<E: Error>(self, v: u32) -> Result<Self::Value, E> {
713                Ok(ValueRef::Int(Integer::from(v)))
714            }
715
716            fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> {
717                Ok(ValueRef::Int(Integer::from(v)))
718            }
719
720            fn visit_f32<E: Error>(self, v: f32) -> Result<Self::Value, E> {
721                Ok(ValueRef::F32(v))
722            }
723
724            fn visit_f64<E: Error>(self, v: f64) -> Result<Self::Value, E> {
725                Ok(ValueRef::F64(v))
726            }
727
728            fn visit_borrowed_str<E: Error>(self, v: &'de str) -> Result<Self::Value, E> {
729                Ok(ValueRef::Str(v))
730            }
731
732            fn visit_borrowed_bytes<E: Error>(self, v: &'de [u8]) -> Result<Self::Value, E> {
733                Ok(ValueRef::Bin(v))
734            }
735
736            fn visit_unit<E: Error>(self) -> Result<Self::Value, E> {
737                Ok(ValueRef::Null)
738            }
739
740            fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
741                // Allocate with the size hint, but be conservative. 4096 is what serde uses
742                // internally for collections, so we'll do likewise.
743                let mut seq = match access.size_hint() {
744                    Some(size) => Vec::with_capacity(size.min(4096)),
745                    None => Vec::new(),
746                };
747                while let Some(elem) = access.next_element()? {
748                    seq.push(elem);
749                }
750                Ok(ValueRef::Array(seq))
751            }
752
753            fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
754                let mut map = BTreeMap::new();
755                while let Some((key, val)) = access.next_entry()? {
756                    map.insert(key, val);
757                }
758                Ok(ValueRef::Map(map))
759            }
760
761            /// Should only be called when deserializing our special types.
762            /// Fogpack's deserializer will always turn the variant into a u64
763            fn visit_enum<A: EnumAccess<'de>>(self, access: A) -> Result<Self::Value, A::Error> {
764                let (variant, access) = access.variant()?;
765                use fog_crypto::serde::*;
766                use serde_bytes::{ByteBuf, Bytes};
767                match variant {
768                    FOG_TYPE_ENUM_TIME_INDEX => {
769                        let bytes: ByteBuf = access.newtype_variant()?;
770                        let val = Timestamp::try_from(bytes.as_ref()).map_err(A::Error::custom)?;
771                        Ok(ValueRef::Timestamp(val))
772                    }
773                    FOG_TYPE_ENUM_HASH_INDEX => {
774                        let bytes: ByteBuf = access.newtype_variant()?;
775                        let val = Hash::try_from(bytes.as_ref())
776                            .map_err(|e| A::Error::custom(e.serde_err()))?;
777                        Ok(ValueRef::Hash(val))
778                    }
779                    FOG_TYPE_ENUM_IDENTITY_INDEX => {
780                        let bytes: ByteBuf = access.newtype_variant()?;
781                        let val = Identity::try_from(bytes.as_ref())
782                            .map_err(|e| A::Error::custom(e.serde_err()))?;
783                        Ok(ValueRef::Identity(val))
784                    }
785                    FOG_TYPE_ENUM_LOCK_ID_INDEX => {
786                        let bytes: ByteBuf = access.newtype_variant()?;
787                        let val = LockId::try_from(bytes.as_ref())
788                            .map_err(|e| A::Error::custom(e.serde_err()))?;
789                        Ok(ValueRef::LockId(val))
790                    }
791                    FOG_TYPE_ENUM_STREAM_ID_INDEX => {
792                        let bytes: ByteBuf = access.newtype_variant()?;
793                        let val = StreamId::try_from(bytes.as_ref())
794                            .map_err(|e| A::Error::custom(e.serde_err()))?;
795                        Ok(ValueRef::StreamId(val))
796                    }
797                    FOG_TYPE_ENUM_DATA_LOCKBOX_INDEX => {
798                        let bytes: &Bytes = access.newtype_variant()?;
799                        let val = DataLockboxRef::from_bytes(bytes)
800                            .map_err(|e| A::Error::custom(e.serde_err()))?;
801                        Ok(ValueRef::DataLockbox(val))
802                    }
803                    FOG_TYPE_ENUM_IDENTITY_LOCKBOX_INDEX => {
804                        let bytes: &Bytes = access.newtype_variant()?;
805                        let val = IdentityLockboxRef::from_bytes(bytes)
806                            .map_err(|e| A::Error::custom(e.serde_err()))?;
807                        Ok(ValueRef::IdentityLockbox(val))
808                    }
809                    FOG_TYPE_ENUM_STREAM_LOCKBOX_INDEX => {
810                        let bytes: &Bytes = access.newtype_variant()?;
811                        let val = StreamLockboxRef::from_bytes(bytes)
812                            .map_err(|e| A::Error::custom(e.serde_err()))?;
813                        Ok(ValueRef::StreamLockbox(val))
814                    }
815                    FOG_TYPE_ENUM_LOCK_LOCKBOX_INDEX => {
816                        let bytes: &Bytes = access.newtype_variant()?;
817                        let val = LockLockboxRef::from_bytes(bytes)
818                            .map_err(|e| A::Error::custom(e.serde_err()))?;
819                        Ok(ValueRef::LockLockbox(val))
820                    }
821                    FOG_TYPE_ENUM_BARE_ID_KEY_INDEX => {
822                        let bytes: ByteBuf = access.newtype_variant()?;
823                        let val = BareIdKey::try_from(bytes.as_ref())
824                            .map_err(|e| A::Error::custom(e.serde_err()))?;
825                        Ok(ValueRef::BareIdKey(Box::new(val)))
826                    }
827                    _ => Err(A::Error::custom("unrecognized fogpack extension type")),
828                }
829            }
830        }
831
832        deserializer.deserialize_any(ValueVisitor)
833    }
834}
835#[cfg(test)]
836mod test {
837    use fog_crypto::{identity::IdentityKey, lock::LockKey, stream::StreamKey};
838
839    use crate::{document::NewDocument, schema::NoSchema};
840
841    use super::*;
842
843    #[test]
844    fn null() {
845        let obj = ValueRef::from(());
846        assert!(obj.is_null());
847        let doc = NewDocument::new(None, &obj).unwrap();
848        let doc = NoSchema::validate_new_doc(doc).unwrap();
849        let decode: ValueRef = doc.deserialize().unwrap();
850        assert!(decode.is_null());
851    }
852
853    #[test]
854    fn int() {
855        let list: Vec<Integer> = vec![
856            i64::MIN.into(),
857            i32::MIN.into(),
858            i16::MIN.into(),
859            i8::MIN.into(),
860            (-1i8).into(),
861            0u8.into(),
862            1u8.into(),
863            u8::MAX.into(),
864            u16::MAX.into(),
865            u32::MAX.into(),
866            u64::MAX.into(),
867        ];
868        for obj in list {
869            let obj = ValueRef::from(obj);
870            let doc = NewDocument::new(None, &obj).unwrap();
871            let doc = NoSchema::validate_new_doc(doc).unwrap();
872            let decode: ValueRef = doc.deserialize().unwrap();
873            assert_eq!(decode.as_int(), obj.as_int());
874        }
875    }
876
877    #[test]
878    fn bool() {
879        let list = vec![false, true];
880        for obj in list {
881            let obj = ValueRef::from(obj);
882            assert!(obj.is_bool());
883            let doc = NewDocument::new(None, &obj).unwrap();
884            let doc = NoSchema::validate_new_doc(doc).unwrap();
885            let decode: ValueRef = doc.deserialize().unwrap();
886            assert_eq!(decode.as_bool(), obj.as_bool());
887        }
888    }
889
890    #[test]
891    fn str() {
892        let list = vec!["", "\0", "a string", "😄"];
893        for obj in list {
894            let obj = ValueRef::from(obj);
895            assert!(obj.is_str());
896            let doc = NewDocument::new(None, &obj).unwrap();
897            let doc = NoSchema::validate_new_doc(doc).unwrap();
898            let decode: ValueRef = doc.deserialize().unwrap();
899            assert_eq!(decode.as_str(), obj.as_str());
900        }
901    }
902
903    #[test]
904    fn f32() {
905        let list = vec![0.0f32, f32::MIN, f32::MAX];
906        for obj in list {
907            let obj = ValueRef::from(obj);
908            assert!(obj.is_f32());
909            let doc = NewDocument::new(None, &obj).unwrap();
910            let doc = NoSchema::validate_new_doc(doc).unwrap();
911            let decode: ValueRef = doc.deserialize().unwrap();
912            assert_eq!(decode.as_f32(), obj.as_f32());
913        }
914    }
915
916    #[test]
917    fn f64() {
918        let list = vec![0.0f64, f64::MIN, f64::MAX];
919        for obj in list {
920            let obj = ValueRef::from(obj);
921            assert!(obj.is_f64());
922            let doc = NewDocument::new(None, &obj).unwrap();
923            let doc = NoSchema::validate_new_doc(doc).unwrap();
924            let decode: ValueRef = doc.deserialize().unwrap();
925            assert_eq!(decode.as_f64(), obj.as_f64());
926        }
927    }
928
929    #[test]
930    fn bin() {
931        let list = vec![vec![], vec![0u8], vec![0u8, 1u8, 2u8]];
932        for obj in list {
933            let obj = ValueRef::from(obj.as_slice());
934            assert!(obj.is_bin());
935            let doc = NewDocument::new(None, &obj).unwrap();
936            let doc = NoSchema::validate_new_doc(doc).unwrap();
937            let decode: ValueRef = doc.deserialize().unwrap();
938            assert_eq!(decode.as_bin(), obj.as_bin());
939        }
940    }
941
942    #[test]
943    fn array() {
944        let obj = Value::from(vec![
945            Value::from(true),
946            Value::from(1u64),
947            Value::from("hi"),
948            Value::from(vec![0u8, 1u8, 2u8]),
949        ]);
950        let obj: ValueRef = obj.as_ref();
951        assert!(obj.is_array());
952        let doc = NewDocument::new(None, &obj).unwrap();
953        let doc = NoSchema::validate_new_doc(doc).unwrap();
954        let decode: ValueRef = doc.deserialize().unwrap();
955        match (decode.as_array(), obj.as_array()) {
956            (Some(x), Some(y)) => assert!(x == y),
957            _ => panic!("Expected both to be arrays"),
958        }
959    }
960
961    #[test]
962    fn map() {
963        let mut map = BTreeMap::new();
964        map.insert("a", ValueRef::from(true));
965        map.insert("b", ValueRef::from(1u64));
966        map.insert("c", ValueRef::from("hi"));
967        let obj: ValueRef = ValueRef::from(map);
968        assert!(obj.is_map());
969        let doc = NewDocument::new(None, &obj).unwrap();
970        let doc = NoSchema::validate_new_doc(doc).unwrap();
971        let decode: ValueRef = doc.deserialize().unwrap();
972        match (decode.as_map(), obj.as_map()) {
973            (Some(x), Some(y)) => assert!(x == y),
974            _ => panic!("Expected both to be map"),
975        }
976    }
977
978    #[test]
979    fn hash() {
980        let obj = Hash::new(b"Just some test hash");
981        let obj = ValueRef::from(obj);
982        assert!(obj.is_hash());
983        let doc = NewDocument::new(None, &obj).unwrap();
984        let doc = NoSchema::validate_new_doc(doc).unwrap();
985        let decode: ValueRef = doc.deserialize().unwrap();
986        assert_eq!(decode.as_hash(), obj.as_hash());
987    }
988
989    #[test]
990    fn identity() {
991        let key = IdentityKey::new();
992        let obj = key.id().clone();
993        let obj = ValueRef::from(obj);
994        assert!(obj.is_identity());
995        let doc = NewDocument::new(None, &obj).unwrap();
996        let doc = NoSchema::validate_new_doc(doc).unwrap();
997        let decode: ValueRef = doc.deserialize().unwrap();
998        assert_eq!(decode.as_identity(), obj.as_identity());
999    }
1000
1001    #[test]
1002    fn stream_id() {
1003        let key = StreamKey::new();
1004        let obj = key.id().clone();
1005        let obj = ValueRef::from(obj);
1006        assert!(obj.is_stream_id());
1007        let doc = NewDocument::new(None, &obj).unwrap();
1008        let doc = NoSchema::validate_new_doc(doc).unwrap();
1009        let decode: ValueRef = doc.deserialize().unwrap();
1010        assert_eq!(decode.as_stream_id(), obj.as_stream_id());
1011    }
1012
1013    #[test]
1014    fn lock_id() {
1015        let key = LockKey::new();
1016        let obj = key.id().clone();
1017        let obj = ValueRef::from(obj);
1018        assert!(obj.is_lock_id());
1019        let doc = NewDocument::new(None, &obj).unwrap();
1020        let doc = NoSchema::validate_new_doc(doc).unwrap();
1021        let decode: ValueRef = doc.deserialize().unwrap();
1022        assert_eq!(decode.as_lock_id(), obj.as_lock_id());
1023    }
1024
1025    #[test]
1026    fn timestamp() {
1027        let obj = Timestamp::from_utc(1647740000, 0).unwrap();
1028        let obj = ValueRef::from(obj);
1029        assert!(obj.is_timestamp());
1030        let doc = NewDocument::new(None, &obj).unwrap();
1031        let doc = NoSchema::validate_new_doc(doc).unwrap();
1032        let decode: ValueRef = doc.deserialize().unwrap();
1033        assert_eq!(decode.as_timestamp(), obj.as_timestamp());
1034    }
1035
1036    #[test]
1037    fn data_lockbox() {
1038        let key = StreamKey::new();
1039        let obj = key.encrypt_data(b"my secret squirrel data");
1040        let obj = ValueRef::from(DataLockboxRef::from_bytes(obj.as_bytes()).unwrap());
1041        assert!(obj.is_data_lockbox());
1042        let doc = NewDocument::new(None, &obj).unwrap();
1043        let doc = NoSchema::validate_new_doc(doc).unwrap();
1044        let decode: ValueRef = doc.deserialize().unwrap();
1045        assert_eq!(decode.as_data_lockbox(), obj.as_data_lockbox());
1046    }
1047
1048    #[test]
1049    fn identity_lockbox() {
1050        let to_encrypt = IdentityKey::new();
1051        let key = StreamKey::new();
1052        let lockbox = to_encrypt.export_for_stream(&key).unwrap();
1053        let obj = ValueRef::from(IdentityLockboxRef::from_bytes(lockbox.as_bytes()).unwrap());
1054        assert!(obj.is_identity_lockbox());
1055        let doc = NewDocument::new(None, &obj).unwrap();
1056        let doc = NoSchema::validate_new_doc(doc).unwrap();
1057        let decode: ValueRef = doc.deserialize().unwrap();
1058        assert_eq!(decode.as_identity_lockbox(), obj.as_identity_lockbox());
1059    }
1060
1061    #[test]
1062    fn stream_lockbox() {
1063        let to_encrypt = StreamKey::new();
1064        let key = StreamKey::new();
1065        let lockbox = to_encrypt.export_for_stream(&key).unwrap();
1066        let obj = ValueRef::from(StreamLockboxRef::from_bytes(lockbox.as_bytes()).unwrap());
1067        assert!(obj.is_stream_lockbox());
1068        let doc = NewDocument::new(None, &obj).unwrap();
1069        let doc = NoSchema::validate_new_doc(doc).unwrap();
1070        let decode: ValueRef = doc.deserialize().unwrap();
1071        assert_eq!(decode.as_stream_lockbox(), obj.as_stream_lockbox());
1072    }
1073
1074    #[test]
1075    fn lock_lockbox() {
1076        let to_encrypt = LockKey::new();
1077        let key = StreamKey::new();
1078        let lockbox = to_encrypt.export_for_stream(&key).unwrap();
1079        let obj = ValueRef::from(LockLockboxRef::from_bytes(lockbox.as_bytes()).unwrap());
1080        assert!(obj.is_lock_lockbox());
1081        let doc = NewDocument::new(None, &obj).unwrap();
1082        let doc = NoSchema::validate_new_doc(doc).unwrap();
1083        let decode: ValueRef = doc.deserialize().unwrap();
1084        assert_eq!(decode.as_lock_lockbox(), obj.as_lock_lockbox());
1085    }
1086
1087    #[test]
1088    fn bare_id_key() {
1089        let key = BareIdKey::new();
1090        let obj = ValueRef::from(key);
1091        assert!(obj.is_bare_id_key());
1092        let doc = NewDocument::new(None, &obj).unwrap();
1093        let doc = NoSchema::validate_new_doc(doc).unwrap();
1094        let decode: ValueRef = doc.deserialize().unwrap();
1095        assert_eq!(decode.as_bare_id_key(), obj.as_bare_id_key());
1096    }
1097}