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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Item values

#![allow(dead_code)]

use crate::alloc_prelude::*;
use crate::datatypes::*;
use crate::{Item, ItemHeader, ItemKey};
use core::convert::TryInto;
use nano_leb128::{SLEB128, ULEB128};

/// The value of an item.
#[derive(Debug, Clone, PartialEq)]
pub enum ItemValue {
    /// A null value.
    Null,

    /// A list containing multiple `Item`s.
    CompositeList(Vec<Item>),

    /// A list containing multiple `Item`s, where the presence of an `ItemKey`
    /// on the objects contained within is guaranteed.
    CompositeDict(Vec<Item>),

    /// A byte array.
    Bytes(Vec<u8>),

    /// A UTF-8 string.
    UTF8(String),

    /// A boolean.
    Boolean(bool),

    /// A signed 64-bit integer.
    Int64(i64),

    /// An unsigned variable-length integer, represented as a `u64`.
    UVarInt(u64),

    /// A signed variable-length integer, represented as an `i64`.
    SVarInt(i64),

    /// A 64-bit floating point number.
    Float64(f64),

    /// A signed UNIX timestamp, represented as an `i64`.
    Stamp64(i64),

    /// Arbitrary data of an unknown type.
    ///
    /// This type's first value is the type number sent on the wire, and the
    /// second value is a byte array of the raw data sent in the message.
    UnknownType(u64, Vec<u8>),
}

impl ItemValue {
    /// Returns the DataType of this value.
    pub fn data_type(&self) -> DataType {
        match self {
            Self::Null => DataType::Null,
            Self::CompositeList(_) => DataType::from(KnownType::CompositeList),
            Self::CompositeDict(_) => DataType::from(KnownType::CompositeDict),
            Self::Bytes(_) => DataType::from(KnownType::Bytes),
            Self::UTF8(_) => DataType::from(KnownType::UTF8),
            Self::Boolean(_) => DataType::from(KnownType::Boolean),
            Self::Int64(_) => DataType::from(KnownType::Int64),
            Self::UVarInt(_) => DataType::from(KnownType::UVarInt),
            Self::SVarInt(_) => DataType::from(KnownType::SVarInt),
            Self::Float64(_) => DataType::from(KnownType::Float64),
            Self::Stamp64(_) => DataType::from(KnownType::Stamp64),
            Self::UnknownType(u, _) => DataType::from(*u),
        }
    }

    /// Encodes this value into it's byte representation.
    ///
    /// If encoding was successful, returns the data type of the encoded
    /// value, and a `Vec<u8>` of the bytes representing the value.
    pub fn encode(&self) -> Result<(DataType, Vec<u8>), crate::Error> {
        let mut out: Vec<u8> = Vec::new();

        match self {
            Self::Null => {}

            Self::CompositeList(items) => {
                // Iterate over items in the list and encode them recursively
                for itm in items {
                    out.extend(itm.encode()?);
                }
            }

            Self::CompositeDict(items) => {
                // Iterate over items in the list and encode them recursively,
                // checking that the items have keys before doing the encode
                // (and bailing if they don't).
                for itm in items {
                    if itm.key == ItemKey::NoKey {
                        return Err(crate::Error::DictItemWithoutKeyError);
                    }

                    out.extend(itm.encode()?);
                }
            }

            Self::Bytes(b) => {
                // Just extend the output vec with the input bytes
                out.extend(b);
            }

            Self::UTF8(s) => {
                // Just extend the output vec with the input string as bytes
                out.extend(s.as_bytes());
            }

            Self::Boolean(b) => {
                // [0x00] for false, [0x01] for true.
                //
                // We can use the compact representation for false, which is
                // an empty data vec, so just push [0x01] if our value is true
                if *b {
                    out.push(0x01);
                }
            }

            Self::Int64(i) => {
                // This should output the full width of an i64 (8 bytes).
                out.extend(&i.to_le_bytes());
            }

            Self::UVarInt(v) => {
                // Unsigned LEB128
                let mut tmp = [0u8; 10];
                let count = ULEB128::from(*v).write_into(&mut tmp)?;
                out.extend(&tmp[0..count]);
            }

            Self::SVarInt(v) => {
                // Signed LEB128
                let mut tmp = [0u8; 10];
                let count = SLEB128::from(*v).write_into(&mut tmp)?;
                out.extend(&tmp[0..count]);
            }

            Self::Float64(f) => {
                // This should output the full width of an f64 (8 bytes).
                out.extend(&f.to_le_bytes());
            }

            Self::Stamp64(i) => {
                // The Stamp64 type is an i64, just interpreted as a UNIX
                // timestamp. This should output the full width of an i64
                // (8 bytes).
                out.extend(&i.to_le_bytes());
            }

            Self::UnknownType(_, b) => {
                // Just extend the output vec with the input bytes
                out.extend(b);
            }
        }

        Ok((self.data_type(), out))
    }

    /// Decode the given data using the type and data length from the given
    /// [`ItemHeader`].
    ///
    /// If decoding succeeds, returns the decoded `ItemValue`, and the number
    /// of bytes consumed by this decode operation.
    pub fn decode(header: &ItemHeader, data: &[u8]) -> Result<(Self, usize), crate::Error> {
        let data_len = header.data_len as usize;
        let mut count: usize = 0;

        // Handle null items
        if header.data_type == DataType::Null {
            return Ok((Self::Null, 0));
        }

        if let DataType::StandardType(ty) = header.data_type {
            match ty {
                KnownType::CompositeList => {
                    if data.len() < data_len {
                        return Err(crate::Error::UnexpectedEof);
                    }

                    let mut items: Vec<Item> = Vec::new();
                    while count < data_len {
                        let (itm, itm_count) = Item::decode(&data[count..])?;
                        count += itm_count;
                        items.push(itm);
                    }

                    return Ok((Self::CompositeList(items), count));
                }

                KnownType::CompositeDict => {
                    if data.len() < data_len {
                        return Err(crate::Error::UnexpectedEof);
                    }

                    let mut items: Vec<Item> = Vec::new();
                    while count < data_len {
                        let (itm, itm_count) = Item::decode(&data[count..])?;
                        items.push(itm);
                        count += itm_count;
                    }

                    return Ok((Self::CompositeDict(items), count));
                }

                KnownType::Bytes => {
                    if data.len() < data_len {
                        return Err(crate::Error::UnexpectedEof);
                    }

                    let b = Vec::from(&data[..data_len]);
                    count += b.len();

                    return Ok((Self::Bytes(b), count));
                }

                KnownType::UTF8 => {
                    if data.len() < data_len {
                        return Err(crate::Error::UnexpectedEof);
                    }

                    let b = Vec::from(&data[..data_len]);
                    count += b.len();

                    let s = String::from_utf8(b)?;
                    return Ok((Self::UTF8(s), count));
                }

                KnownType::Boolean => {
                    if data_len == 0 {
                        return Ok((Self::Boolean(false), 0));
                    }

                    if data.len() < 1 {
                        return Err(crate::Error::UnexpectedEof);
                    }

                    let b = data[0] == 0x01;
                    count += 1;

                    return Ok((Self::Boolean(b), count));
                }

                KnownType::Int64 => {
                    if data_len == 0 {
                        return Ok((Self::Int64(0i64), 0));
                    }

                    if data.len() < 8 {
                        return Err(crate::Error::UnexpectedEof);
                    }

                    let b =
                        i64::from_le_bytes(data[0..8].try_into().expect("failed to get [u8; 8]"));
                    count += 8;

                    return Ok((Self::Int64(b), count));
                }

                KnownType::UVarInt => {
                    let (val, len) = ULEB128::read_from(&data[0..data_len])?;
                    count += len;

                    return Ok((Self::UVarInt(u64::from(val)), count));
                }

                KnownType::SVarInt => {
                    let (val, len) = SLEB128::read_from(&data[0..data_len])?;
                    count += len;

                    return Ok((Self::SVarInt(i64::from(val)), count));
                }

                KnownType::Float64 => {
                    if data_len == 0 {
                        return Ok((Self::Float64(0.0f64), 0));
                    }

                    if data.len() < 8 {
                        return Err(crate::Error::UnexpectedEof);
                    }

                    let b =
                        f64::from_le_bytes(data[0..8].try_into().expect("failed to get [u8; 8]"));
                    count += 8;

                    return Ok((Self::Float64(b), count));
                }

                _ => {
                    return Err(crate::Error::UnimplementedB3TypeError);
                }
            }
        }

        return Err(crate::Error::UnimplementedB3TypeError);
    }

    /// Return the entries contained in this `ItemValue`, if this value is a
    /// `CompositeList` or a `CompositeDict`.
    pub fn get_entries(&self) -> Option<Vec<Item>> {
        match self {
            Self::CompositeList(i) => Some(i.clone()),
            Self::CompositeDict(i) => Some(i.clone()),
            _ => None,
        }
    }

    /// Get the bytes conatined in this `ItemValue`, if this value is a
    /// `Bytes`.
    pub fn get_bytes(&self) -> Option<Vec<u8>> {
        match self {
            Self::Bytes(b) => Some(b.clone()),
            _ => None,
        }
    }

    /// Get the UTF-8 string contained in this `ItemValue`, if this value is
    /// a `UTF8`.
    pub fn get_utf8(&self) -> Option<String> {
        match self {
            Self::UTF8(s) => Some(s.clone()),
            _ => None,
        }
    }

    /// Get the boolean contained in this `ItemValue`, if this value is a
    /// `Boolean`.
    pub fn get_bool(&self) -> Option<bool> {
        match self {
            Self::Boolean(b) => Some(*b),
            _ => None,
        }
    }

    /// Get the `i64` contained in this `ItemValue`, if this value is a
    /// `Int64`, a `SVarInt`, or a `Stamp64`.
    pub fn get_i64(&self) -> Option<i64> {
        match self {
            Self::Int64(i) => Some(*i),
            Self::SVarInt(i) => Some(*i),
            Self::Stamp64(i) => Some(*i),
            _ => None,
        }
    }

    /// Get the `u64` contained in this `ItemValue`, if this value is a
    /// `UVarInt`.
    pub fn get_u64(&self) -> Option<u64> {
        match self {
            Self::UVarInt(i) => Some(*i),
            _ => None,
        }
    }

    /// Get the `f64` contained in this `ItemValue`, if this value is a
    /// `Float64`.
    pub fn get_f64(&self) -> Option<f64> {
        match self {
            Self::Float64(i) => Some(*i),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn header_kt(kt: KnownType, data: &[u8]) -> ItemHeader {
        ItemHeader::new(DataType::from(kt), ItemKey::NoKey, false, data.len() as u64)
    }

    #[test]
    fn encode_composite_list() {
        let list_entry = Item::new(ItemKey::NoKey, ItemValue::Boolean(true));
        let (ty, val) = ItemValue::CompositeList(vec![list_entry.clone(), list_entry.clone()])
            .encode()
            .unwrap();

        assert_eq!(ty, DataType::from(KnownType::CompositeList));
        assert_eq!(val, vec![0b01000101, 0x01, 0x01, 0b01000101, 0x01, 0x01]);
    }

    #[test]
    fn encode_composite_dict_fails_with_missing_key() {
        let dict_entry = Item::new(ItemKey::NoKey, ItemValue::Boolean(true));
        let err = ItemValue::CompositeDict(vec![dict_entry])
            .encode()
            .err()
            .unwrap();

        assert_eq!(err, crate::Error::DictItemWithoutKeyError);
    }

    #[test]
    fn encode_composite_dict() {
        let dict_ent_one = Item::new(ItemKey::IntegerKey(1), ItemValue::Boolean(true));
        let dict_ent_two = Item::new(ItemKey::IntegerKey(2), ItemValue::Boolean(true));
        let (ty, val) = ItemValue::CompositeDict(vec![dict_ent_one, dict_ent_two])
            .encode()
            .unwrap();

        assert_eq!(ty, DataType::from(KnownType::CompositeDict));
        assert_eq!(
            val,
            vec![0b01010101, 0x01, 0x01, 0x01, 0b01010101, 0x02, 0x01, 0x01]
        );
    }

    #[test]
    fn encode_boolean_false() {
        let (ty, val) = ItemValue::Boolean(false).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::Boolean));
        assert_eq!(val.len(), 0);
    }

    #[test]
    fn encode_boolean_true() {
        let (ty, val) = ItemValue::Boolean(true).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::Boolean));
        assert_eq!(val, vec![0x01]);
    }

    #[test]
    fn decode_boolean_false_compact() {
        // Check the compact 'false' representation (empty data)
        let data = vec![];
        let header = header_kt(KnownType::Boolean, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();

        assert_eq!(val, ItemValue::Boolean(false));
        assert_eq!(count, data.len());
    }

    #[test]
    fn decode_boolean_false() {
        // Check the full 'false' representation ([0x00])
        let data = vec![0x00u8];
        let header = header_kt(KnownType::Boolean, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();

        assert_eq!(val, ItemValue::Boolean(false));
        assert_eq!(count, data.len());
    }

    #[test]
    fn decode_boolean_true() {
        let data = vec![0x01u8];
        let header = header_kt(KnownType::Boolean, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::Boolean(true));
        assert_eq!(count, data.len());
    }

    #[test]
    fn encode_bytes() {
        let (ty, val) = ItemValue::Bytes(vec![0xC0, 0xFF, 0xEE]).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::Bytes));
        assert_eq!(val, vec![0xC0, 0xFF, 0xEE]);
    }

    #[test]
    fn decode_bytes_empty() {
        let data = vec![];
        let header = header_kt(KnownType::Bytes, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::Bytes(data));
        assert_eq!(count, 0);
    }

    #[test]
    fn decode_bytes() {
        let data = vec![0xC0, 0xFF, 0xEE];
        let header = header_kt(KnownType::Bytes, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::Bytes(data));
        assert_eq!(count, 3);
    }

    #[test]
    fn encode_utf8() {
        let (ty, val) = ItemValue::UTF8(String::from("AAA")).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::UTF8));
        assert_eq!(val, vec![0x41, 0x41, 0x41]);
    }

    #[test]
    fn decode_utf8_empty() {
        let data = vec![];
        let header = header_kt(KnownType::UTF8, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::UTF8(String::new()));
        assert_eq!(count, 0);
    }

    #[test]
    fn decode_utf8() {
        let data = vec![0x41, 0x41, 0x41];
        let header = header_kt(KnownType::UTF8, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::UTF8(String::from("AAA")));
        assert_eq!(count, 3);
    }

    #[test]
    fn encode_int64() {
        let (ty, val) = ItemValue::Int64(0x1234567890123456i64).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::Int64));
        assert_eq!(val, vec![0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);

        let (ty, val) = ItemValue::Int64(0).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::Int64));
        assert_eq!(val, vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
    }

    #[test]
    fn decode_int64_empty() {
        let data = vec![];
        let header = header_kt(KnownType::Int64, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::Int64(0i64));
        assert_eq!(count, 0);
    }

    #[test]
    fn decode_int64() {
        let data = vec![0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12];
        let header = header_kt(KnownType::Int64, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::Int64(0x1234567890123456i64));
        assert_eq!(count, 8);

        let data = vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
        let header = header_kt(KnownType::Int64, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::Int64(0i64));
        assert_eq!(count, 8);
    }

    #[test]
    fn encode_uvarint() {
        let (ty, val) = ItemValue::UVarInt(127).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::UVarInt));
        assert_eq!(val, vec![0x7F]);

        let (ty, val) = ItemValue::UVarInt(62451).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::UVarInt));
        assert_eq!(val, vec![0xF3, 0xE7, 0x03]);
    }

    #[test]
    fn decode_uvarint() {
        let data = vec![0xF3, 0xE7, 0x03];
        let header = header_kt(KnownType::UVarInt, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::UVarInt(62451));
        assert_eq!(count, 3);

        let data = vec![0x7F];
        let header = header_kt(KnownType::UVarInt, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::UVarInt(127));
        assert_eq!(count, 1);
    }

    #[test]
    fn encode_svarint() {
        let (ty, val) = ItemValue::SVarInt(128).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::SVarInt));
        assert_eq!(val, vec![0x80, 0x01]);

        let (ty, val) = ItemValue::SVarInt(-62541).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::SVarInt));
        assert_eq!(val, vec![0xB3, 0x97, 0x7C]);
    }

    #[test]
    fn decode_svarint() {
        let data = vec![0xB3, 0x97, 0x7C];
        let header = header_kt(KnownType::SVarInt, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::SVarInt(-62541));
        assert_eq!(count, 3);

        let data = vec![0x80, 0x01];
        let header = header_kt(KnownType::SVarInt, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::SVarInt(128));
        assert_eq!(count, 2);
    }

    #[test]
    fn encode_float64() {
        let (ty, val) = ItemValue::Float64(-1.0).encode().unwrap();
        assert_eq!(ty, DataType::from(KnownType::Float64));
        assert_eq!(val, vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xBF]);
    }

    #[test]
    fn decode_float64_empty() {
        let data = vec![];
        let header = header_kt(KnownType::Float64, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::Float64(0.0));
        assert_eq!(count, 0);
    }

    #[test]
    fn decode_float64() {
        let data = vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0xBF];
        let header = header_kt(KnownType::Float64, &data);
        let (val, count) = ItemValue::decode(&header, &data).unwrap();
        assert_eq!(val, ItemValue::Float64(-1.0));
        assert_eq!(count, 8);
    }
}