nson/
value.rs

1use std::fmt;
2use std::{f64, i64};
3use std::convert::Into;
4use std::ops::{DerefMut, Deref};
5
6use hex::{ToHex, FromHex};
7
8use crate::message::Message;
9use crate::array::Array;
10use crate::spec::ElementType;
11use crate::message_id::MessageId;
12use crate::msg;
13
14#[derive(Clone, PartialEq)]
15pub enum Value {
16    F32(f32),
17    F64(f64),
18    I32(i32),
19    I64(i64),
20    U32(u32),
21    U64(u64),
22    String(String),
23    Array(Array),
24    Message(Message),
25    Bool(bool),
26    Null,
27    Binary(Binary),
28    TimeStamp(TimeStamp),
29    MessageId(MessageId)
30}
31
32impl Eq for Value {}
33
34impl fmt::Debug for Value {
35    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
36        match self {
37            Value::F32(f) => write!(fmt, "F32({:?})", f),
38            Value::F64(f) => write!(fmt, "F64({:?})", f),
39            Value::I32(i) => write!(fmt, "I32({:?})", i),
40            Value::I64(i) => write!(fmt, "I64({:?})", i),
41            Value::U32(u) => write!(fmt, "U32({:?})", u),
42            Value::U64(u) => write!(fmt, "U64({:?})", u),
43            Value::String(ref s) => write!(fmt, "String({:?})", s),
44            Value::Array(ref vec) => write!(fmt, "Array({:?})", vec),
45            Value::Message(ref o) => write!(fmt, "{:?}", o),
46            Value::Bool(b) => write!(fmt, "Bool({:?})", b),
47            Value::Null => write!(fmt, "Null"),
48            Value::Binary(ref vec) => write!(fmt, "Binary(0x{})", vec.0.encode_hex::<String>()),
49            Value::TimeStamp(t) => {
50                write!(fmt, "TimeStamp({})", t.0)
51            },
52            Value::MessageId(ref id) => write!(fmt, "MessageId({})", id),
53        }
54    }
55}
56
57impl fmt::Display for Value {
58    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
59        match self {
60            Value::F32(f) => write!(fmt, "F32({})", f),
61            Value::F64(f) => write!(fmt, "F64({})", f),
62            Value::I32(i) => write!(fmt, "I32({})", i),
63            Value::I64(i) => write!(fmt, "I64({})", i),
64            Value::U32(u) => write!(fmt, "U32({})", u),
65            Value::U64(u) => write!(fmt, "U64({})", u),
66            Value::String(ref s) => write!(fmt, "String({})", s),
67            Value::Array(ref vec) => {
68                write!(fmt, "Array[")?;
69
70                let mut first = true;
71                for value in vec.iter() {
72                    if !first {
73                        write!(fmt, ", ")?;
74                    }
75
76                    write!(fmt, "{}", value)?;
77                    first = false;
78                }
79
80                write!(fmt, "]")
81            },
82            Value::Message(ref o) => write!(fmt, "Message({})", o),
83            Value::Bool(b) => write!(fmt, "{}", b),
84            Value::Null => write!(fmt, "null"),
85            Value::Binary(ref vec) => write!(fmt, "Binary(0x{})", vec.0.encode_hex::<String>()),
86            Value::TimeStamp(t) => {
87                write!(fmt, "TimeStamp({})", t.0)
88            },
89            Value::MessageId(ref id) => write!(fmt, "MessageId({})", id),
90        }
91    }
92}
93
94impl From<f32> for Value {
95    fn from(f: f32) -> Value {
96        Value::F32(f)
97    }
98}
99
100impl From<f64> for Value {
101    fn from(f: f64) -> Value {
102        Value::F64(f)
103    }
104}
105
106impl From<i32> for Value {
107    fn from(i: i32) -> Value {
108        Value::I32(i)
109    }
110}
111
112impl From<i64> for Value {
113    fn from(i: i64) -> Value {
114        Value::I64(i)
115    }
116}
117
118impl From<u32> for Value {
119    fn from(u: u32) -> Value {
120        Value::U32(u)
121    }
122}
123
124impl From<u64> for Value {
125    fn from(u: u64) -> Value {
126        Value::U64(u)
127    }
128}
129
130impl<'a> From<&'a str> for Value {
131    fn from(s: &str) -> Value {
132        Value::String(s.to_owned())
133    }
134}
135
136impl From<String> for Value {
137    fn from(s: String) -> Value {
138        Value::String(s)
139    }
140}
141
142impl<'a> From<&'a String> for Value {
143    fn from(s: &'a String) -> Value {
144        Value::String(s.to_owned())
145    }
146}
147
148impl From<Array> for Value {
149    fn from(a: Array) -> Value {
150        Value::Array(a)
151    }
152}
153
154impl From<Message> for Value {
155    fn from(d: Message) -> Value {
156        Value::Message(d)
157    }
158}
159
160impl From<bool> for Value {
161    fn from(b: bool) -> Value {
162        Value::Bool(b)
163    }
164}
165
166impl From<Vec<u8>> for Value {
167    fn from(b: Vec<u8>) -> Value {
168        Value::Binary(Binary(b))
169    }
170}
171
172impl From<[u8; 12]> for Value {
173    fn from(o: [u8; 12]) -> Value {
174        Value::MessageId(MessageId::with_bytes(o))
175    }
176}
177
178impl From<TimeStamp> for Value {
179    fn from(t: TimeStamp) -> Self {
180        Value::TimeStamp(t)
181    }
182}
183
184impl From<MessageId> for Value {
185    fn from(o: MessageId) -> Value {
186        Value::MessageId(o)
187    }
188}
189
190impl<'a> From<&'a MessageId> for Value {
191    fn from(o: &'a MessageId) -> Value {
192        Value::MessageId(o.to_owned())
193    }
194}
195
196impl<T: Into<Value>> From<Option<T>> for Value {
197    fn from(v: Option<T>) -> Value {
198        v.map(|v| v.into()).unwrap_or(Value::Null)
199    }
200}
201
202macro_rules! value_from_impls {
203    ($($T:ty)+) => {
204        $(
205            impl From<Vec<$T>> for Value {
206                fn from(vec: Vec<$T>) -> Value {
207                    Value::Array(vec.into())
208                }
209            }
210        )+
211    }
212}
213
214value_from_impls! {
215    f32 f64 i32 i64 &str String &String Array
216    Message bool Vec<u8> MessageId
217}
218
219impl Value {
220    pub fn element_type(&self) -> ElementType {
221        match self {
222            Value::F32(..) => ElementType::F32,
223            Value::F64(..) => ElementType::F64,
224            Value::I32(..) => ElementType::I32,
225            Value::I64(..) => ElementType::I64,
226            Value::U32(..) => ElementType::U32,
227            Value::U64(..) => ElementType::U64,
228            Value::String(..) => ElementType::String,
229            Value::Array(..) => ElementType::Array,
230            Value::Message(..) => ElementType::Message,
231            Value::Bool(..) => ElementType::Bool,
232            Value::Null => ElementType::Null,
233            Value::Binary(..) => ElementType::Binary,
234            Value::TimeStamp(..) => ElementType::TimeStamp,
235            Value::MessageId(..) => ElementType::MessageId
236        }
237    }
238
239    pub fn bytes_size(&self) -> usize {
240        match self {
241            Value::F32(_) => 4,
242            Value::F64(_) => 8,
243            Value::I32(_) => 4,
244            Value::I64(_) => 8,
245            Value::U32(_) => 4,
246            Value::U64(_) => 8,
247            Value::String(s) => 4 + s.len(),
248            Value::Array(a) => a.bytes_size(),
249            Value::Message(m) => m.bytes_size(),
250            Value::Bool(_) => 1,
251            Value::Null => 0,
252            Value::Binary(b) => 4 + b.0.len(),
253            Value::TimeStamp(_) => 8,
254            Value::MessageId(_) => 12
255        }
256    }
257
258    pub fn as_f32(&self) -> Option<f32> {
259        match self {
260            Value::F32(ref v) => Some(*v),
261            _ => None
262        }
263    }
264
265    pub fn as_f64(&self) -> Option<f64> {
266        match self {
267            Value::F64(ref v) => Some(*v),
268            _ => None
269        }
270    }
271
272    pub fn as_i32(&self) -> Option<i32> {
273        match self {
274            Value::I32(ref v) => Some(*v),
275            _ => None
276        }
277    }
278
279    pub fn as_u32(&self) -> Option<u32> {
280        match self {
281            Value::U32(ref v) => Some(*v),
282            _ => None,
283        }
284    }
285
286    pub fn as_i64(&self) -> Option<i64> {
287        match self {
288            Value::I64(ref v) => Some(*v),
289            _ => None,
290        }
291    }
292
293    pub fn as_u64(&self) -> Option<u64> {
294        match self {
295            Value::U64(ref v) => Some(*v),
296            _ => None,
297        }
298    }
299
300    pub fn as_str(&self) -> Option<&str> {
301        match self {
302            Value::String(ref s) => Some(s),
303            _ => None,
304        }
305    }
306
307    pub fn as_array(&self) -> Option<&Array> {
308        match self {
309            Value::Array(ref v) => Some(v),
310            _ => None,
311        }
312    }
313
314    pub fn as_message(&self) -> Option<&Message> {
315        match self {
316            Value::Message(ref v) => Some(v),
317            _ => None,
318        }
319    }
320
321    pub fn as_bool(&self) -> Option<bool> {
322        match self {
323            Value::Bool(ref v) => Some(*v),
324            _ => None,
325        }
326    }
327
328    pub fn as_message_id(&self) -> Option<&MessageId> {
329        match self {
330            Value::MessageId(ref v) => Some(v),
331            _ => None,
332        }
333    }
334
335    pub fn as_timestamp(&self) -> Option<TimeStamp> {
336        match self {
337            Value::TimeStamp(v) => Some(*v),
338            _ => None
339        }
340    }
341
342    pub fn as_null(&self) -> Option<()> {
343        match self {
344            Value::Null => Some(()),
345            _ => None
346        }
347    }
348
349    pub fn as_binary(&self) -> Option<&Binary> {
350        match self {
351            Value::Binary(b) => Some(&b),
352            _ => None
353        }
354    }
355
356    pub(crate) fn to_extended_message(&self) -> Message {
357        match self {
358            Value::Binary(ref v) => {
359                msg!{
360                    "$bin": v.0.encode_hex::<String>()
361                }
362            }
363            Value::TimeStamp(v) => {
364                msg!{
365                    "$tim": v.0
366                }
367            }
368            Value::MessageId(ref v) => {
369                msg!{
370                    "$mid": v.to_string()
371                }
372            }
373            _ => panic!("Attempted conversion of invalid data type: {}", self)
374        }
375    }
376
377    pub(crate) fn from_extended_message(msg: Message) -> Value {
378        if msg.len() == 1 {
379            let (key, value) = msg.get_index(0).unwrap();
380
381            match key.as_str() {
382                "$tim" => {
383                    if let Value::U64(u) = value {
384                        return Value::TimeStamp((*u).into())
385                    }
386                }
387                "$bin" => {
388                    if let Value::String(hex) = value {
389                        if let Ok(bin) = FromHex::from_hex(hex.as_bytes()) {
390                            return Value::Binary(Binary(bin))
391                        }
392                    }
393                }
394                "$mid" => {
395                    if let Value::String(hex) = value {
396                        if let Ok(message_id) = MessageId::with_string(&hex) {
397                            return message_id.into()
398                        }
399                    }
400                }
401                _ => ()
402            }
403        }
404
405        Value::Message(msg)
406    }
407}
408
409#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
410pub struct TimeStamp(pub u64);
411
412impl From<u64> for TimeStamp {
413    fn from(v: u64) -> Self {
414        TimeStamp(v)
415    }
416}
417
418impl From<TimeStamp> for u64 {
419    fn from(t: TimeStamp) -> Self {
420        t.0
421    }
422}
423
424#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
425pub struct Binary(pub Vec<u8>);
426
427impl From<Vec<u8>> for Binary {
428    fn from(v: Vec<u8>) -> Self {
429        Binary(v)
430    }
431}
432
433impl From<Binary> for Vec<u8> {
434    fn from(b: Binary) -> Self {
435        b.0
436    }
437}
438
439impl Deref for Binary {
440    type Target = Vec<u8>;
441    fn deref(&self) -> &Vec<u8> {
442        &self.0
443    }
444}
445
446impl DerefMut for Binary {
447    fn deref_mut(&mut self) -> &mut Vec<u8> {
448        &mut self.0
449    }
450}