msgpackin/
value.rs

1//! MessagePack Rust Value and ValueRef types
2
3use crate::consumer::*;
4use crate::producer::*;
5use crate::*;
6
7#[cfg(feature = "serde")]
8macro_rules! visit {
9    ($id:ident, $ty:ty, $n:ident, $b:block) => {
10        fn $id<E>(self, $n: $ty) -> result::Result<Self::Value, E>
11        where
12            E: serde::de::Error,
13        $b
14    };
15}
16
17/// MessagePack Utf8 String Reference type
18#[derive(Clone, PartialEq)]
19pub struct Utf8Str(pub Box<[u8]>);
20
21#[cfg(feature = "serde")]
22impl serde::Serialize for Utf8Str {
23    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
24    where
25        S: serde::Serializer,
26    {
27        match self.as_str() {
28            Ok(s) => serializer.serialize_str(s),
29            Err(_) => serializer.serialize_bytes(&self.0),
30        }
31    }
32}
33
34#[cfg(feature = "serde")]
35impl<'de> serde::Deserialize<'de> for Utf8Str {
36    fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
37    where
38        D: serde::de::Deserializer<'de>,
39    {
40        struct V;
41        impl<'de> serde::de::Visitor<'de> for V {
42            type Value = Utf8Str;
43
44            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
45                f.write_str("str, or bytes")
46            }
47
48            visit!(visit_str, &str, v, {
49                Ok(Utf8Str(v.to_string().into_bytes().into_boxed_slice()))
50            });
51            visit!(visit_string, String, v, {
52                Ok(Utf8Str(v.into_bytes().into_boxed_slice()))
53            });
54            visit!(visit_bytes, &[u8], v, {
55                Ok(Utf8Str(v.to_vec().into_boxed_slice()))
56            });
57            visit!(visit_byte_buf, Vec<u8>, v, {
58                Ok(Utf8Str(v.into_boxed_slice()))
59            });
60        }
61
62        deserializer.deserialize_string(V)
63    }
64}
65
66impl fmt::Debug for Utf8Str {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        match self.as_str() {
69            Ok(s) => s.fmt(f),
70            Err(_) => write!(f, "EInvalidUtf8({:?})", &self.0),
71        }
72    }
73}
74
75impl fmt::Display for Utf8Str {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        match self.as_str() {
78            Ok(s) => s.fmt(f),
79            Err(_) => write!(f, "EInvalidUtf8({:?})", &self.0),
80        }
81    }
82}
83
84impl<'a> From<&Utf8StrRef<'a>> for Utf8Str {
85    fn from(s: &Utf8StrRef<'a>) -> Self {
86        Self(s.0.to_vec().into_boxed_slice())
87    }
88}
89
90impl From<&str> for Utf8Str {
91    fn from(s: &str) -> Self {
92        Self(s.as_bytes().to_vec().into_boxed_slice())
93    }
94}
95
96impl From<&String> for Utf8Str {
97    fn from(s: &String) -> Self {
98        s.as_str().into()
99    }
100}
101
102impl From<String> for Utf8Str {
103    fn from(s: String) -> Self {
104        Self(s.into_bytes().into_boxed_slice())
105    }
106}
107
108impl<'a> From<Cow<'a, str>> for Utf8Str {
109    fn from(c: Cow<'a, str>) -> Self {
110        c.into_owned().into()
111    }
112}
113
114impl Utf8Str {
115    /// Get a Utf8StrRef from this instance
116    pub fn as_ref(&self) -> Utf8StrRef {
117        self.into()
118    }
119
120    /// Attempt to get this string as a `&str`
121    pub fn as_str(&self) -> Result<&str> {
122        lib::core::str::from_utf8(&self.0).map_err(|_| Error::EInvalidUtf8)
123    }
124
125    /// Attempt to convert this into a rust String
126    pub fn into_string(self) -> Result<String> {
127        String::from_utf8(self.0.into_vec()).map_err(|_| Error::EInvalidUtf8)
128    }
129
130    /// Get the underlying raw bytes of this "string" type
131    pub fn as_bytes(&self) -> &[u8] {
132        &self.0
133    }
134}
135
136/// MessagePack Rust owned Value type
137#[derive(Debug, Clone, PartialEq)]
138pub enum Value {
139    /// MessagePack `Nil` type
140    Nil,
141
142    /// MessagePack `Boolean` type
143    Bool(bool),
144
145    /// MessagePack `Number` type
146    Num(Num),
147
148    /// MessagePack `Bin` type
149    Bin(Box<[u8]>),
150
151    /// MessagePack `Str` type
152    Str(Utf8Str),
153
154    /// MessagePack `Arr` type
155    Arr(Vec<Value>),
156
157    /// MessagePack `Map` type
158    Map(Vec<(Value, Value)>),
159
160    /// MessagePack `Ext` type
161    Ext(i8, Box<[u8]>),
162}
163
164#[cfg(feature = "serde")]
165impl serde::Serialize for Value {
166    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
167    where
168        S: serde::Serializer,
169    {
170        serde::Serialize::serialize(&ValueRef::from(self), serializer)
171    }
172}
173
174#[cfg(feature = "serde")]
175impl<'de> serde::Deserialize<'de> for Value {
176    fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
177    where
178        D: serde::de::Deserializer<'de>,
179    {
180        struct V;
181        impl<'de> serde::de::Visitor<'de> for V {
182            type Value = Value;
183
184            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
185                f.write_str("any")
186            }
187
188            visit!(visit_bool, bool, v, { Ok(Value::Bool(v)) });
189            visit!(visit_i8, i8, v, { Ok(Value::Num(v.into())) });
190            visit!(visit_i16, i16, v, { Ok(Value::Num(v.into())) });
191            visit!(visit_i32, i32, v, { Ok(Value::Num(v.into())) });
192            visit!(visit_i64, i64, v, { Ok(Value::Num(v.into())) });
193            visit!(visit_u8, u8, v, { Ok(Value::Num(v.into())) });
194            visit!(visit_u16, u16, v, { Ok(Value::Num(v.into())) });
195            visit!(visit_u32, u32, v, { Ok(Value::Num(v.into())) });
196            visit!(visit_u64, u64, v, { Ok(Value::Num(v.into())) });
197            visit!(visit_f32, f32, v, { Ok(Value::Num(v.into())) });
198            visit!(visit_f64, f64, v, { Ok(Value::Num(v.into())) });
199            visit!(visit_str, &str, v, {
200                Ok(Value::Str(Utf8Str(
201                    v.to_string().into_bytes().into_boxed_slice(),
202                )))
203            });
204            visit!(visit_string, String, v, {
205                Ok(Value::Str(Utf8Str(v.into_bytes().into_boxed_slice())))
206            });
207            visit!(visit_bytes, &[u8], v, {
208                Ok(Value::Bin(v.to_vec().into_boxed_slice()))
209            });
210            visit!(visit_byte_buf, Vec<u8>, v, {
211                Ok(Value::Bin(v.into_boxed_slice()))
212            });
213
214            fn visit_none<E>(self) -> result::Result<Self::Value, E>
215            where
216                E: serde::de::Error,
217            {
218                Ok(Value::Nil)
219            }
220
221            fn visit_some<D>(
222                self,
223                deserializer: D,
224            ) -> result::Result<Self::Value, D::Error>
225            where
226                D: serde::de::Deserializer<'de>,
227            {
228                deserializer.deserialize_any(V)
229            }
230
231            fn visit_unit<E>(self) -> result::Result<Self::Value, E>
232            where
233                E: serde::de::Error,
234            {
235                Ok(Value::Nil)
236            }
237
238            fn visit_newtype_struct<D>(
239                self,
240                deserializer: D,
241            ) -> result::Result<Self::Value, D::Error>
242            where
243                D: serde::de::Deserializer<'de>,
244            {
245                let dec: Self::Value = deserializer.deserialize_any(V)?;
246                if let Value::Arr(mut arr) = dec {
247                    if arr.len() == 2 {
248                        let t = arr.remove(0);
249                        let data = arr.remove(0);
250                        if let (Value::Num(t), Value::Bin(data)) = (t, data) {
251                            if t.fits::<i8>() {
252                                return Ok(Value::Ext(t.to(), data));
253                            }
254                        }
255                    }
256                }
257                unreachable!()
258            }
259
260            fn visit_seq<A>(
261                self,
262                mut acc: A,
263            ) -> result::Result<Self::Value, A::Error>
264            where
265                A: serde::de::SeqAccess<'de>,
266            {
267                let mut arr = match acc.size_hint() {
268                    Some(l) => Vec::with_capacity(l),
269                    None => Vec::new(),
270                };
271                while let Some(v) = acc.next_element()? {
272                    arr.push(v);
273                }
274                Ok(Value::Arr(arr))
275            }
276
277            fn visit_map<A>(
278                self,
279                mut acc: A,
280            ) -> result::Result<Self::Value, A::Error>
281            where
282                A: serde::de::MapAccess<'de>,
283            {
284                let mut map = match acc.size_hint() {
285                    Some(l) => Vec::with_capacity(l),
286                    None => Vec::new(),
287                };
288                while let Some(pair) = acc.next_entry()? {
289                    map.push(pair);
290                }
291                Ok(Value::Map(map))
292            }
293        }
294
295        deserializer.deserialize_any(V)
296    }
297}
298
299impl PartialEq<ValueRef<'_>> for Value {
300    fn eq(&self, oth: &ValueRef) -> bool {
301        &self.as_ref() == oth
302    }
303}
304
305impl<'a> From<&ValueRef<'a>> for Value {
306    fn from(r: &ValueRef<'a>) -> Self {
307        match r {
308            ValueRef::Nil => Value::Nil,
309            ValueRef::Bool(b) => Value::Bool(*b),
310            ValueRef::Num(n) => Value::Num(*n),
311            ValueRef::Bin(data) => Value::Bin(data.to_vec().into_boxed_slice()),
312            ValueRef::Str(data) => Value::Str(data.into()),
313            ValueRef::Ext(t, data) => {
314                Value::Ext(*t, data.to_vec().into_boxed_slice())
315            }
316            ValueRef::Arr(a) => Value::Arr(a.iter().map(Into::into).collect()),
317            ValueRef::Map(m) => Value::Map(
318                m.iter().map(|(k, v)| (k.into(), v.into())).collect(),
319            ),
320        }
321    }
322}
323
324impl From<()> for Value {
325    fn from(_: ()) -> Self {
326        Value::Nil
327    }
328}
329
330impl From<bool> for Value {
331    fn from(b: bool) -> Self {
332        Value::Bool(b)
333    }
334}
335
336macro_rules! num_2_v {
337    ($($t:ty)*) => {$(
338        impl From<$t> for Value {
339            fn from(n: $t) -> Self {
340                Value::Num(n.into())
341            }
342        }
343    )*};
344}
345
346num_2_v!( i8 i16 i32 i64 isize u8 u16 u32 u64 usize f32 f64 );
347
348impl From<&str> for Value {
349    fn from(s: &str) -> Self {
350        Value::Str(s.into())
351    }
352}
353
354impl From<&String> for Value {
355    fn from(s: &String) -> Self {
356        Value::Str(s.into())
357    }
358}
359
360impl From<String> for Value {
361    fn from(s: String) -> Self {
362        Value::Str(s.into())
363    }
364}
365
366impl<'a> From<Cow<'a, str>> for Value {
367    fn from(c: Cow<'a, str>) -> Self {
368        Value::Str(c.into())
369    }
370}
371
372impl From<&[u8]> for Value {
373    fn from(b: &[u8]) -> Self {
374        Value::Bin(b.to_vec().into_boxed_slice())
375    }
376}
377
378impl From<Box<[u8]>> for Value {
379    fn from(b: Box<[u8]>) -> Self {
380        Value::Bin(b)
381    }
382}
383
384impl From<Vec<u8>> for Value {
385    fn from(b: Vec<u8>) -> Self {
386        Value::Bin(b.into_boxed_slice())
387    }
388}
389
390fn priv_decode<'func, 'prod>(
391    iter: &mut (impl Iterator<Item = OwnedToken> + 'func),
392    config: &Config,
393) -> Result<Value> {
394    let _config = config;
395    match iter.next() {
396        Some(OwnedToken::Nil) => Ok(Value::Nil),
397        Some(OwnedToken::Bool(b)) => Ok(Value::Bool(b)),
398        Some(OwnedToken::Num(n)) => Ok(Value::Num(n)),
399        Some(OwnedToken::Bin(b)) => Ok(Value::Bin(b)),
400        Some(OwnedToken::Str(s)) => Ok(Value::Str(Utf8Str(s))),
401        Some(OwnedToken::Ext(t, d)) => Ok(Value::Ext(t, d)),
402        Some(OwnedToken::Arr(l)) => {
403            let mut arr = Vec::with_capacity(l as usize);
404            for _ in 0..l {
405                arr.push(priv_decode(iter, config)?);
406            }
407            Ok(Value::Arr(arr))
408        }
409        Some(OwnedToken::Map(l)) => {
410            let mut map = Vec::with_capacity(l as usize);
411            for _ in 0..l {
412                let key = priv_decode(iter, config)?;
413                let val = priv_decode(iter, config)?;
414                map.push((key, val));
415            }
416            Ok(Value::Map(map))
417        }
418        None => Err(Error::EDecode {
419            expected: "Marker".into(),
420            got: "UnexpectedEOF".into(),
421        }),
422    }
423}
424
425impl Value {
426    /// Get a ValueRef from this instance
427    pub fn as_ref(&self) -> ValueRef {
428        self.into()
429    }
430
431    /// Encode this value as a `Vec<u8>`
432    pub fn to_bytes(&self) -> Result<Vec<u8>> {
433        let mut out = Vec::new();
434        self.to_sync(&mut out)?;
435        Ok(out)
436    }
437
438    /// Encode this value as message pack data to the given consumer.
439    /// E.g. `&mut Vec<u8>`
440    pub fn to_sync<'con, C>(&self, c: C) -> Result<()>
441    where
442        C: Into<DynConsumerSync<'con>>,
443    {
444        self.to_sync_config(c, &Config::default())
445    }
446
447    /// Encode this value as message pack data to the given consumer.
448    /// E.g. `&mut Vec<u8>`
449    pub fn to_sync_config<'con, C>(&self, c: C, config: &Config) -> Result<()>
450    where
451        C: Into<DynConsumerSync<'con>>,
452    {
453        ValueRef::from(self).to_sync_config(c, config)
454    }
455
456    /// Encode this value as message pack data to the given consumer.
457    /// E.g. `&mut Vec<u8>`
458    pub async fn to_async<'con, C>(&self, c: C) -> Result<()>
459    where
460        C: Into<DynConsumerAsync<'con>>,
461    {
462        self.to_async_config(c, &Config::default()).await
463    }
464
465    /// Encode this value as message pack data to the given consumer.
466    /// E.g. `&mut Vec<u8>`
467    pub async fn to_async_config<'con, C>(
468        &self,
469        c: C,
470        config: &Config,
471    ) -> Result<()>
472    where
473        C: Into<DynConsumerAsync<'con>>,
474    {
475        ValueRef::from(self).to_async_config(c, config).await
476    }
477
478    /// Decode a Value from something that can be converted
479    /// into a DynProducerSync, such as a byte array slice (`&[u8]`)
480    pub fn from_sync<'prod, P>(p: P) -> Result<Self>
481    where
482        P: Into<DynProducerSync<'prod>>,
483    {
484        Self::from_sync_config(p, &Config::default())
485    }
486
487    /// Decode a Value from something that can be converted
488    /// into a DynProducerSync, such as a byte array slice (`&[u8]`)
489    pub fn from_sync_config<'prod, P>(p: P, config: &Config) -> Result<Self>
490    where
491        P: Into<DynProducerSync<'prod>>,
492    {
493        let mut tokens = Vec::new();
494        let mut dec = msgpackin_core::decode::Decoder::new();
495        let mut p = p.into();
496        priv_decode_owned_sync(&mut tokens, &mut dec, &mut p, config)?;
497        let mut iter = tokens.into_iter();
498        priv_decode(&mut iter, config)
499    }
500
501    /// Decode a Value from something that can be converted
502    /// into a DynProducerAsync, such as a byte array slice (`&[u8]`)
503    pub async fn from_async<'prod, P>(p: P) -> Result<Self>
504    where
505        P: Into<DynProducerAsync<'prod>>,
506    {
507        Self::from_async_config(p, &Config::default()).await
508    }
509
510    /// Decode a Value from something that can be converted
511    /// into a DynProducerAsync, such as a byte array slice (`&[u8]`)
512    pub async fn from_async_config<'prod, P>(
513        p: P,
514        config: &Config,
515    ) -> Result<Self>
516    where
517        P: Into<DynProducerAsync<'prod>>,
518    {
519        let mut tokens = Vec::new();
520        let mut dec = msgpackin_core::decode::Decoder::new();
521        let mut p = p.into();
522        priv_decode_owned_async(&mut tokens, &mut dec, &mut p, config).await?;
523        let mut iter = tokens.into_iter();
524        priv_decode(&mut iter, config)
525    }
526}
527
528/// MessagePack Utf8 String Reference type
529#[derive(Clone, PartialEq)]
530pub struct Utf8StrRef<'lt>(pub &'lt [u8]);
531
532#[cfg(feature = "serde")]
533impl<'lt> serde::Serialize for Utf8StrRef<'lt> {
534    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
535    where
536        S: serde::Serializer,
537    {
538        match self.as_str() {
539            Ok(s) => serializer.serialize_str(s),
540            Err(_) => serializer.serialize_bytes(self.0),
541        }
542    }
543}
544
545#[cfg(feature = "serde")]
546impl<'de> serde::Deserialize<'de> for Utf8StrRef<'de> {
547    fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
548    where
549        D: serde::de::Deserializer<'de>,
550    {
551        struct V;
552        impl<'de> serde::de::Visitor<'de> for V {
553            type Value = Utf8StrRef<'de>;
554
555            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
556                f.write_str("str, or bytes")
557            }
558
559            visit!(visit_borrowed_str, &'de str, v, {
560                Ok(Utf8StrRef(v.as_bytes()))
561            });
562            visit!(visit_borrowed_bytes, &'de [u8], v, { Ok(Utf8StrRef(v)) });
563        }
564
565        deserializer.deserialize_str(V)
566    }
567}
568
569impl<'a> From<&'a Utf8Str> for Utf8StrRef<'a> {
570    fn from(s: &'a Utf8Str) -> Self {
571        Utf8StrRef(&s.0)
572    }
573}
574
575impl<'a> From<&'a str> for Utf8StrRef<'a> {
576    fn from(s: &'a str) -> Self {
577        Utf8StrRef(s.as_bytes())
578    }
579}
580
581impl<'a> From<&'a [u8]> for Utf8StrRef<'a> {
582    fn from(s: &'a [u8]) -> Self {
583        Utf8StrRef(s)
584    }
585}
586
587impl fmt::Debug for Utf8StrRef<'_> {
588    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
589        match self.as_str() {
590            Ok(s) => s.fmt(f),
591            Err(_) => write!(f, "EInvalidUtf8({:?})", &self.0),
592        }
593    }
594}
595
596impl fmt::Display for Utf8StrRef<'_> {
597    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598        match self.as_str() {
599            Ok(s) => s.fmt(f),
600            Err(_) => write!(f, "EInvalidUtf8({:?})", &self.0),
601        }
602    }
603}
604
605impl<'lt> Utf8StrRef<'lt> {
606    /// Attempt to get this string as a `&str`
607    pub fn as_str(&self) -> Result<&'lt str> {
608        lib::core::str::from_utf8(self.0).map_err(|_| Error::EInvalidUtf8)
609    }
610
611    /// Get the underlying raw bytes of this "string" type
612    pub fn as_bytes(&self) -> &'lt [u8] {
613        self.0
614    }
615}
616
617/// MessagePack Rust Value Reference type
618#[derive(Debug, Clone, PartialEq)]
619pub enum ValueRef<'lt> {
620    /// MessagePack `Nil` type
621    Nil,
622
623    /// MessagePack `Boolean` type
624    Bool(bool),
625
626    /// MessagePack `Number` type
627    Num(Num),
628
629    /// MessagePack `Bin` type
630    Bin(&'lt [u8]),
631
632    /// MessagePack `Str` type
633    Str(Utf8StrRef<'lt>),
634
635    /// MessagePack `Arr` type
636    Arr(Vec<ValueRef<'lt>>),
637
638    /// MessagePack `Map` type
639    Map(Vec<(ValueRef<'lt>, ValueRef<'lt>)>),
640
641    /// MessagePack `Ext` type
642    Ext(i8, &'lt [u8]),
643}
644
645#[cfg(feature = "serde")]
646impl<'lt> serde::Serialize for ValueRef<'lt> {
647    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
648    where
649        S: serde::Serializer,
650    {
651        match self {
652            ValueRef::Nil => serializer.serialize_unit(),
653            ValueRef::Bool(b) => serializer.serialize_bool(*b),
654            ValueRef::Num(Num::Unsigned(u)) => serializer.serialize_u64(*u),
655            ValueRef::Num(Num::Signed(i)) => serializer.serialize_i64(*i),
656            ValueRef::Num(Num::F32(f)) => serializer.serialize_f32(*f),
657            ValueRef::Num(Num::F64(f)) => serializer.serialize_f64(*f),
658            ValueRef::Bin(data) => serializer.serialize_bytes(data),
659            ValueRef::Str(s) => serde::Serialize::serialize(s, serializer),
660            ValueRef::Arr(arr) => {
661                use serde::ser::SerializeSeq;
662                let mut seq = serializer.serialize_seq(Some(arr.len()))?;
663                for item in arr.iter() {
664                    seq.serialize_element(item)?;
665                }
666                seq.end()
667            }
668            ValueRef::Map(map) => {
669                use serde::ser::SerializeMap;
670                let mut ser = serializer.serialize_map(Some(map.len()))?;
671                for (k, v) in map.iter() {
672                    ser.serialize_entry(k, v)?;
673                }
674                ser.end()
675            }
676            ValueRef::Ext(t, data) => serializer.serialize_newtype_struct(
677                EXT_STRUCT_NAME,
678                &(t, ValueRef::Bin(data)),
679            ),
680        }
681    }
682}
683
684#[cfg(feature = "serde")]
685impl<'de> serde::Deserialize<'de> for ValueRef<'de> {
686    fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error>
687    where
688        D: serde::de::Deserializer<'de>,
689    {
690        struct V;
691        impl<'de> serde::de::Visitor<'de> for V {
692            type Value = ValueRef<'de>;
693
694            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
695                f.write_str("any")
696            }
697
698            visit!(visit_bool, bool, v, { Ok(ValueRef::Bool(v)) });
699            visit!(visit_i8, i8, v, { Ok(ValueRef::Num(v.into())) });
700            visit!(visit_i16, i16, v, { Ok(ValueRef::Num(v.into())) });
701            visit!(visit_i32, i32, v, { Ok(ValueRef::Num(v.into())) });
702            visit!(visit_i64, i64, v, { Ok(ValueRef::Num(v.into())) });
703            visit!(visit_u8, u8, v, { Ok(ValueRef::Num(v.into())) });
704            visit!(visit_u16, u16, v, { Ok(ValueRef::Num(v.into())) });
705            visit!(visit_u32, u32, v, { Ok(ValueRef::Num(v.into())) });
706            visit!(visit_u64, u64, v, { Ok(ValueRef::Num(v.into())) });
707            visit!(visit_f32, f32, v, { Ok(ValueRef::Num(v.into())) });
708            visit!(visit_f64, f64, v, { Ok(ValueRef::Num(v.into())) });
709            visit!(visit_borrowed_str, &'de str, v, {
710                Ok(ValueRef::Str(Utf8StrRef(v.as_bytes())))
711            });
712            visit!(visit_borrowed_bytes, &'de [u8], v, {
713                Ok(ValueRef::Bin(v))
714            });
715
716            fn visit_none<E>(self) -> result::Result<Self::Value, E>
717            where
718                E: serde::de::Error,
719            {
720                Ok(ValueRef::Nil)
721            }
722
723            fn visit_some<D>(
724                self,
725                deserializer: D,
726            ) -> result::Result<Self::Value, D::Error>
727            where
728                D: serde::de::Deserializer<'de>,
729            {
730                deserializer.deserialize_any(V)
731            }
732
733            fn visit_unit<E>(self) -> result::Result<Self::Value, E>
734            where
735                E: serde::de::Error,
736            {
737                Ok(ValueRef::Nil)
738            }
739
740            fn visit_newtype_struct<D>(
741                self,
742                deserializer: D,
743            ) -> result::Result<Self::Value, D::Error>
744            where
745                D: serde::de::Deserializer<'de>,
746            {
747                let dec: Self::Value = deserializer.deserialize_any(V)?;
748                if let ValueRef::Arr(mut arr) = dec {
749                    if arr.len() == 2 {
750                        let t = arr.remove(0);
751                        let data = arr.remove(0);
752                        if let (ValueRef::Num(t), ValueRef::Bin(data)) =
753                            (t, data)
754                        {
755                            if t.fits::<i8>() {
756                                return Ok(ValueRef::Ext(t.to(), data));
757                            }
758                        }
759                    }
760                }
761                unreachable!()
762            }
763
764            fn visit_seq<A>(
765                self,
766                mut acc: A,
767            ) -> result::Result<Self::Value, A::Error>
768            where
769                A: serde::de::SeqAccess<'de>,
770            {
771                let mut arr = match acc.size_hint() {
772                    Some(l) => Vec::with_capacity(l),
773                    None => Vec::new(),
774                };
775                while let Some(v) = acc.next_element()? {
776                    arr.push(v);
777                }
778                Ok(ValueRef::Arr(arr))
779            }
780
781            fn visit_map<A>(
782                self,
783                mut acc: A,
784            ) -> result::Result<Self::Value, A::Error>
785            where
786                A: serde::de::MapAccess<'de>,
787            {
788                let mut map = match acc.size_hint() {
789                    Some(l) => Vec::with_capacity(l),
790                    None => Vec::new(),
791                };
792                while let Some(pair) = acc.next_entry()? {
793                    map.push(pair);
794                }
795                Ok(ValueRef::Map(map))
796            }
797        }
798
799        deserializer.deserialize_any(V)
800    }
801}
802
803impl PartialEq<Value> for ValueRef<'_> {
804    fn eq(&self, oth: &Value) -> bool {
805        self == &oth.as_ref()
806    }
807}
808
809impl<'a> From<&'a Value> for ValueRef<'a> {
810    fn from(v: &'a Value) -> Self {
811        match v {
812            Value::Nil => ValueRef::Nil,
813            Value::Bool(b) => ValueRef::Bool(*b),
814            Value::Num(n) => ValueRef::Num(*n),
815            Value::Bin(data) => ValueRef::Bin(data),
816            Value::Str(data) => ValueRef::Str(data.into()),
817            Value::Ext(t, data) => ValueRef::Ext(*t, data),
818            Value::Arr(a) => ValueRef::Arr(a.iter().map(Into::into).collect()),
819            Value::Map(m) => ValueRef::Map(
820                m.iter().map(|(k, v)| (k.into(), v.into())).collect(),
821            ),
822        }
823    }
824}
825
826macro_rules! stub_wrap {
827    ($($t:tt)*) => { $($t)* };
828}
829
830macro_rules! async_wrap {
831    ($($t:tt)*) => { Box::pin(async move { $($t)* }) };
832}
833
834macro_rules! mk_encode {
835    (
836        $id:ident,
837        ($($con:tt)*),
838        ($($await:tt)*),
839        ($($ret:tt)*),
840        $wrap:ident,
841    ) => {
842        fn $id<'func, 'con>(
843            val: &'func ValueRef,
844            enc: &'func mut msgpackin_core::encode::Encoder,
845            con: &'func mut $($con)*,
846            config: &'func Config,
847        ) -> $($ret)* {$wrap! {
848            match val {
849                ValueRef::Nil => con.write(&enc.enc_nil())$($await)*,
850                ValueRef::Bool(b) => con.write(&enc.enc_bool(*b))$($await)*,
851                ValueRef::Num(n) => con.write(&enc.enc_num(*n))$($await)*,
852                ValueRef::Bin(data) => {
853                    con.write(&enc.enc_bin_len(data.len() as u32))$($await)*?;
854                    con.write(data)$($await)*
855                }
856                ValueRef::Str(data) => {
857                    con.write(&enc.enc_str_len(data.0.len() as u32))$($await)*?;
858                    con.write(&data.0)$($await)*
859                }
860                ValueRef::Ext(t, data) => {
861                    con.write(
862                        &enc.enc_ext_len(data.len() as u32, *t),
863                    )$($await)*?;
864                    con.write(data)$($await)*
865                }
866                ValueRef::Arr(a) => {
867                    con.write(&enc.enc_arr_len(a.len() as u32))$($await)*?;
868                    for item in a.iter() {
869                        $id(item, enc, con, config)$($await)*?;
870                    }
871                    Ok(())
872                }
873                ValueRef::Map(m) => {
874                    con.write(&enc.enc_map_len(m.len() as u32))$($await)*?;
875                    for (key, value) in m.iter() {
876                        $id(key, enc, con, config)$($await)*?;
877                        $id(value, enc, con, config)$($await)*?;
878                    }
879                    Ok(())
880                }
881            }
882        }}
883    };
884}
885
886mk_encode!(
887    priv_encode_sync,
888    (DynConsumerSync<'con>),
889    (),
890    (Result<()>),
891    stub_wrap,
892);
893
894mk_encode!(
895    priv_encode_async,
896    (DynConsumerAsync<'con>),
897    (.await),
898    (BoxFut<'func, ()>),
899    async_wrap,
900);
901
902struct VRDecode<'dec, 'buf> {
903    iter: msgpackin_core::decode::TokenIter<'dec, 'buf>,
904}
905
906impl<'dec, 'buf> VRDecode<'dec, 'buf> {
907    fn next_val(&mut self) -> Result<ValueRef<'buf>> {
908        use msgpackin_core::decode::LenType;
909        use msgpackin_core::decode::Token::*;
910        match self.iter.next() {
911            Some(Nil) => Ok(ValueRef::Nil),
912            Some(Bool(b)) => Ok(ValueRef::Bool(b)),
913            Some(Num(n)) => Ok(ValueRef::Num(n)),
914            tok @ Some(Len(LenType::Bin, l)) => {
915                if let Some(Bin(data)) = self.iter.next() {
916                    if data.len() == l as usize {
917                        return Ok(ValueRef::Bin(data));
918                    }
919                }
920                Err(Error::EDecode {
921                    expected: format!("Some(Bin({:?} bytes))", l),
922                    got: format!("{:?}", tok),
923                })
924            }
925            tok @ Some(Len(LenType::Str, l)) => {
926                if let Some(Bin(data)) = self.iter.next() {
927                    if data.len() == l as usize {
928                        return Ok(ValueRef::Str(Utf8StrRef(data)));
929                    }
930                }
931                Err(Error::EDecode {
932                    expected: format!("Some(Bin({:?} bytes))", l),
933                    got: format!("{:?}", tok),
934                })
935            }
936            tok @ Some(Len(LenType::Ext(ext_type), l)) => {
937                if let Some(Bin(data)) = self.iter.next() {
938                    if data.len() == l as usize {
939                        return Ok(ValueRef::Ext(ext_type, data));
940                    }
941                }
942                Err(Error::EDecode {
943                    expected: format!("Some(Bin({:?} bytes))", l),
944                    got: format!("{:?}", tok),
945                })
946            }
947            Some(Len(LenType::Arr, l)) => {
948                let mut out = Vec::with_capacity(l as usize);
949                for _ in 0..l {
950                    out.push(self.next_val()?);
951                }
952                Ok(ValueRef::Arr(out))
953            }
954            Some(Len(LenType::Map, l)) => {
955                let mut out = Vec::with_capacity(l as usize);
956                for _ in 0..l {
957                    let key = self.next_val()?;
958                    let val = self.next_val()?;
959                    out.push((key, val));
960                }
961                Ok(ValueRef::Map(out))
962            }
963            None => Err(Error::EDecode {
964                expected: "Marker".into(),
965                got: "UnexpectedEOF".into(),
966            }),
967            tok => Err(Error::EDecode {
968                expected: "Marker".into(),
969                got: format!("{:?}", tok),
970            }),
971        }
972    }
973}
974
975impl<'lt> ValueRef<'lt> {
976    /// Convert this ValueRef into an owned Value
977    pub fn to_owned(&self) -> Value {
978        self.into()
979    }
980
981    /// Encode this value ref as a `Vec<u8>`
982    pub fn to_bytes(&self) -> Result<Vec<u8>> {
983        let mut out = Vec::new();
984        self.to_sync(&mut out)?;
985        Ok(out)
986    }
987
988    /// Encode this value ref as message pack data to the given consumer.
989    /// E.g. `&mut Vec<u8>`
990    pub fn to_sync<'con, C>(&self, c: C) -> Result<()>
991    where
992        C: Into<DynConsumerSync<'con>>,
993    {
994        self.to_sync_config(c, &Config::default())
995    }
996
997    /// Encode this value ref as message pack data to the given consumer.
998    /// E.g. `&mut Vec<u8>`
999    pub fn to_sync_config<'con, C>(&self, c: C, config: &Config) -> Result<()>
1000    where
1001        C: Into<DynConsumerSync<'con>>,
1002    {
1003        let mut enc = msgpackin_core::encode::Encoder::new();
1004        let mut c = c.into();
1005        priv_encode_sync(self, &mut enc, &mut c, config)
1006    }
1007
1008    /// Encode this value ref as message pack data to the given consumer.
1009    /// E.g. `&mut Vec<u8>`
1010    pub async fn to_async<'con, C>(&self, c: C) -> Result<()>
1011    where
1012        C: Into<DynConsumerAsync<'con>>,
1013    {
1014        self.to_async_config(c, &Config::default()).await
1015    }
1016
1017    /// Encode this value ref as message pack data to the given consumer.
1018    /// E.g. `&mut Vec<u8>`
1019    pub async fn to_async_config<'con, C>(
1020        &self,
1021        c: C,
1022        config: &Config,
1023    ) -> Result<()>
1024    where
1025        C: Into<DynConsumerAsync<'con>>,
1026    {
1027        let mut enc = msgpackin_core::encode::Encoder::new();
1028        let mut c = c.into();
1029        priv_encode_async(self, &mut enc, &mut c, config).await
1030    }
1031
1032    /// Decode a ValueRef from something that can be converted
1033    /// into a DynProducerComplete, such as a byte array slice (`&[u8]`)
1034    pub fn from_ref<P>(p: P) -> Result<Self>
1035    where
1036        P: Into<DynProducerComplete<'lt>>,
1037    {
1038        Self::from_ref_config(p, &Config::default())
1039    }
1040
1041    /// Decode a ValueRef from something that can be converted
1042    /// into a DynProducerComplete, such as a byte array slice (`&[u8]`)
1043    pub fn from_ref_config<P>(p: P, config: &Config) -> Result<Self>
1044    where
1045        P: Into<DynProducerComplete<'lt>>,
1046    {
1047        let _config = config;
1048        let mut dec = msgpackin_core::decode::Decoder::new();
1049        let mut dec = VRDecode {
1050            iter: dec.parse(p.into().read_all()?),
1051        };
1052
1053        dec.next_val()
1054    }
1055}
1056
1057#[cfg(test)]
1058mod tests {
1059    use super::*;
1060
1061    #[cfg(feature = "serde")]
1062    #[test]
1063    fn test_value_serde() {
1064        let arr = Value::Arr(vec![
1065            Value::from(true),
1066            Value::Ext(-42, b"hello".to_vec().into()),
1067            Value::from(false),
1068        ]);
1069        let _res = crate::to_bytes(&arr).unwrap();
1070    }
1071
1072    #[test]
1073    fn test_value_encode_decode() {
1074        let arr = Value::Arr(vec![
1075            Value::from(()),
1076            Value::from(true),
1077            Value::from(false),
1078            Value::from("hello"),
1079            Value::from(&b"hello"[..]),
1080            Value::from(-42_i8),
1081            Value::from(3.14159_f64),
1082        ]);
1083        let map = Value::Map(vec![
1084            (Value::from("array"), arr),
1085            (Value::from("nother"), Value::from("testing")),
1086        ]);
1087        let mut data = Vec::new();
1088        map.to_sync(&mut data).unwrap();
1089        let mut data2 = Vec::new();
1090        futures::executor::block_on(async {
1091            map.to_async(&mut data2).await.unwrap();
1092        });
1093        assert_eq!(data, data2);
1094
1095        let dec1 = ValueRef::from_ref(data.as_slice()).unwrap();
1096        assert_eq!(dec1, map);
1097
1098        let dec2 = Value::from_sync(data.as_slice()).unwrap();
1099        assert_eq!(dec1, dec2);
1100
1101        let dec3 = futures::executor::block_on(async {
1102            Value::from_async(data.as_slice()).await
1103        })
1104        .unwrap();
1105        assert_eq!(dec2, dec3);
1106    }
1107}