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