rmpv/
lib.rs

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