msgpack/
value.rs

1pub mod float;
2pub mod from;
3pub mod integer;
4pub mod utf8_string;
5
6pub use float::Float;
7pub use float::Number as FloatNumber;
8pub use integer::Integer;
9pub use integer::Number as IntegerNumber;
10pub use utf8_string::{Utf8String, Utf8StringRef};
11
12use chrono::{self, TimeZone};
13use std::fmt;
14
15pub struct Nil;
16
17#[derive(Clone, PartialEq, Debug)]
18pub enum Value {
19    // represents an integer
20    Integer(integer::Integer),
21
22    // represents nil
23    Nil,
24
25    // represents true or false
26    Boolean(bool),
27
28    // represents a IEEE 754 double precision floating point number including NaN and Infinity
29    Float(float::Float),
30
31    // Raw. extending Raw type represents a byte array
32    Binary(Vec<u8>),
33
34    // Raw. extending Raw type represents a UTF-8 string
35    String(utf8_string::Utf8String),
36
37    // represents a sequence of objects
38    Array(Vec<Value>),
39
40    // represents key-value pairs of objects
41    Map(Vec<(Value, Value)>),
42
43    // represents a tuple of type information and a byte array where type information is an integer whose meaning is defined by applications or MessagePack specification
44    Extension(i8, Vec<u8>),
45
46    // represents an instantaneous point on the time-line in the world that is independent from time zones or calendars. Maximum precision is nanoseconds.
47    Timestamp(i64, u32),
48}
49
50impl fmt::Display for Value {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match self {
53            Value::Nil => write!(f, "null"),
54            Value::Boolean(val) => write!(f, "{}", if *val { "true" } else { "false" }),
55            Value::Float(val) => val.fmt(f),
56            Value::Integer(val) => val.fmt(f),
57            Value::Binary(ref val) => {
58                for v in val {
59                    write!(f, "{:02X}", v)?;
60                }
61                Ok(())
62            }
63            Value::String(ref val) => val.fmt(f),
64            Value::Array(ref val) => {
65                write!(f, "[")?;
66                let mut s = true;
67                for v in val {
68                    if s {
69                        s = false
70                    } else {
71                        write!(f, ", ")?;
72                    }
73
74                    v.fmt(f)?;
75                }
76                write!(f, "]")
77            }
78            Value::Map(ref val) => {
79                write!(f, "{{")?;
80                let mut s = true;
81                for v in val {
82                    if s {
83                        s = false
84                    } else {
85                        write!(f, ", ")?;
86                    }
87
88                    write!(f, "{}: {}", v.0, v.1)?;
89                }
90                write!(f, "}}")
91            }
92            Value::Extension(ty, ref buf) => {
93                write!(f, "Extension({}, ", ty)?;
94                for b in buf {
95                    write!(f, "{:X}", b)?;
96                }
97                write!(f, ")")
98            }
99
100            Value::Timestamp(sec, nsec) => {
101                write!(f, "{}", chrono::Local.timestamp(*sec as i64, *nsec))
102            }
103        }
104    }
105}
106
107#[derive(Debug, PartialEq)]
108pub enum RefValue<'a> {
109    // represents an integer
110    Integer(integer::Integer),
111
112    // represents nil
113    Nil,
114
115    // represents true or false
116    Boolean(bool),
117
118    // represents a IEEE 754 double precision floating point number including NaN and Infinity
119    Float(float::Float),
120
121    // Raw. extending Raw type represents a byte array
122    Binary(&'a [u8]),
123
124    // Raw. extending Raw type represents a UTF-8 string
125    String(utf8_string::Utf8StringRef<'a>),
126
127    // represents a sequence of objects
128    Array(Vec<RefValue<'a>>),
129
130    // represents key-value pairs of objects
131    Map(Vec<(RefValue<'a>, RefValue<'a>)>),
132
133    // represents a tuple of type information and a byte array where type information is an integer whose meaning is defined by applications or MessagePack specification
134    Extension(i8, &'a [u8]),
135
136    // represents an instantaneous point on the time-line in the world that is independent from time zones or calendars. Maximum precision is nanoseconds.
137    Timestamp(i64, u32),
138}
139
140impl<'a> fmt::Display for RefValue<'a> {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        match self {
143            RefValue::Nil => write!(f, "null"),
144            RefValue::Boolean(val) => write!(f, "{}", if *val { "true" } else { "false" }),
145            RefValue::Float(val) => val.fmt(f),
146            RefValue::Integer(val) => val.fmt(f),
147            RefValue::Binary(val) => {
148                for v in *val {
149                    write!(f, "{:02X}", v)?;
150                }
151                Ok(())
152            }
153            RefValue::String(ref val) => val.fmt(f),
154            RefValue::Array(ref val) => {
155                write!(f, "[")?;
156                let mut s = true;
157                for v in val {
158                    if s {
159                        s = false
160                    } else {
161                        write!(f, ", ")?;
162                    }
163
164                    v.fmt(f)?;
165                }
166                write!(f, "]")
167            }
168            RefValue::Map(ref val) => {
169                write!(f, "{{")?;
170                let mut s = true;
171                for v in val {
172                    if s {
173                        s = false
174                    } else {
175                        write!(f, ", ")?;
176                    }
177
178                    write!(f, "{}: {}", v.0, v.1)?;
179                }
180                write!(f, "}}")
181            }
182            RefValue::Extension(ty, buf) => {
183                write!(f, "Extension({}, ", ty)?;
184                for b in *buf {
185                    write!(f, "{:X}", b)?;
186                }
187                write!(f, ")")
188            }
189            RefValue::Timestamp(sec, nsec) => {
190                write!(f, "{}", chrono::Local.timestamp(*sec as i64, *nsec))
191            }
192        }
193    }
194}
195
196impl Value {
197    pub fn to_ref(&self) -> RefValue {
198        match self {
199            &Value::Nil => RefValue::Nil,
200            &Value::Boolean(val) => RefValue::Boolean(val),
201            &Value::Float(v) => RefValue::Float(v),
202            &Value::Integer(val) => RefValue::Integer(val),
203            &Value::Binary(ref v) => RefValue::Binary(v.as_slice()),
204            &Value::String(ref v) => RefValue::String(v.as_ref()), // XXX
205            &Value::Array(ref v) => RefValue::Array(v.iter().map(|v| v.to_ref()).collect()),
206            &Value::Map(ref v) => RefValue::Map(
207                v.iter()
208                    .map(|&(ref k, ref v)| (k.to_ref(), v.to_ref()))
209                    .collect(),
210            ),
211            &Value::Extension(ty, ref buf) => RefValue::Extension(ty, buf.as_slice()),
212            &Value::Timestamp(sec, nsec) => RefValue::Timestamp(sec, nsec),
213        }
214    }
215
216    pub fn to_nil(&self) -> Option<Nil> {
217        match self {
218            Value::Nil => Some(Nil),
219            _ => None,
220        }
221    }
222
223    pub fn to_ary(&self) -> Option<&Vec<Value>> {
224        match self {
225            Value::Array(v) => Some(v),
226            _ => None,
227        }
228    }
229}
230
231impl<'a> RefValue<'a> {
232    pub fn to_owned(&self) -> Value {
233        match self {
234            &RefValue::Nil => Value::Nil,
235            &RefValue::Boolean(v) => Value::Boolean(v),
236            &RefValue::Integer(v) => Value::Integer(v),
237            &RefValue::Float(v) => Value::Float(v),
238            &RefValue::Binary(v) => Value::Binary(v.into()),
239            &RefValue::String(v) => Value::String(v.into()), // XXX
240            &RefValue::Array(ref v) => Value::Array(v.iter().map(|v| v.to_owned()).collect()),
241            &RefValue::Map(ref v) => Value::Map(
242                v.iter()
243                    .map(|&(ref k, ref v)| (k.to_owned(), v.to_owned()))
244                    .collect(),
245            ),
246            &RefValue::Extension(ty, buf) => Value::Extension(ty, buf.into()),
247            &RefValue::Timestamp(sec, nsec) => Value::Timestamp(sec, nsec),
248        }
249    }
250
251    pub fn to_nil(&self) -> Option<Nil> {
252        match self {
253            RefValue::Nil => Some(Nil),
254            _ => None,
255        }
256    }
257
258    pub fn to_ary(&self) -> Option<&Vec<RefValue>> {
259        match self {
260            RefValue::Array(v) => Some(v),
261            _ => None,
262        }
263    }
264
265    pub fn to_str(&self) -> Option<&str> {
266        match self {
267            RefValue::String(v) => v.as_str(),
268            _ => None,
269        }
270    }
271
272    pub fn to_slice(&self) -> Option<&[u8]> {
273        match self {
274            RefValue::String(v) => Some(v.as_slice()),
275            _ => None,
276        }
277    }
278}