1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
use std::fmt;
use std::{f64, i64};
use std::convert::Into;
use std::ops::{DerefMut, Deref};

use crate::message::Message;
use crate::array::Array;
use crate::spec::ElementType;
use crate::util::hex::{ToHex, FromHex};
use crate::message_id::MessageId;
use crate::msg;

#[derive(Clone, PartialEq)]
pub enum Value {
    F32(f32),
    F64(f64),
    I32(i32),
    I64(i64),
    U32(u32),
    U64(u64),
    String(String),
    Array(Array),
    Message(Message),
    Bool(bool),
    Null,
    Binary(Binary),
    TimeStamp(TimeStamp),
    MessageId(MessageId)
}

impl Eq for Value {}

impl fmt::Debug for Value {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Value::F32(f) => write!(fmt, "F32({:?})", f),
            Value::F64(f) => write!(fmt, "F64({:?})", f),
            Value::I32(i) => write!(fmt, "I32({:?})", i),
            Value::I64(i) => write!(fmt, "I64({:?})", i),
            Value::U32(u) => write!(fmt, "U32({:?})", u),
            Value::U64(u) => write!(fmt, "U64({:?})", u),
            Value::String(ref s) => write!(fmt, "String({:?})", s),
            Value::Array(ref vec) => write!(fmt, "Array({:?})", vec),
            Value::Message(ref o) => write!(fmt, "{:?}", o),
            Value::Bool(b) => write!(fmt, "Bool({:?})", b),
            Value::Null => write!(fmt, "Null"),
            Value::Binary(ref vec) => write!(fmt, "Binary(0x{})", vec.0.to_hex()),
            Value::TimeStamp(t) => {
                write!(fmt, "TimeStamp({})", t.0)
            },
            Value::MessageId(ref id) => write!(fmt, "MessageId({})", id),
        }
    }
}

impl fmt::Display for Value {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Value::F32(f) => write!(fmt, "{}", f),
            Value::F64(f) => write!(fmt, "{}", f),
            Value::I32(i) => write!(fmt, "{}", i),
            Value::I64(i) => write!(fmt, "{}", i),
            Value::U32(u) => write!(fmt, "{}", u),
            Value::U64(u) => write!(fmt, "{}", u),
            Value::String(ref s) => write!(fmt, "\"{}\"", s),
            Value::Array(ref vec) => {
                write!(fmt, "[")?;

                let mut first = true;
                for value in vec.iter() {
                    if !first {
                        write!(fmt, ", ")?;
                    }

                    write!(fmt, "{}", value)?;
                    first = false;
                }

                write!(fmt, "]")
            },
            Value::Message(ref o) => write!(fmt, "{}", o),
            Value::Bool(b) => write!(fmt, "{}", b),
            Value::Null => write!(fmt, "null"),
            Value::Binary(ref vec) => write!(fmt, "Binary(0x{})", vec.0.to_hex()),
            Value::TimeStamp(t) => {
                write!(fmt, "TimeStamp({})", t.0)
            },
            Value::MessageId(ref id) => write!(fmt, "MessageId({})", id),
        }
    }
}

impl From<f32> for Value {
    fn from(f: f32) -> Value {
        Value::F32(f)
    }
}

impl From<f64> for Value {
    fn from(f: f64) -> Value {
        Value::F64(f)
    }
}

impl From<i32> for Value {
    fn from(i: i32) -> Value {
        Value::I32(i)
    }
}

impl From<i64> for Value {
    fn from(i: i64) -> Value {
        Value::I64(i)
    }
}

impl From<u32> for Value {
    fn from(u: u32) -> Value {
        Value::U32(u)
    }
}

impl From<u64> for Value {
    fn from(u: u64) -> Value {
        Value::U64(u)
    }
}

impl<'a> From<&'a str> for Value {
    fn from(s: &str) -> Value {
        Value::String(s.to_owned())
    }
}

impl From<String> for Value {
    fn from(s: String) -> Value {
        Value::String(s)
    }
}

impl<'a> From<&'a String> for Value {
    fn from(s: &'a String) -> Value {
        Value::String(s.to_owned())
    }
}

impl From<Array> for Value {
    fn from(a: Array) -> Value {
        Value::Array(a)
    }
}

impl From<Message> for Value {
    fn from(d: Message) -> Value {
        Value::Message(d)
    }
}

impl From<bool> for Value {
    fn from(b: bool) -> Value {
        Value::Bool(b)
    }
}

impl From<Vec<u8>> for Value {
    fn from(b: Vec<u8>) -> Value {
        Value::Binary(Binary(b))
    }
}

impl From<[u8; 16]> for Value {
    fn from(o: [u8; 16]) -> Value {
        Value::MessageId(MessageId::with_bytes(o))
    }
}

impl From<TimeStamp> for Value {
    fn from(t: TimeStamp) -> Self {
        Value::TimeStamp(t)
    }
}

impl From<MessageId> for Value {
    fn from(o: MessageId) -> Value {
        Value::MessageId(o)
    }
}

impl<'a> From<&'a MessageId> for Value {
    fn from(o: &'a MessageId) -> Value {
        Value::MessageId(o.to_owned())
    }
}

impl<T: Into<Value>> From<Option<T>> for Value {
    fn from(v: Option<T>) -> Value {
        v.map(|v| v.into()).unwrap_or(Value::Null)
    }
}

macro_rules! value_from_impls {
    ($($T:ty)+) => {
        $(
            impl From<Vec<$T>> for Value {
                fn from(vec: Vec<$T>) -> Value {
                    Value::Array(vec.into())
                }
            }
        )+
    }
}

value_from_impls! {
    f32 f64 i32 i64 &str String &String Array
    Message bool Vec<u8> MessageId
}

impl Value {
    pub fn element_type(&self) -> ElementType {
        match self {
            Value::F32(..) => ElementType::F32,
            Value::F64(..) => ElementType::F64,
            Value::I32(..) => ElementType::I32,
            Value::I64(..) => ElementType::I64,
            Value::U32(..) => ElementType::U32,
            Value::U64(..) => ElementType::U64,
            Value::String(..) => ElementType::String,
            Value::Array(..) => ElementType::Array,
            Value::Message(..) => ElementType::Message,
            Value::Bool(..) => ElementType::Bool,
            Value::Null => ElementType::Null,
            Value::Binary(..) => ElementType::Binary,
            Value::TimeStamp(..) => ElementType::TimeStamp,
            Value::MessageId(..) => ElementType::MessageId
        }
    }

    pub fn bytes_size(&self) -> usize {
        match self {
            Value::F32(_) => 4,
            Value::F64(_) => 8,
            Value::I32(_) => 4,
            Value::I64(_) => 8,
            Value::U32(_) => 4,
            Value::U64(_) => 8,
            Value::String(s) => 4 + s.len() + 1,
            Value::Array(a) => a.bytes_size(),
            Value::Message(m) => m.bytes_size(),
            Value::Bool(_) => 1,
            Value::Null => 0,
            Value::Binary(b) => 4 + b.0.len(),
            Value::TimeStamp(_) => 8,
            Value::MessageId(_) => 16
        }
    }

    pub fn as_f32(&self) -> Option<f32> {
        match self {
            Value::F32(ref v) => Some(*v),
            _ => None
        }
    }

    pub fn as_f64(&self) -> Option<f64> {
        match self {
            Value::F64(ref v) => Some(*v),
            _ => None
        }
    }

    pub fn as_i32(&self) -> Option<i32> {
        match self {
            Value::I32(ref v) => Some(*v),
            _ => None
        }
    }

    pub fn as_u32(&self) -> Option<u32> {
        match self {
            Value::U32(ref v) => Some(*v),
            _ => None,
        }
    }

    pub fn as_i64(&self) -> Option<i64> {
        match self {
            Value::I64(ref v) => Some(*v),
            _ => None,
        }
    }

    pub fn as_u64(&self) -> Option<u64> {
        match self {
            Value::U64(ref v) => Some(*v),
            _ => None,
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            Value::String(ref s) => Some(s),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&Array> {
        match self {
            Value::Array(ref v) => Some(v),
            _ => None,
        }
    }

    pub fn as_message(&self) -> Option<&Message> {
        match self {
            Value::Message(ref v) => Some(v),
            _ => None,
        }
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Value::Bool(ref v) => Some(*v),
            _ => None,
        }
    }

    pub fn as_message_id(&self) -> Option<&MessageId> {
        match self {
            Value::MessageId(ref v) => Some(v),
            _ => None,
        }
    }

    pub fn as_timestamp(&self) -> Option<TimeStamp> {
        match self {
            Value::TimeStamp(v) => Some(*v),
            _ => None
        }
    }

    pub fn as_null(&self) -> Option<()> {
        match self {
            Value::Null => Some(()),
            _ => None
        }
    }

    pub fn as_binary(&self) -> Option<&Binary> {
        match self {
            Value::Binary(b) => Some(&b),
            _ => None
        }
    }

    pub fn to_extended_message(&self) -> Message {
        match self {
            Value::Binary(ref v) => {
                msg!{
                    "$bin": v.0.to_hex()
                }
            }
            Value::TimeStamp(v) => {
                msg!{
                    "$tim": v.0
                }
            }
            Value::MessageId(ref v) => {
                msg!{
                    "$mid": v.to_string()
                }
            }
            _ => panic!("Attempted conversion of invalid data type: {}", self)
        }
    }

    pub fn from_extended_message(values: Message) -> Value {
        if values.len() == 1 {
            if let Ok(timestamp) = values.get_i32("$tim") {
                return Value::TimeStamp((timestamp as u64).into())
            } else if let Ok(timestamp) = values.get_u32("$tim") {
                return Value::TimeStamp((timestamp as u64).into())
            } else if let Ok(timestamp) = values.get_i64("$tim") {
                return Value::TimeStamp((timestamp as u64).into())
            } else if let Ok(timestamp) = values.get_u64("$tim") {
                return Value::TimeStamp(timestamp.into())
            } else if let Ok(hex) = values.get_str("$bin") {
                if let Ok(bin) = FromHex::from_hex(hex.as_bytes()) {
                    return Value::Binary(Binary(bin))
                }
            } else if let Ok(hex) = values.get_str("$mid") {
                if let Ok(message_id) = MessageId::with_string(hex) {
                    return message_id.into()
                }
            }
        }

        Value::Message(values)
    }
}

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Copy, Clone)]
pub struct TimeStamp(pub u64);

impl From<u64> for TimeStamp {
    fn from(v: u64) -> Self {
        TimeStamp(v)
    }
}

impl From<TimeStamp> for u64 {
    fn from(t: TimeStamp) -> Self {
        t.0
    }
}

#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub struct Binary(pub Vec<u8>);

impl From<Vec<u8>> for Binary {
    fn from(v: Vec<u8>) -> Self {
        Binary(v)
    }
}

impl From<Binary> for Vec<u8> {
    fn from(b: Binary) -> Self {
        b.0
    }
}

impl Deref for Binary {
    type Target = Vec<u8>;
    fn deref(&self) -> &Vec<u8> {
        &self.0
    }
}

impl DerefMut for Binary {
    fn deref_mut(&mut self) -> &mut Vec<u8> {
        &mut self.0
    }
}