[go: up one dir, main page]

rmpv/
lib.rs

1//! Contains Value and `ValueRef` structs and its conversion traits.
2#![forbid(unsafe_code)]
3
4use std::borrow::Cow;
5use std::convert::TryFrom;
6use std::fmt::{self, Debug, Display};
7use std::iter::FromIterator;
8use std::ops::Index;
9use std::str::Utf8Error;
10
11use num_traits::NumCast;
12
13pub mod decode;
14pub mod encode;
15
16#[cfg(feature = "with-serde")]
17pub mod ext;
18
19#[derive(Copy, Clone, Debug, PartialEq)]
20enum IntPriv {
21    /// Always non-less than zero.
22    PosInt(u64),
23    /// Always less than zero.
24    NegInt(i64),
25}
26
27/// Name of Serde newtype struct to Represent Msgpack's Ext
28/// Msgpack Ext: Ext(tag, binary)
29/// Serde data model: _ExtStruct((tag, binary))
30/// Example Serde impl for custom type:
31///
32/// ```ignore
33/// #[derive(Debug, PartialEq, Serialize, Deserialize)]
34/// #[serde(rename = "_ExtStruct")]
35/// struct ExtStruct((i8, serde_bytes::ByteBuf));
36///
37/// test_round(ExtStruct((2, serde_bytes::ByteBuf::from(vec![5]))),
38///            Value::Ext(2, vec![5]));
39/// ```
40pub const MSGPACK_EXT_STRUCT_NAME: &str = "_ExtStruct";
41
42/// Represents a MessagePack integer, whether signed or unsigned.
43///
44/// A `Value` or `ValueRef` that contains integer can be constructed using `From` trait.
45#[derive(Copy, Clone, PartialEq)]
46pub struct Integer {
47    n: IntPriv,
48}
49
50impl Integer {
51    /// Returns `true` if the integer can be represented as `i64`.
52    #[inline]
53    #[must_use]
54    pub fn is_i64(&self) -> bool {
55        match self.n {
56            IntPriv::PosInt(n) => n <= std::i64::MAX as u64,
57            IntPriv::NegInt(..) => true,
58        }
59    }
60
61    /// Returns `true` if the integer can be represented as `u64`.
62    #[inline]
63    #[must_use]
64    pub fn is_u64(&self) -> bool {
65        match self.n {
66            IntPriv::PosInt(..) => true,
67            IntPriv::NegInt(..) => false,
68        }
69    }
70
71    /// Returns the integer represented as `i64` if possible, or else `None`.
72    #[inline]
73    #[must_use]
74    pub fn as_i64(&self) -> Option<i64> {
75        match self.n {
76            IntPriv::PosInt(n) => NumCast::from(n),
77            IntPriv::NegInt(n) => Some(n),
78        }
79    }
80
81    /// Returns the integer represented as `u64` if possible, or else `None`.
82    #[inline]
83    #[must_use]
84    pub fn as_u64(&self) -> Option<u64> {
85        match self.n {
86            IntPriv::PosInt(n) => Some(n),
87            IntPriv::NegInt(n) => NumCast::from(n),
88        }
89    }
90
91    /// Returns the integer represented as `f64` if possible, or else `None`.
92    #[inline]
93    #[must_use]
94    pub fn as_f64(&self) -> Option<f64> {
95        match self.n {
96            IntPriv::PosInt(n) => NumCast::from(n),
97            IntPriv::NegInt(n) => NumCast::from(n),
98        }
99    }
100}
101
102impl Debug for Integer {
103    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
104        Debug::fmt(&self.n, fmt)
105    }
106}
107
108impl Display for Integer {
109    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
110        match self.n {
111            IntPriv::PosInt(v) => Display::fmt(&v, fmt),
112            IntPriv::NegInt(v) => Display::fmt(&v, fmt),
113        }
114    }
115}
116
117impl From<u8> for Integer {
118    #[inline]
119    fn from(n: u8) -> Self {
120        Integer { n: IntPriv::PosInt(n as u64) }
121    }
122}
123
124impl From<u16> for Integer {
125    #[inline]
126    fn from(n: u16) -> Self {
127        Integer { n: IntPriv::PosInt(n as u64) }
128    }
129}
130
131impl From<u32> for Integer {
132    #[inline]
133    fn from(n: u32) -> Self {
134        Integer { n: IntPriv::PosInt(n as u64) }
135    }
136}
137
138impl From<u64> for Integer {
139    #[inline]
140    fn from(n: u64) -> Self {
141        Integer { n: IntPriv::PosInt(n) }
142    }
143}
144
145impl From<usize> for Integer {
146    #[inline]
147    fn from(n: usize) -> Self {
148        Integer { n: IntPriv::PosInt(n as u64) }
149    }
150}
151
152impl From<i8> for Integer {
153    #[inline]
154    fn from(n: i8) -> Self {
155        if n < 0 {
156            Integer { n: IntPriv::NegInt(n as i64) }
157        } else {
158            Integer { n: IntPriv::PosInt(n as u64) }
159        }
160    }
161}
162
163impl From<i16> for Integer {
164    #[inline]
165    fn from(n: i16) -> Self {
166        if n < 0 {
167            Integer { n: IntPriv::NegInt(n as i64) }
168        } else {
169            Integer { n: IntPriv::PosInt(n as u64) }
170        }
171    }
172}
173
174impl From<i32> for Integer {
175    #[inline]
176    fn from(n: i32) -> Self {
177        if n < 0 {
178            Integer { n: IntPriv::NegInt(n as i64) }
179        } else {
180            Integer { n: IntPriv::PosInt(n as u64) }
181        }
182    }
183}
184
185impl From<i64> for Integer {
186    #[inline]
187    fn from(n: i64) -> Self {
188        if n < 0 {
189            Integer { n: IntPriv::NegInt(n) }
190        } else {
191            Integer { n: IntPriv::PosInt(n as u64) }
192        }
193    }
194}
195
196impl From<isize> for Integer {
197    #[inline]
198    fn from(n: isize) -> Self {
199        if n < 0 {
200            Integer { n: IntPriv::NegInt(n as i64) }
201        } else {
202            Integer { n: IntPriv::PosInt(n as u64) }
203        }
204    }
205}
206
207/// Represents an UTF-8 MessagePack string type.
208///
209/// According to the MessagePack spec, string objects may contain invalid byte sequence and the
210/// behavior of a deserializer depends on the actual implementation when it received invalid byte
211/// sequence.
212/// Deserializers should provide functionality to get the original byte array so that applications
213/// can decide how to handle the object.
214///
215/// Summarizing, it's prohibited to instantiate a string type with invalid UTF-8 sequences, however
216/// it is possible to obtain an underlying bytes that were attempted to convert to a `String`. This
217/// may happen when trying to unpack strings that were decoded using older MessagePack spec with
218/// raw types instead of string/binary.
219#[derive(Clone, Debug, PartialEq)]
220pub struct Utf8String {
221    s: Result<String, (Vec<u8>, Utf8Error)>,
222}
223
224impl Utf8String {
225    /// Returns `true` if the string is valid UTF-8.
226    #[inline]
227    #[must_use]
228    pub fn is_str(&self) -> bool {
229        self.s.is_ok()
230    }
231
232    /// Returns `true` if the string contains invalid UTF-8 sequence.
233    #[inline]
234    #[must_use]
235    pub fn is_err(&self) -> bool {
236        self.s.is_err()
237    }
238
239    /// Returns the string reference if the string is valid UTF-8, or else `None`.
240    #[inline]
241    #[must_use]
242    pub fn as_str(&self) -> Option<&str> {
243        match self.s {
244            Ok(ref s) => Some(s.as_str()),
245            Err(..) => None,
246        }
247    }
248
249    /// Returns the underlying `Utf8Error` if the string contains invalud UTF-8 sequence, or
250    /// else `None`.
251    #[inline]
252    #[must_use]
253    pub fn as_err(&self) -> Option<&Utf8Error> {
254        match self.s {
255            Ok(..) => None,
256            Err((_, ref err)) => Some(err),
257        }
258    }
259
260    /// Returns a byte slice of this `Utf8String`'s contents.
261    #[inline]
262    #[must_use]
263    pub fn as_bytes(&self) -> &[u8] {
264        match self.s {
265            Ok(ref s) => s.as_bytes(),
266            Err(ref err) => &err.0[..],
267        }
268    }
269
270    /// Consumes this object, yielding the string if the string is valid UTF-8, or else `None`.
271    #[inline]
272    #[must_use]
273    pub fn into_str(self) -> Option<String> {
274        self.s.ok()
275    }
276
277    /// Converts a `Utf8String` into a byte vector.
278    #[inline]
279    #[must_use]
280    pub fn into_bytes(self) -> Vec<u8> {
281        match self.s {
282            Ok(s) => s.into_bytes(),
283            Err(err) => err.0,
284        }
285    }
286
287    #[inline]
288    #[must_use]
289    pub fn as_ref(&self) -> Utf8StringRef<'_> {
290        match self.s {
291            Ok(ref s) => Utf8StringRef { s: Ok(s.as_str()) },
292            Err((ref buf, err)) => Utf8StringRef { s: Err((&buf[..], err)) },
293        }
294    }
295}
296
297impl Display for Utf8String {
298    #[cold]
299    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
300        match self.s {
301            Ok(ref s) => Debug::fmt(&s, fmt),
302            Err(ref err) => Debug::fmt(&err.0, fmt),
303        }
304    }
305}
306
307impl<'a> From<String> for Utf8String {
308    #[inline]
309    fn from(val: String) -> Self {
310        Utf8String { s: Ok(val) }
311    }
312}
313
314impl<'a> From<&'a str> for Utf8String {
315    #[inline]
316    fn from(val: &str) -> Self {
317        Utf8String { s: Ok(val.into()) }
318    }
319}
320
321impl<'a> From<Cow<'a, str>> for Utf8String {
322    #[inline]
323    fn from(val: Cow<'a, str>) -> Self {
324        Utf8String {
325            s: Ok(val.into_owned()),
326        }
327    }
328}
329
330/// A non-owning evil twin of `Utf8String`. Does exactly the same thing except ownership.
331#[derive(Clone, Copy, Debug, PartialEq)]
332pub struct Utf8StringRef<'a> {
333    s: Result<&'a str, (&'a [u8], Utf8Error)>,
334}
335
336impl<'a> Utf8StringRef<'a> {
337    /// Returns `true` if the string is valid UTF-8.
338    #[inline]
339    #[must_use]
340    pub fn is_str(&self) -> bool {
341        self.s.is_ok()
342    }
343
344    /// Returns `true` if the string contains invalid UTF-8 sequence.
345    #[inline]
346    #[must_use]
347    pub fn is_err(&self) -> bool {
348        self.s.is_err()
349    }
350
351    /// Returns the string reference if the string is valid UTF-8, or else `None`.
352    #[inline]
353    #[must_use]
354    pub fn as_str(&self) -> Option<&str> {
355        match self.s {
356            Ok(s) => Some(s),
357            Err(..) => None,
358        }
359    }
360
361    /// Returns the underlying `Utf8Error` if the string contains invalud UTF-8 sequence, or
362    /// else `None`.
363    #[inline]
364    #[must_use]
365    pub fn as_err(&self) -> Option<&Utf8Error> {
366        match self.s {
367            Ok(..) => None,
368            Err((_, ref err)) => Some(err),
369        }
370    }
371
372    /// Returns a byte slice of this string contents no matter whether it's valid or not UTF-8.
373    #[inline]
374    #[must_use]
375    pub fn as_bytes(&self) -> &[u8] {
376        match self.s {
377            Ok(s) => s.as_bytes(),
378            Err(ref err) => err.0,
379        }
380    }
381
382    /// Consumes this object, yielding the string if the string is valid UTF-8, or else `None`.
383    #[inline]
384    #[must_use]
385    pub fn into_string(self) -> Option<String> {
386        self.s.ok().map(|s| s.into())
387    }
388
389    /// Consumes this object, yielding the string reference if the string is valid UTF-8, or else `None`.
390    #[inline]
391    #[must_use]
392    pub fn into_str(self) -> Option<&'a str> {
393        self.s.ok()
394    }
395
396    /// Converts a `Utf8StringRef` into a byte vector.
397    #[inline]
398    #[must_use]
399    pub fn into_bytes(self) -> Vec<u8> {
400        match self.s {
401            Ok(s) => s.as_bytes().into(),
402            Err(err) => err.0.into(),
403        }
404    }
405}
406
407impl<'a> Display for Utf8StringRef<'a> {
408    #[cold]
409    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
410        match self.s {
411            Ok(ref s) => Debug::fmt(&s, fmt),
412            Err(ref err) => Debug::fmt(&err.0, fmt),
413        }
414    }
415}
416
417impl<'a> From<&'a str> for Utf8StringRef<'a> {
418    #[inline]
419    fn from(val: &'a str) -> Self {
420        Utf8StringRef { s: Ok(val) }
421    }
422}
423
424impl<'a> From<Utf8StringRef<'a>> for Utf8String {
425    fn from(val: Utf8StringRef<'a>) -> Self {
426        match val.s {
427            Ok(s) => Utf8String { s: Ok(s.into()) },
428            Err((buf, err)) => Utf8String { s: Err((buf.into(), err)) },
429        }
430    }
431}
432
433/// Represents any valid MessagePack value.
434#[derive(Clone, Debug, PartialEq)]
435pub enum Value {
436    /// Nil represents nil.
437    Nil,
438    /// Boolean represents true or false.
439    Boolean(bool),
440    /// Integer represents an integer.
441    ///
442    /// A value of an `Integer` object is limited from `-(2^63)` upto `(2^64)-1`.
443    ///
444    /// # Examples
445    ///
446    /// ```
447    /// use rmpv::Value;
448    ///
449    /// assert_eq!(42, Value::from(42).as_i64().unwrap());
450    /// ```
451    Integer(Integer),
452    /// A 32-bit floating point number.
453    F32(f32),
454    /// A 64-bit floating point number.
455    F64(f64),
456    /// String extending Raw type represents a UTF-8 string.
457    ///
458    /// # Note
459    ///
460    /// String objects may contain invalid byte sequence and the behavior of a deserializer depends
461    /// on the actual implementation when it received invalid byte sequence. Deserializers should
462    /// provide functionality to get the original byte array so that applications can decide how to
463    /// handle the object
464    String(Utf8String),
465    /// Binary extending Raw type represents a byte array.
466    Binary(Vec<u8>),
467    /// Array represents a sequence of objects.
468    Array(Vec<Value>),
469    /// Map represents key-value pairs of objects.
470    Map(Vec<(Value, Value)>),
471    /// Extended implements Extension interface: represents a tuple of type information and a byte
472    /// array where type information is an integer whose meaning is defined by applications.
473    Ext(i8, Vec<u8>),
474}
475
476impl Value {
477    /// Converts the current owned Value to a `ValueRef`.
478    ///
479    /// # Panics
480    ///
481    /// Panics in unable to allocate memory to keep all internal structures and buffers.
482    ///
483    /// # Examples
484    /// ```
485    /// use rmpv::{Value, ValueRef};
486    ///
487    /// let val = Value::Array(vec![
488    ///     Value::Nil,
489    ///     Value::from(42),
490    ///     Value::Array(vec![
491    ///         Value::String("le message".into())
492    ///     ])
493    /// ]);
494    ///
495    /// let expected = ValueRef::Array(vec![
496    ///    ValueRef::Nil,
497    ///    ValueRef::from(42),
498    ///    ValueRef::Array(vec![
499    ///        ValueRef::from("le message"),
500    ///    ])
501    /// ]);
502    ///
503    /// assert_eq!(expected, val.as_ref());
504    /// ```
505    #[must_use]
506    pub fn as_ref(&self) -> ValueRef<'_> {
507        match *self {
508            Value::Nil => ValueRef::Nil,
509            Value::Boolean(val) => ValueRef::Boolean(val),
510            Value::Integer(val) => ValueRef::Integer(val),
511            Value::F32(val) => ValueRef::F32(val),
512            Value::F64(val) => ValueRef::F64(val),
513            Value::String(ref val) => ValueRef::String(val.as_ref()),
514            Value::Binary(ref val) => ValueRef::Binary(val.as_slice()),
515            Value::Array(ref val) => {
516                ValueRef::Array(val.iter().map(|v| v.as_ref()).collect())
517            }
518            Value::Map(ref val) => {
519                ValueRef::Map(val.iter().map(|(k, v)| (k.as_ref(), v.as_ref())).collect())
520            }
521            Value::Ext(ty, ref buf) => ValueRef::Ext(ty, buf.as_slice()),
522        }
523    }
524
525    /// Returns true if the `Value` is a Null. Returns false otherwise.
526    ///
527    /// # Examples
528    ///
529    /// ```
530    /// use rmpv::Value;
531    ///
532    /// assert!(Value::Nil.is_nil());
533    /// ```
534    #[inline]
535    #[must_use]
536    pub fn is_nil(&self) -> bool {
537        if let Value::Nil = *self {
538            true
539        } else {
540            false
541        }
542    }
543
544    /// Returns true if the `Value` is a Boolean. Returns false otherwise.
545    ///
546    /// # Examples
547    ///
548    /// ```
549    /// use rmpv::Value;
550    ///
551    /// assert!(Value::Boolean(true).is_bool());
552    ///
553    /// assert!(!Value::Nil.is_bool());
554    /// ```
555    #[inline]
556    #[must_use]
557    pub fn is_bool(&self) -> bool {
558        self.as_bool().is_some()
559    }
560
561    /// Returns true if the `Value` is convertible to an i64. Returns false otherwise.
562    ///
563    /// # Examples
564    ///
565    /// ```
566    /// use rmpv::Value;
567    ///
568    /// assert!(Value::from(42).is_i64());
569    ///
570    /// assert!(!Value::from(42.0).is_i64());
571    /// ```
572    #[inline]
573    #[must_use]
574    pub fn is_i64(&self) -> bool {
575        if let Value::Integer(ref v) = *self {
576            v.is_i64()
577        } else {
578            false
579        }
580    }
581
582    /// Returns true if the `Value` is convertible to an u64. Returns false otherwise.
583    ///
584    /// # Examples
585    ///
586    /// ```
587    /// use rmpv::Value;
588    ///
589    /// assert!(Value::from(42).is_u64());
590    ///
591    /// assert!(!Value::F32(42.0).is_u64());
592    /// assert!(!Value::F64(42.0).is_u64());
593    /// ```
594    #[inline]
595    #[must_use]
596    pub fn is_u64(&self) -> bool {
597        if let Value::Integer(ref v) = *self {
598            v.is_u64()
599        } else {
600            false
601        }
602    }
603
604    /// Returns true if (and only if) the `Value` is a f32. Returns false otherwise.
605    ///
606    /// # Examples
607    ///
608    /// ```
609    /// use rmpv::Value;
610    ///
611    /// assert!(Value::F32(42.0).is_f32());
612    ///
613    /// assert!(!Value::from(42).is_f32());
614    /// assert!(!Value::F64(42.0).is_f32());
615    /// ```
616    #[inline]
617    #[must_use]
618    pub fn is_f32(&self) -> bool {
619        if let Value::F32(..) = *self {
620            true
621        } else {
622            false
623        }
624    }
625
626    /// Returns true if (and only if) the `Value` is a f64. Returns false otherwise.
627    ///
628    /// # Examples
629    ///
630    /// ```
631    /// use rmpv::Value;
632    ///
633    /// assert!(Value::F64(42.0).is_f64());
634    ///
635    /// assert!(!Value::from(42).is_f64());
636    /// assert!(!Value::F32(42.0).is_f64());
637    /// ```
638    #[inline]
639    #[must_use]
640    pub fn is_f64(&self) -> bool {
641        if let Value::F64(..) = *self {
642            true
643        } else {
644            false
645        }
646    }
647
648    /// Returns true if the `Value` is a Number. Returns false otherwise.
649    ///
650    /// # Examples
651    ///
652    /// ```
653    /// use rmpv::Value;
654    ///
655    /// assert!(Value::from(42).is_number());
656    /// assert!(Value::F32(42.0).is_number());
657    /// assert!(Value::F64(42.0).is_number());
658    ///
659    /// assert!(!Value::Nil.is_number());
660    /// ```
661    #[must_use]
662    pub fn is_number(&self) -> bool {
663        match *self {
664            Value::Integer(..) | Value::F32(..) | Value::F64(..) => true,
665            _ => false,
666        }
667    }
668
669    /// Returns true if the `Value` is a String. Returns false otherwise.
670    ///
671    /// # Examples
672    ///
673    /// ```
674    /// use rmpv::Value;
675    ///
676    /// assert!(Value::String("value".into()).is_str());
677    ///
678    /// assert!(!Value::Nil.is_str());
679    /// ```
680    #[inline]
681    #[must_use]
682    pub fn is_str(&self) -> bool {
683        self.as_str().is_some()
684    }
685
686    /// Returns true if the `Value` is a Binary. Returns false otherwise.
687    #[inline]
688    #[must_use]
689    pub fn is_bin(&self) -> bool {
690        self.as_slice().is_some()
691    }
692
693    /// Returns true if the `Value` is an Array. Returns false otherwise.
694    #[inline]
695    #[must_use]
696    pub fn is_array(&self) -> bool {
697        self.as_array().is_some()
698    }
699
700    /// Returns true if the `Value` is a Map. Returns false otherwise.
701    #[inline]
702    #[must_use]
703    pub fn is_map(&self) -> bool {
704        self.as_map().is_some()
705    }
706
707    /// Returns true if the `Value` is an Ext. Returns false otherwise.
708    #[inline]
709    #[must_use]
710    pub fn is_ext(&self) -> bool {
711        self.as_ext().is_some()
712    }
713
714    /// If the `Value` is a Boolean, returns the associated bool.
715    /// Returns None otherwise.
716    ///
717    /// # Examples
718    ///
719    /// ```
720    /// use rmpv::Value;
721    ///
722    /// assert_eq!(Some(true), Value::Boolean(true).as_bool());
723    ///
724    /// assert_eq!(None, Value::Nil.as_bool());
725    /// ```
726    #[inline]
727    #[must_use]
728    pub fn as_bool(&self) -> Option<bool> {
729        if let Value::Boolean(val) = *self {
730            Some(val)
731        } else {
732            None
733        }
734    }
735
736    /// If the `Value` is an integer, return or cast it to a i64.
737    /// Returns None otherwise.
738    ///
739    /// # Examples
740    ///
741    /// ```
742    /// use rmpv::Value;
743    ///
744    /// assert_eq!(Some(42i64), Value::from(42).as_i64());
745    ///
746    /// assert_eq!(None, Value::F64(42.0).as_i64());
747    /// ```
748    #[inline]
749    #[must_use]
750    pub fn as_i64(&self) -> Option<i64> {
751        match *self {
752            Value::Integer(ref n) => n.as_i64(),
753            _ => None,
754        }
755    }
756
757    /// If the `Value` is an integer, return or cast it to a u64.
758    /// Returns None otherwise.
759    ///
760    /// # Examples
761    ///
762    /// ```
763    /// use rmpv::Value;
764    ///
765    /// assert_eq!(Some(42u64), Value::from(42).as_u64());
766    ///
767    /// assert_eq!(None, Value::from(-42).as_u64());
768    /// assert_eq!(None, Value::F64(42.0).as_u64());
769    /// ```
770    #[inline]
771    #[must_use]
772    pub fn as_u64(&self) -> Option<u64> {
773        match *self {
774            Value::Integer(ref n) => n.as_u64(),
775            _ => None,
776        }
777    }
778
779    /// If the `Value` is a number, return or cast it to a f64.
780    /// Returns None otherwise.
781    ///
782    /// # Examples
783    ///
784    /// ```
785    /// use rmpv::Value;
786    ///
787    /// assert_eq!(Some(42.0), Value::from(42).as_f64());
788    /// assert_eq!(Some(42.0), Value::F32(42.0f32).as_f64());
789    /// assert_eq!(Some(42.0), Value::F64(42.0f64).as_f64());
790    ///
791    /// assert_eq!(Some(2147483647.0), Value::from(i32::MAX as i64).as_f64());
792    ///
793    /// assert_eq!(None, Value::Nil.as_f64());
794    /// ```
795    #[must_use]
796    pub fn as_f64(&self) -> Option<f64> {
797        match *self {
798            Value::Integer(ref n) => n.as_f64(),
799            Value::F32(n) => Some(From::from(n)),
800            Value::F64(n) => Some(n),
801            _ => None,
802        }
803    }
804
805    /// If the `Value` is a String, returns the associated str.
806    /// Returns None otherwise.
807    ///
808    /// # Examples
809    ///
810    /// ```
811    /// use rmpv::Value;
812    ///
813    /// assert_eq!(Some("le message"), Value::String("le message".into()).as_str());
814    ///
815    /// assert_eq!(None, Value::Boolean(true).as_str());
816    /// ```
817    #[inline]
818    #[must_use]
819    pub fn as_str(&self) -> Option<&str> {
820        if let Value::String(ref val) = *self {
821            val.as_str()
822        } else {
823            None
824        }
825    }
826
827    /// If the `Value` is a Binary or a String, returns the associated slice.
828    /// Returns None otherwise.
829    ///
830    /// # Examples
831    ///
832    /// ```
833    /// use rmpv::Value;
834    ///
835    /// assert_eq!(Some(&[1, 2, 3, 4, 5][..]), Value::Binary(vec![1, 2, 3, 4, 5]).as_slice());
836    ///
837    /// assert_eq!(None, Value::Boolean(true).as_slice());
838    /// ```
839    #[must_use]
840    pub fn as_slice(&self) -> Option<&[u8]> {
841        if let Value::Binary(ref val) = *self {
842            Some(val)
843        } else if let Value::String(ref val) = *self {
844            Some(val.as_bytes())
845        } else {
846            None
847        }
848    }
849
850    /// If the `Value` is an Array, returns the associated vector.
851    /// Returns None otherwise.
852    ///
853    /// # Examples
854    ///
855    /// ```
856    /// use rmpv::Value;
857    ///
858    /// let val = Value::Array(vec![Value::Nil, Value::Boolean(true)]);
859    ///
860    /// assert_eq!(Some(&vec![Value::Nil, Value::Boolean(true)]), val.as_array());
861    ///
862    /// assert_eq!(None, Value::Nil.as_array());
863    /// ```
864    #[inline]
865    #[must_use]
866    pub fn as_array(&self) -> Option<&Vec<Value>> {
867        if let Value::Array(ref array) = *self {
868            Some(array)
869        } else {
870            None
871        }
872    }
873
874    /// If the `Value` is a Map, returns the associated vector of key-value tuples.
875    /// Returns None otherwise.
876    ///
877    /// # Note
878    ///
879    /// MessagePack represents map as a vector of key-value tuples.
880    ///
881    /// # Examples
882    ///
883    /// ```
884    /// use rmpv::Value;
885    ///
886    /// let val = Value::Map(vec![(Value::Nil, Value::Boolean(true))]);
887    ///
888    /// assert_eq!(Some(&vec![(Value::Nil, Value::Boolean(true))]), val.as_map());
889    ///
890    /// assert_eq!(None, Value::Nil.as_map());
891    /// ```
892    #[inline]
893    #[must_use]
894    pub fn as_map(&self) -> Option<&Vec<(Value, Value)>> {
895        if let Value::Map(ref map) = *self {
896            Some(map)
897        } else {
898            None
899        }
900    }
901
902    /// If the `Value` is an Ext, returns the associated tuple with a ty and slice.
903    /// Returns None otherwise.
904    ///
905    /// # Examples
906    ///
907    /// ```
908    /// use rmpv::Value;
909    ///
910    /// assert_eq!(Some((42, &[1, 2, 3, 4, 5][..])), Value::Ext(42, vec![1, 2, 3, 4, 5]).as_ext());
911    ///
912    /// assert_eq!(None, Value::Boolean(true).as_ext());
913    /// ```
914    #[inline]
915    #[must_use]
916    pub fn as_ext(&self) -> Option<(i8, &[u8])> {
917        if let Value::Ext(ty, ref buf) = *self {
918            Some((ty, buf))
919        } else {
920            None
921        }
922    }
923}
924
925static NIL: Value = Value::Nil;
926static NIL_REF: ValueRef<'static> = ValueRef::Nil;
927
928impl Index<usize> for Value {
929    type Output = Value;
930
931    fn index(&self, index: usize) -> &Value {
932        self.as_array().and_then(|v| v.get(index)).unwrap_or(&NIL)
933    }
934}
935
936impl Index<&str> for Value {
937    type Output = Value;
938    fn index(&self, index: &str) -> &Value {
939        if let Value::Map(ref map) = *self {
940            if let Some(found) = map.iter().find(
941                |(key, _val)|  {
942                if let Value::String(ref strval) = *key {
943                    if let Some(s) = strval.as_str() {
944                        if s == index { return true; }
945                    }
946                }
947                false
948                })
949            {
950                return &found.1;
951            }
952        }
953        &NIL
954    }
955}
956
957impl From<bool> for Value {
958    #[inline]
959    fn from(v: bool) -> Self {
960        Value::Boolean(v)
961    }
962}
963
964impl From<u8> for Value {
965    #[inline]
966    fn from(v: u8) -> Self {
967        Value::Integer(From::from(v))
968    }
969}
970
971impl From<u16> for Value {
972    #[inline]
973    fn from(v: u16) -> Self {
974        Value::Integer(From::from(v))
975    }
976}
977
978impl From<u32> for Value {
979    #[inline]
980    fn from(v: u32) -> Self {
981        Value::Integer(From::from(v))
982    }
983}
984
985impl From<u64> for Value {
986    #[inline]
987    fn from(v: u64) -> Self {
988        Value::Integer(From::from(v))
989    }
990}
991
992impl From<usize> for Value {
993    #[inline]
994    fn from(v: usize) -> Self {
995        Value::Integer(From::from(v))
996    }
997}
998
999impl From<i8> for Value {
1000    #[inline]
1001    fn from(v: i8) -> Self {
1002        Value::Integer(From::from(v))
1003    }
1004}
1005
1006impl From<i16> for Value {
1007    #[inline]
1008    fn from(v: i16) -> Self {
1009        Value::Integer(From::from(v))
1010    }
1011}
1012
1013impl From<i32> for Value {
1014    #[inline]
1015    fn from(v: i32) -> Self {
1016        Value::Integer(From::from(v))
1017    }
1018}
1019
1020impl From<i64> for Value {
1021    #[inline]
1022    fn from(v: i64) -> Self {
1023        Value::Integer(From::from(v))
1024    }
1025}
1026
1027impl From<isize> for Value {
1028    #[inline]
1029    fn from(v: isize) -> Self {
1030        Value::Integer(From::from(v))
1031    }
1032}
1033
1034impl From<f32> for Value {
1035    #[inline]
1036    fn from(v: f32) -> Self {
1037        Value::F32(v)
1038    }
1039}
1040
1041impl From<f64> for Value {
1042    #[inline]
1043    fn from(v: f64) -> Self {
1044        Value::F64(v)
1045    }
1046}
1047
1048impl From<String> for Value {
1049    #[inline]
1050    fn from(v: String) -> Self {
1051        Value::String(Utf8String::from(v))
1052    }
1053}
1054
1055impl<'a> From<&'a str> for Value {
1056    #[inline]
1057    fn from(v: &str) -> Self {
1058        Value::String(Utf8String::from(v))
1059    }
1060}
1061
1062impl<'a> From<Cow<'a, str>> for Value {
1063    #[inline]
1064    fn from(v: Cow<'a, str>) -> Self {
1065        Value::String(Utf8String::from(v))
1066    }
1067}
1068
1069impl From<Vec<u8>> for Value {
1070    #[inline]
1071    fn from(v: Vec<u8>) -> Self {
1072        Value::Binary(v)
1073    }
1074}
1075
1076impl<'a> From<&'a [u8]> for Value {
1077    #[inline]
1078    fn from(v: &[u8]) -> Self {
1079        Value::Binary(v.into())
1080    }
1081}
1082
1083impl<'a> From<Cow<'a, [u8]>> for Value {
1084    #[inline]
1085    fn from(v: Cow<'a, [u8]>) -> Self {
1086        Value::Binary(v.into_owned())
1087    }
1088}
1089
1090impl From<Vec<Value>> for Value {
1091    #[inline]
1092    fn from(v: Vec<Value>) -> Self {
1093        Value::Array(v)
1094    }
1095}
1096
1097impl From<Vec<(Value, Value)>> for Value {
1098    #[inline]
1099    fn from(v: Vec<(Value, Value)>) -> Self {
1100        Value::Map(v)
1101    }
1102}
1103
1104/// Note that an `Iterator<Item = u8>` will be collected into an
1105/// [`Array`](crate::Value::Array), rather than a
1106/// [`Binary`](crate::Value::Binary)
1107impl<V> FromIterator<V> for Value
1108where V: Into<Value> {
1109  fn from_iter<I: IntoIterator<Item = V>>(iter: I) -> Self {
1110    let v: Vec<Value> = iter.into_iter().map(|v| v.into()).collect();
1111    Value::Array(v)
1112  }
1113}
1114
1115impl TryFrom<Value> for u64 {
1116  type Error = Value;
1117
1118  fn try_from(val: Value) -> Result<Self, Self::Error> {
1119      match val {
1120        Value::Integer(n) => {
1121          match n.as_u64() {
1122            Some(i) => Ok(i),
1123            None => Err(val)
1124          }
1125        }
1126        v => Err(v),
1127      }
1128  }
1129}
1130
1131impl TryFrom<Value> for i64 {
1132  type Error = Value;
1133
1134  fn try_from(val: Value) -> Result<Self, Self::Error> {
1135      match val {
1136        Value::Integer(n) => {
1137          match n.as_i64() {
1138            Some(i) => Ok(i),
1139            None => Err(val)
1140          }
1141        }
1142        v => Err(v),
1143      }
1144  }
1145}
1146
1147impl TryFrom<Value> for f64 {
1148  type Error = Value;
1149
1150  fn try_from(val: Value) -> Result<Self, Self::Error> {
1151      match val {
1152        Value::Integer(n) => {
1153          match n.as_f64() {
1154            Some(i) => Ok(i),
1155            None => Err(val)
1156          }
1157        }
1158        Value::F32(n) => Ok(From::from(n)),
1159        Value::F64(n) => Ok(n),
1160        v => Err(v),
1161      }
1162  }
1163}
1164
1165impl TryFrom<Value> for String {
1166  type Error = Value;
1167
1168  fn try_from(val: Value) -> Result<Self, Self::Error> {
1169    match val {
1170      Value::String(Utf8String{ s: Ok(u)}) => {
1171        Ok(u)
1172      }
1173      _ => Err(val)
1174    }
1175  }
1176}
1177// The following impl was left out intentionally, see
1178// https://github.com/3Hren/msgpack-rust/pull/228#discussion_r359513925
1179/*
1180impl TryFrom<Value> for (i8, Vec<u8>) {
1181  type Error = Value;
1182
1183  fn try_from(val: Value) -> Result<Self, Self::Error> {
1184      match val {
1185        Value::Ext(i, v) => Ok((i, v)),
1186        v => Err(v),
1187      }
1188  }
1189}
1190*/
1191
1192macro_rules! impl_try_from {
1193  ($t: ty, $p: ident) => {
1194    impl TryFrom<Value> for $t {
1195      type Error = Value;
1196
1197      fn try_from(val: Value) -> Result<$t, Self::Error> {
1198        match val {
1199          Value::$p(v) => Ok(v),
1200          v => Err(v)
1201        }
1202      }
1203    }
1204  };
1205}
1206
1207impl_try_from!(bool, Boolean);
1208impl_try_from!(Vec<Value>, Array);
1209impl_try_from!(Vec<(Value, Value)>, Map);
1210impl_try_from!(Vec<u8>, Binary);
1211impl_try_from!(f32, F32);
1212impl_try_from!(Utf8String, String);
1213
1214impl Display for Value {
1215    #[cold]
1216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1217        match *self {
1218            Value::Nil => f.write_str("nil"),
1219            Value::Boolean(val) => Display::fmt(&val, f),
1220            Value::Integer(ref val) => Display::fmt(&val, f),
1221            Value::F32(val) => Display::fmt(&val, f),
1222            Value::F64(val) => Display::fmt(&val, f),
1223            Value::String(ref val) => Display::fmt(&val, f),
1224            Value::Binary(ref val) => Debug::fmt(&val, f),
1225            Value::Array(ref vec) => {
1226                // TODO: This can be slower than naive implementation. Need benchmarks for more
1227                // information.
1228                let res = vec.iter()
1229                    .map(|val| format!("{val}"))
1230                    .collect::<Vec<String>>()
1231                    .join(", ");
1232
1233                write!(f, "[{res}]")
1234            }
1235            Value::Map(ref vec) => {
1236                write!(f, "{{")?;
1237
1238                match vec.iter().take(1).next() {
1239                    Some((k, v)) => {
1240                        write!(f, "{k}: {v}")?;
1241                    }
1242                    None => {
1243                        write!(f, "")?;
1244                    }
1245                }
1246
1247                for (k, v) in vec.iter().skip(1) {
1248                    write!(f, ", {k}: {v}")?;
1249                }
1250
1251                write!(f, "}}")
1252            }
1253            Value::Ext(ty, ref data) => {
1254                write!(f, "[{ty}, {data:?}]")
1255            }
1256        }
1257    }
1258}
1259
1260#[derive(Clone, Debug, PartialEq)]
1261pub enum ValueRef<'a> {
1262    /// Nil represents nil.
1263    Nil,
1264    /// Boolean represents true or false.
1265    Boolean(bool),
1266    /// Integer represents an integer.
1267    ///
1268    /// A value of an `Integer` object is limited from `-(2^63)` upto `(2^64)-1`.
1269    Integer(Integer),
1270    /// A 32-bit floating point number.
1271    F32(f32),
1272    /// A 64-bit floating point number.
1273    F64(f64),
1274    /// String extending Raw type represents a UTF-8 string.
1275    String(Utf8StringRef<'a>),
1276    /// Binary extending Raw type represents a byte array.
1277    Binary(&'a [u8]),
1278    /// Array represents a sequence of objects.
1279    Array(Vec<ValueRef<'a>>),
1280    /// Map represents key-value pairs of objects.
1281    Map(Vec<(ValueRef<'a>, ValueRef<'a>)>),
1282    /// Extended implements Extension interface: represents a tuple of type information and a byte
1283    /// array where type information is an integer whose meaning is defined by applications.
1284    Ext(i8, &'a [u8]),
1285}
1286
1287impl<'a> ValueRef<'a> {
1288    /// Converts the current non-owning value to an owned Value.
1289    ///
1290    /// This is achieved by deep copying all underlying structures and borrowed buffers.
1291    ///
1292    /// # Panics
1293    ///
1294    /// Panics in unable to allocate memory to keep all internal structures and buffers.
1295    ///
1296    /// # Examples
1297    /// ```
1298    /// use rmpv::{Value, ValueRef};
1299    ///
1300    /// let val = ValueRef::Array(vec![
1301    ///    ValueRef::Nil,
1302    ///    ValueRef::from(42),
1303    ///    ValueRef::Array(vec![
1304    ///        ValueRef::from("le message"),
1305    ///    ])
1306    /// ]);
1307    ///
1308    /// let expected = Value::Array(vec![
1309    ///     Value::Nil,
1310    ///     Value::from(42),
1311    ///     Value::Array(vec![
1312    ///         Value::String("le message".into())
1313    ///     ])
1314    /// ]);
1315    ///
1316    /// assert_eq!(expected, val.to_owned());
1317    /// ```
1318    #[must_use]
1319    pub fn to_owned(&self) -> Value {
1320        match *self {
1321            ValueRef::Nil => Value::Nil,
1322            ValueRef::Boolean(val) => Value::Boolean(val),
1323            ValueRef::Integer(val) => Value::Integer(val),
1324            ValueRef::F32(val) => Value::F32(val),
1325            ValueRef::F64(val) => Value::F64(val),
1326            ValueRef::String(val) => Value::String(val.into()),
1327            ValueRef::Binary(val) => Value::Binary(val.to_vec()),
1328            ValueRef::Array(ref val) => {
1329                Value::Array(val.iter().map(|v| v.to_owned()).collect())
1330            }
1331            ValueRef::Map(ref val) => {
1332                Value::Map(val.iter().map(|(k, v)| (k.to_owned(), v.to_owned())).collect())
1333            }
1334            ValueRef::Ext(ty, buf) => Value::Ext(ty, buf.to_vec()),
1335        }
1336    }
1337
1338    #[must_use]
1339    pub fn index(&self, index: usize) -> &ValueRef<'_> {
1340        self.as_array().and_then(|v| v.get(index)).unwrap_or(&NIL_REF)
1341    }
1342
1343    /// If the `ValueRef` is an integer, return or cast it to a u64.
1344    /// Returns None otherwise.
1345    ///
1346    /// # Examples
1347    ///
1348    /// ```
1349    /// use rmpv::ValueRef;
1350    ///
1351    /// assert_eq!(Some(42), ValueRef::from(42).as_u64());
1352    /// ```
1353    #[must_use]
1354    pub fn as_u64(&self) -> Option<u64> {
1355        match *self {
1356            ValueRef::Integer(ref n) => n.as_u64(),
1357            _ => None,
1358        }
1359    }
1360
1361    /// If the `ValueRef` is an Array, returns the associated vector.
1362    /// Returns None otherwise.
1363    ///
1364    /// # Examples
1365    ///
1366    /// ```
1367    /// use rmpv::ValueRef;
1368    ///
1369    /// let val = ValueRef::Array(vec![ValueRef::Nil, ValueRef::Boolean(true)]);
1370    ///
1371    /// assert_eq!(Some(&vec![ValueRef::Nil, ValueRef::Boolean(true)]), val.as_array());
1372    /// assert_eq!(None, ValueRef::Nil.as_array());
1373    /// ```
1374    #[must_use]
1375    pub fn as_array(&self) -> Option<&Vec<ValueRef<'_>>> {
1376        if let ValueRef::Array(ref array) = *self {
1377            Some(array)
1378        } else {
1379            None
1380        }
1381    }
1382
1383    #[inline]
1384    #[must_use]
1385    pub fn into_array(self) -> Option<Vec<ValueRef<'a>>> {
1386        if let ValueRef::Array(array) = self {
1387            Some(array)
1388        } else {
1389            None
1390        }
1391    }
1392}
1393
1394impl<'a> From<u8> for ValueRef<'a> {
1395    #[inline]
1396    fn from(v: u8) -> Self {
1397        ValueRef::Integer(From::from(v))
1398    }
1399}
1400
1401impl<'a> From<u16> for ValueRef<'a> {
1402    #[inline]
1403    fn from(v: u16) -> Self {
1404        ValueRef::Integer(From::from(v))
1405    }
1406}
1407
1408impl<'a> From<u32> for ValueRef<'a> {
1409    #[inline]
1410    fn from(v: u32) -> Self {
1411        ValueRef::Integer(From::from(v))
1412    }
1413}
1414
1415impl<'a> From<u64> for ValueRef<'a> {
1416    #[inline]
1417    fn from(v: u64) -> Self {
1418        ValueRef::Integer(From::from(v))
1419    }
1420}
1421
1422impl<'a> From<usize> for ValueRef<'a> {
1423    #[inline]
1424    fn from(v: usize) -> Self {
1425        ValueRef::Integer(From::from(v))
1426    }
1427}
1428
1429impl<'a> From<i8> for ValueRef<'a> {
1430    #[inline]
1431    fn from(v: i8) -> Self {
1432        ValueRef::Integer(From::from(v))
1433    }
1434}
1435
1436impl<'a> From<i16> for ValueRef<'a> {
1437    #[inline]
1438    fn from(v: i16) -> Self {
1439        ValueRef::Integer(From::from(v))
1440    }
1441}
1442
1443impl<'a> From<i32> for ValueRef<'a> {
1444    #[inline]
1445    fn from(v: i32) -> Self {
1446        ValueRef::Integer(From::from(v))
1447    }
1448}
1449
1450impl<'a> From<i64> for ValueRef<'a> {
1451    #[inline]
1452    fn from(v: i64) -> Self {
1453        ValueRef::Integer(From::from(v))
1454    }
1455}
1456
1457impl<'a> From<isize> for ValueRef<'a> {
1458    #[inline]
1459    fn from(v: isize) -> Self {
1460        ValueRef::Integer(From::from(v))
1461    }
1462}
1463
1464impl<'a> From<f32> for ValueRef<'a> {
1465    #[inline]
1466    fn from(v: f32) -> Self {
1467        ValueRef::F32(v)
1468    }
1469}
1470
1471impl<'a> From<f64> for ValueRef<'a> {
1472    #[inline]
1473    fn from(v: f64) -> Self {
1474        ValueRef::F64(v)
1475    }
1476}
1477
1478impl<'a> From<&'a str> for ValueRef<'a> {
1479    #[inline]
1480    fn from(v: &'a str) -> Self {
1481        ValueRef::String(Utf8StringRef::from(v))
1482    }
1483}
1484
1485impl<'a> From<&'a [u8]> for ValueRef<'a> {
1486    #[inline]
1487    fn from(v: &'a [u8]) -> Self {
1488        ValueRef::Binary(v)
1489    }
1490}
1491
1492impl<'a> From<Vec<ValueRef<'a>>> for ValueRef<'a> {
1493    #[inline]
1494    fn from(v: Vec<ValueRef<'a>>) -> Self {
1495        ValueRef::Array(v)
1496    }
1497}
1498
1499/// Note that an `Iterator<Item = u8>` will be collected into an
1500/// [`Array`](crate::Value::Array), rather than a
1501/// [`Binary`](crate::Value::Binary)
1502impl<'a, V> FromIterator<V> for ValueRef<'a>
1503where V: Into<ValueRef<'a>> {
1504  fn from_iter<I: IntoIterator<Item = V>>(iter: I) -> Self {
1505    let v: Vec<ValueRef<'a>> = iter.into_iter().map(|v| v.into()).collect();
1506    ValueRef::Array(v)
1507  }
1508}
1509
1510impl<'a> From<Vec<(ValueRef<'a>, ValueRef<'a>)>> for ValueRef<'a> {
1511    fn from(v: Vec<(ValueRef<'a>, ValueRef<'a>)>) -> Self {
1512        ValueRef::Map(v)
1513    }
1514}
1515
1516impl<'a> TryFrom<ValueRef<'a>> for u64 {
1517    type Error = ValueRef<'a>;
1518
1519    fn try_from(val: ValueRef<'a>) -> Result<Self, Self::Error> {
1520        match val {
1521            ValueRef::Integer(n) => match n.as_u64() {
1522                Some(i) => Ok(i),
1523                None => Err(val),
1524            },
1525            v => Err(v),
1526        }
1527    }
1528}
1529
1530// The following impl was left out intentionally, see
1531// https://github.com/3Hren/msgpack-rust/pull/228#discussion_r359513925
1532/*
1533impl<'a> TryFrom<ValueRef<'a>> for (i8, &'a[u8]) {
1534  type Error = ValueRef<'a>;
1535
1536  fn try_from(val: ValueRef<'a>) -> Result<Self, Self::Error> {
1537      match val {
1538        ValueRef::Ext(i, v) => Ok((i, v)),
1539        v => Err(v),
1540      }
1541  }
1542}
1543*/
1544
1545macro_rules! impl_try_from_ref {
1546  ($t: ty, $p: ident) => {
1547    impl<'a> TryFrom<ValueRef<'a>> for $t {
1548      type Error = ValueRef<'a>;
1549
1550      fn try_from(val: ValueRef<'a>) -> Result<$t, Self::Error> {
1551        match val {
1552          ValueRef::$p(v) => Ok(v),
1553          v => Err(v)
1554        }
1555      }
1556    }
1557  };
1558}
1559
1560impl_try_from_ref!(bool, Boolean);
1561impl_try_from_ref!(Vec<ValueRef<'a>>, Array);
1562impl_try_from_ref!(Vec<(ValueRef<'a>, ValueRef<'a>)>, Map);
1563impl_try_from_ref!(&'a [u8], Binary);
1564impl_try_from_ref!(f32, F32);
1565impl_try_from_ref!(Utf8StringRef<'a>, String);
1566
1567impl<'a> Display for ValueRef<'a> {
1568    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1569        match *self {
1570            ValueRef::Nil => write!(f, "nil"),
1571            ValueRef::Boolean(val) => Display::fmt(&val, f),
1572            ValueRef::Integer(ref val) => Display::fmt(&val, f),
1573            ValueRef::F32(val) => Display::fmt(&val, f),
1574            ValueRef::F64(val) => Display::fmt(&val, f),
1575            ValueRef::String(ref val) => Display::fmt(&val, f),
1576            ValueRef::Binary(ref val) => Debug::fmt(&val, f),
1577            ValueRef::Array(ref vec) => {
1578                let res = vec.iter()
1579                    .map(|val| format!("{val}"))
1580                    .collect::<Vec<String>>()
1581                    .join(", ");
1582
1583                write!(f, "[{res}]")
1584            }
1585            ValueRef::Map(ref vec) => {
1586                write!(f, "{{")?;
1587
1588                match vec.iter().take(1).next() {
1589                    Some((k, v)) => {
1590                        write!(f, "{k}: {v}")?;
1591                    }
1592                    None => {
1593                        write!(f, "")?;
1594                    }
1595                }
1596
1597                for (k, v) in vec.iter().skip(1) {
1598                    write!(f, ", {k}: {v}")?;
1599                }
1600
1601                write!(f, "}}")
1602            }
1603            ValueRef::Ext(ty, data) => {
1604                write!(f, "[{ty}, {data:?}]")
1605            }
1606        }
1607    }
1608}