Files
aho_corasick
ansi_term
atty
backtrace
backtrace_sys
bitflags
blindbid
block_buffer
block_padding
bulletproofs
byte_tools
byteorder
cfg_if
chrono
clap
clear_on_drop
curve25519_dalek
digest
dusk_blindbidproof
dusk_tlv
dusk_uds
env_logger
failure
failure_derive
fake_simd
futures
futures_channel
futures_core
futures_executor
futures_io
futures_macro
futures_sink
futures_task
futures_util
async_await
future
io
lock
sink
stream
task
generic_array
humantime
keccak
lazy_static
libc
log
memchr
merlin
num_cpus
num_integer
num_traits
opaque_debug
packed_simd
pin_utils
proc_macro2
proc_macro_hack
proc_macro_nested
quick_error
quote
rand
rand_chacha
rand_core
rand_hc
rand_isaac
rand_jitter
rand_os
rand_pcg
rand_xorshift
regex
regex_syntax
rustc_demangle
serde
serde_derive
sha2
sha3
slab
strsim
subtle
syn
synstructure
termcolor
textwrap
thread_local
time
typenum
unicode_width
unicode_xid
vec_map
  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
use crate::Error;

use std::io::{self, Read};

use serde::de::{DeserializeSeed, Deserializer, SeqAccess, Visitor};

/// Optionally consumes an implementation of [`Read`], and fetch n payloads in TLV format from it.
///
/// The payloads can be fetched either via [`TlvReader::reader_to_tlv_len`], or via the iterator
pub struct TlvReader<R>
where
    R: io::Read,
{
    reader: R,
}

impl<R> TlvReader<R>
where
    R: io::Read,
{
    /// [`TlvReader`] constructor
    pub fn new(reader: R) -> Self {
        TlvReader { reader }
    }

    /// Consumes self, and return the inner reader
    pub fn into_inner(self) -> R {
        self.reader
    }

    /// Consumes an implementation of [`Read`], and return the amount of bytes that should be read
    /// to fetch the TLV payload.
    ///
    /// The function will effectively read the bytes to fetch the length, so the reader will be
    /// pointing to the begining of the payload after the call.
    pub fn reader_to_tlv_len(reader: R) -> Result<usize, Error> {
        let mut reader = reader;

        // The first byte defines the type
        let mut tlv_type = [0x0u8];
        reader.read_exact(&mut tlv_type[..])?;

        // Since we always use 0xf`x` format, we just need to extract the least significant byte
        //
        // This can be performed by a simple bitwise operation
        let len = (tlv_type[0] & 0x0f) as usize;

        // The TLV length cannot be bigger than a [`u64`]. Since this value is immensely big, there
        // should be no case when we need more bytes than that.
        //
        // Here, the amount of bytes defined by the type mask will be read.
        let mut tlv_len = [0x00u8; 8];
        reader.read_exact(&mut tlv_len[..len])?;
        let tlv_len = u64::from_le_bytes(tlv_len);

        Ok(tlv_len as usize)
    }

    /// From an implementation of [`Read`], fetch the type, length and write the value to the
    /// provided buf.
    pub fn read_slice(reader: R, buf: &mut [u8]) -> Result<usize, Error> {
        let mut reader = reader;

        let tlv_len = TlvReader::reader_to_tlv_len(&mut reader)?;

        // If the provided length is bigger than the buffer, then the provided buffer cannot
        // contain all the bytes. This verification prevents inconsistent data.
        if buf.len() < tlv_len as usize {
            return Err(Error::Io(io::Error::new(
                io::ErrorKind::InvalidInput,
                "The buffer is not big enough",
            )));
        }

        // Grant we take all the bytes informed by the type from the reader
        let mut reader = reader.take(tlv_len as u64);
        reader.read_exact(&mut buf[..tlv_len as usize])?;

        Ok(tlv_len)
    }

    /// Read a list of serializable items from the provided reader
    pub fn read_list<L: From<Vec<u8>>>(&mut self) -> Result<Vec<L>, Error> {
        let buf = self.next().ok_or(Error::Io(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "Not enough bytes to read the list from the TLV format",
        )))??;

        let mut list = vec![];
        for item in TlvReader::new(buf.as_slice()) {
            let item = item?;
            list.push(L::from(item));
        }

        Ok(list)
    }
}

impl<R> From<R> for TlvReader<R>
where
    R: io::Read,
{
    fn from(reader: R) -> Self {
        TlvReader::new(reader)
    }
}

impl<R> Iterator for TlvReader<R>
where
    R: io::Read,
{
    type Item = Result<Vec<u8>, Error>;

    /// Since we are dealing with I/O, the iterator itself is error-prone. Therefore, the item must
    /// be a [`Result`].
    ///
    /// If the function fails to read the TLV type/length, then it will return [`None`].
    ///
    /// If the type/length is successfully read but we have an I/O error, the function will return a
    /// [`Some(Error)`]
    ///
    /// Otherwise, the payload of the TLV will be returned
    fn next(&mut self) -> Option<Self::Item> {
        let tlv_len = match TlvReader::reader_to_tlv_len(&mut self.reader) {
            Ok(l) => l,
            Err(_) => return None,
        };

        let mut v = Vec::with_capacity(tlv_len);

        let reader = &mut self.reader;
        let mut reader = reader.take(tlv_len as u64);
        let bytes = match reader.read_to_end(&mut v).map_err(|e| e.into()) {
            Ok(b) => b,
            Err(e) => return Some(Err(e)),
        };

        if bytes < tlv_len {
            return Some(Err(Error::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "The reader didnt provide enough bytes for the TLV decoding",
            ))));
        }

        Some(Ok(v))
    }
}

impl<'de, R> SeqAccess<'de> for TlvReader<R>
where
    R: io::Read,
{
    type Error = Error;

    fn next_element_seed<T>(&mut self, _seed: T) -> Result<Option<T::Value>, Self::Error>
    where
        T: DeserializeSeed<'de>,
    {
        unimplemented!()
    }
}

impl<'de, R> Deserializer<'de> for &mut TlvReader<R>
where
    R: io::Read,
{
    type Error = Error;

    fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_bool(if buf[0] == 0 { false } else { true })
    }

    fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_i8(i8::from_le_bytes(buf))
    }

    fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8; 2];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_i16(i16::from_le_bytes(buf))
    }

    fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8; 4];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_i32(i32::from_le_bytes(buf))
    }

    fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8; 8];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_i64(i64::from_le_bytes(buf))
    }

    fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8; 1];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_u8(u8::from_le_bytes(buf))
    }

    fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8; 2];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_u16(u16::from_le_bytes(buf))
    }

    fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8; 4];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_u32(u32::from_le_bytes(buf))
    }

    fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8; 8];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_u64(u64::from_le_bytes(buf))
    }

    fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8; 4];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_f32(f32::from_le_bytes(buf))
    }

    fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8; 8];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_f64(f64::from_le_bytes(buf))
    }

    fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let mut buf = [0x00u8; 1];
        TlvReader::read_slice(&mut self.reader, &mut buf)?;
        visitor.visit_char(char::from(buf[0]))
    }

    fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        unsafe {
            self.next()
                .unwrap_or(Err(Error::Io(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "It was not possible to deserialize the text",
                ))))
                .and_then(|bytes| {
                    visitor.visit_str(std::str::from_utf8_unchecked(bytes.as_slice()))
                })
        }
    }

    fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        unsafe {
            self.next()
                .unwrap_or(Err(Error::Io(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "It was not possible to deserialize the text",
                ))))
                .and_then(|bytes| visitor.visit_string(String::from_utf8_unchecked(bytes)))
        }
    }

    fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.next()
            .unwrap_or(Err(Error::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "It was not possible to deserialize the text",
            ))))
            .and_then(|bytes| visitor.visit_bytes(bytes.as_slice()))
    }

    fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.next()
            .unwrap_or(Err(Error::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "It was not possible to deserialize the text",
            ))))
            .and_then(|bytes| visitor.visit_byte_buf(bytes))
    }

    fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        self.next()
            .unwrap_or(Err(Error::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "It was not possible to deserialize the text",
            ))))
            .and_then(|bytes| {
                if !bytes.is_empty() {
                    visitor.visit_byte_buf(bytes)
                } else {
                    visitor.visit_none()
                }
            })
    }

    fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_unit()
    }

    fn deserialize_unit_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_unit()
    }

    fn deserialize_newtype_struct<V>(
        self,
        _name: &'static str,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        visitor.visit_newtype_struct(self)
    }

    fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let buf = self.next().ok_or(Error::Io(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "Not enough bytes to read the list from the TLV format",
        )))??;

        let buf = TlvReader::new(buf.as_slice());

        visitor.visit_seq(buf)
    }

    fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let buf = self.next().ok_or(Error::Io(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "Not enough bytes to read the list from the TLV format",
        )))??;

        let buf = TlvReader::new(buf.as_slice());

        visitor.visit_seq(buf)
    }

    fn deserialize_tuple_struct<V>(
        self,
        _name: &'static str,
        _len: usize,
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let buf = self.next().ok_or(Error::Io(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "Not enough bytes to read the list from the TLV format",
        )))??;

        let buf = TlvReader::new(buf.as_slice());

        visitor.visit_seq(buf)
    }

    fn deserialize_map<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_struct<V>(
        self,
        _name: &'static str,
        _fields: &'static [&'static str],
        visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        let buf = self.next().ok_or(Error::Io(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "Not enough bytes to read the list from the TLV format",
        )))??;

        let buf = TlvReader::new(buf.as_slice());

        visitor.visit_seq(buf)
    }

    fn deserialize_enum<V>(
        self,
        _name: &'static str,
        _variants: &'static [&'static str],
        _visitor: V,
    ) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_identifier<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }

    fn deserialize_ignored_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
    where
        V: Visitor<'de>,
    {
        unimplemented!()
    }
}

#[cfg(test)]
mod tests {
    use crate::*;
    use serde::de::Deserialize;
    use serde::ser::Serialize;
    use std::io::{Cursor, Write};
    use std::iter;

    #[test]
    fn tlv_reader_vec() {
        let buf: Vec<u8> = iter::repeat(())
            .take(65536)
            .enumerate()
            .map(|(i, _)| i as u8)
            .collect();

        let buf_other: Vec<u8> = iter::repeat(())
            .take(10)
            .enumerate()
            .map(|(i, _)| i as u8)
            .collect();

        let cursor = Cursor::new(Vec::<u8>::new());
        let mut tlv_writer = TlvWriter::new(cursor);

        tlv_writer.write(buf.as_slice()).unwrap();
        tlv_writer.write(buf_other.as_slice()).unwrap();

        let mut cursor = tlv_writer.into_inner();
        cursor.set_position(0);

        let mut tlv_reader = TlvReader::new(cursor);

        let fetch_vec = tlv_reader.next().unwrap().unwrap();
        assert_eq!(buf, fetch_vec);

        let fetch_vec = tlv_reader.next().unwrap().unwrap();
        assert_eq!(buf_other, fetch_vec);
    }

    #[test]
    fn tlv_reader_deserialize_u64() {
        let cursor = Cursor::new(Vec::<u8>::new());

        let input = 2533u64;

        let mut tlv_writer = TlvWriter::new(cursor);
        input.serialize(&mut tlv_writer).unwrap();

        let mut cursor = tlv_writer.into_inner();
        cursor.set_position(0);

        let mut tlv_reader = TlvReader::new(cursor);
        let output = Deserialize::deserialize(&mut tlv_reader).unwrap();

        assert_eq!(input, output);
    }

    #[test]
    fn tlv_reader_list() {
        let cursor = Cursor::new(Vec::<u8>::new());

        let input = vec![2558usize, 21, 37, 2009];
        let mut tlv_writer = TlvWriter::new(cursor);

        let list = input
            .iter()
            .map(|i| i.to_le_bytes())
            .collect::<Vec<[u8; 8]>>();
        tlv_writer.write_list(list.as_slice()).unwrap();

        let mut cursor = tlv_writer.into_inner();
        cursor.set_position(0);

        let mut tlv_reader = TlvReader::new(cursor);
        let output: Vec<usize> = tlv_reader
            .read_list::<Vec<u8>>()
            .unwrap()
            .iter()
            .map(|i| {
                let mut n = [0x00u8; 8];
                n.copy_from_slice(i.as_slice());
                usize::from_le_bytes(n)
            })
            .collect();

        assert_eq!(input, output);
    }
}