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
use crate::Error;

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

use serde::ser::{
    SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, SerializeTuple,
    SerializeTupleStruct, SerializeTupleVariant,
};
use serde::Serialize;

macro_rules! implemented_ser_trait_unimplemented {
    ($t:ty,$m:ident) => {
        impl<'a, W> $t for &'a mut TlvWriter<W>
        where
            W: io::Write,
        {
            type Ok = ();
            type Error = Error;

            fn $m<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
            where
                T: Serialize,
            {
                let r: &mut TlvWriter<W> = *self;
                value.serialize(r)
            }

            fn end(self) -> Result<Self::Ok, Self::Error> {
                Ok(())
            }
        }
    };
}

macro_rules! implemented_ser_trait_unimplemented_two {
    ($t:ty,$m:ident,$m2:ident) => {
        impl<'a, W> $t for &'a mut TlvWriter<W>
        where
            W: io::Write,
        {
            type Ok = ();
            type Error = Error;

            fn $m<T: ?Sized>(&mut self, _value: &T) -> Result<(), Self::Error>
            where
                T: Serialize,
            {
                unimplemented!()
            }

            fn $m2<T: ?Sized>(&mut self, _value: &T) -> Result<(), Self::Error>
            where
                T: Serialize,
            {
                unimplemented!()
            }

            fn end(self) -> Result<Self::Ok, Self::Error> {
                unimplemented!()
            }
        }
    };
}

macro_rules! implemented_ser_trait_unimplemented_field {
    ($t:ty,$m:ident) => {
        impl<'a, W> $t for &'a mut TlvWriter<W>
        where
            W: io::Write,
        {
            type Ok = ();
            type Error = Error;

            fn $m<T: ?Sized>(&mut self, _key: &'static str, _value: &T) -> Result<(), Self::Error>
            where
                T: Serialize,
            {
                unimplemented!()
            }

            fn end(self) -> Result<Self::Ok, Self::Error> {
                unimplemented!()
            }
        }
    };
}

/// Optionally consumes an implementation of [`io::Write`], and provides an adapter to convert
/// slices of bytes to TLV format, and output the result to the writer.
pub struct TlvWriter<W>
where
    W: io::Write,
{
    writer: W,
}

impl<W> TlvWriter<W>
where
    W: io::Write,
{
    /// [`TlvWriter`] constructor
    pub fn new(writer: W) -> Self {
        TlvWriter { writer }
    }

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

    /// Convert the provided slice of bytes to TLV format, and write the TL to the writer
    pub fn bytes_len_to_writer(writer: W, mut len: usize) -> Result<usize, Error> {
        let mut writer = writer;

        // If the buffer is empty, the type should be 0xf0
        if len == 0 {
            writer.write(&[0xf0])?;
            return Ok(0);
        }

        // The TLV length will be little-endian format
        let buf_len = len.to_le_bytes();

        // The TLV type will be 0xf`x`, where `x` is the amount of bytes that will be used by the
        // length.
        //
        // Therefore, `len_mask` will hold this amount of bytes. The bitwise operators will allow
        // a fast definition for that.
        let mut len_mask = 0x01;
        len >>= 8;
        while len > 0 {
            len_mask <<= 1;
            len >>= 8;
        }

        writer.write(&[0xf0 | len_mask])?;
        Ok(writer.write(&buf_len[..len_mask as usize])?)
    }

    /// Convert the provided slice of bytes to TLV format, output the result to the provided
    /// writer, and return the amount of bytes written.
    pub fn bytes_to_writer(mut writer: W, buf: &[u8]) -> Result<usize, Error> {
        TlvWriter::bytes_len_to_writer(&mut writer, buf.len())?;
        Ok(writer.write(buf)?)
    }

    /// Append the provided usize to the writer in TLV format
    pub fn write_usize(&mut self, n: usize) -> Result<usize, Error> {
        let n = n.to_le_bytes();

        TlvWriter::bytes_to_writer(&mut self.writer, &n[..])
    }

    /// Write a list of serializable items
    pub fn write_list<L: AsRef<[u8]>>(&mut self, list: &[L]) -> Result<usize, Error> {
        let buf: Vec<u8> = vec![];
        let mut writer = TlvWriter::new(buf);

        for item in list {
            writer.write(item.as_ref())?;
        }

        let buf = writer.into_inner();
        Ok(self.write(buf.as_slice())?)
    }
}

impl<W> io::Write for TlvWriter<W>
where
    W: io::Write,
{
    /// The [`io::Write::write`] implementation will internally call the
    /// [`TlvWriter::bytes_to_writer`]. Therefore, the provided buffer will first be converted to
    /// TLV format, and then sent to the inner writer.
    fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
        TlvWriter::bytes_to_writer(&mut self.writer, buf).map_err(|e| e.into())
    }

    /// The [`io::Write::flush`] implementation will just forward the call to the inner writer.
    fn flush(&mut self) -> Result<(), io::Error> {
        self.writer.flush()
    }
}

impl<'a, W> SerializeSeq for &mut TlvWriter<W>
where
    W: io::Write,
{
    type Ok = ();
    type Error = Error;

    fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
    where
        T: Serialize,
    {
        let r: &mut TlvWriter<W> = *self;
        value.serialize(r)
    }

    fn end(self) -> Result<Self::Ok, Self::Error> {
        Ok(())
    }
}

implemented_ser_trait_unimplemented!(SerializeTuple, serialize_element);
implemented_ser_trait_unimplemented!(SerializeTupleStruct, serialize_field);
implemented_ser_trait_unimplemented!(SerializeTupleVariant, serialize_field);
implemented_ser_trait_unimplemented_two!(SerializeMap, serialize_key, serialize_value);
implemented_ser_trait_unimplemented_field!(SerializeStruct, serialize_field);
implemented_ser_trait_unimplemented_field!(SerializeStructVariant, serialize_field);

impl<'a, W> serde::Serializer for &'a mut TlvWriter<W>
where
    W: io::Write,
{
    type Ok = ();
    type Error = Error;
    type SerializeSeq = Self;
    type SerializeTuple = Self;
    type SerializeTupleStruct = Self;
    type SerializeTupleVariant = Self;
    type SerializeMap = Self;
    type SerializeStruct = Self;
    type SerializeStructVariant = Self;

    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&[if v { 0x01u8 } else { 0x00u8 }]).map(|_| ())?)
    }

    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&v.to_le_bytes()[..]).map(|_| ())?)
    }

    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&v.to_le_bytes()[..]).map(|_| ())?)
    }

    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&v.to_le_bytes()[..]).map(|_| ())?)
    }

    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&v.to_le_bytes()[..]).map(|_| ())?)
    }

    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&v.to_le_bytes()[..]).map(|_| ())?)
    }

    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&v.to_le_bytes()[..]).map(|_| ())?)
    }

    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&v.to_le_bytes()[..]).map(|_| ())?)
    }

    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&v.to_le_bytes()[..]).map(|_| ())?)
    }

    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&v.to_le_bytes()[..]).map(|_| ())?)
    }

    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&v.to_le_bytes()[..]).map(|_| ())?)
    }

    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&[v as u8]).map(|_| ())?)
    }

    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(v.as_bytes()).map(|_| ())?)
    }

    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(v).map(|_| ())?)
    }

    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&[]).map(|_| ())?)
    }

    fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&[]).map(|_| ())?)
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&[]).map(|_| ())?)
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
    ) -> Result<Self::Ok, Self::Error> {
        Ok(self.write(&[]).map(|_| ())?)
    }

    fn serialize_newtype_struct<T: ?Sized>(
        self,
        _name: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T: ?Sized>(
        self,
        _name: &'static str,
        variant_index: u32,
        _variant: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: Serialize,
    {
        self.write(&variant_index.to_le_bytes()[..]).map(|_| ())?;
        value.serialize(self)
    }

    fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        let len = len.ok_or(Error::Io(io::Error::new(
            io::ErrorKind::Other,
            "The leading size is mandatory",
        )))?;

        TlvWriter::bytes_len_to_writer(&mut self.writer, len)?;
        Ok(self)
    }

    fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        TlvWriter::bytes_len_to_writer(&mut self.writer, len)?;
        Ok(self)
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        TlvWriter::bytes_len_to_writer(&mut self.writer, len)?;
        Ok(self)
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        TlvWriter::bytes_len_to_writer(&mut self.writer, len)?;
        Ok(self)
    }

    fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        let len = len.ok_or(Error::Io(io::Error::new(
            io::ErrorKind::Other,
            "The leading size is mandatory",
        )))?;

        TlvWriter::bytes_len_to_writer(&mut self.writer, len)?;
        Ok(self)
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        TlvWriter::bytes_len_to_writer(&mut self.writer, len)?;
        Ok(self)
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        TlvWriter::bytes_len_to_writer(&mut self.writer, len)?;
        Ok(self)
    }
}

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

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

        let cursor = Cursor::new(Vec::<u8>::new());
        let mut tlv = TlvWriter::new(cursor);
        tlv.write(buf.as_slice()).unwrap();

        let cursor = tlv.into_inner();
        let result = cursor.into_inner();

        assert_eq!(0xf1u8, result[0]);
        assert_eq!(0x19u8, result[1]);
        assert_eq!(buf.as_slice(), &result[2..]);
    }

    #[test]
    fn tlv_writer_zero() {
        let cursor = Cursor::new(Vec::<u8>::new());
        let mut tlv = TlvWriter::new(cursor);
        tlv.write(&[][..]).unwrap();

        let cursor = tlv.into_inner();
        let result = cursor.into_inner();

        assert_eq!(0xf0u8, result[0]);
    }

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

        let cursor = Cursor::new(Vec::<u8>::new());
        let mut tlv = TlvWriter::new(cursor);
        tlv.write(buf.as_slice()).unwrap();

        let cursor = tlv.into_inner();
        let result = cursor.into_inner();

        assert_eq!(0xf1u8, result[0]);
        assert_eq!(0x01u8, result[1]);
        assert_eq!(buf.as_slice(), &result[2..]);
    }

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

        let cursor = Cursor::new(Vec::<u8>::new());
        let mut tlv = TlvWriter::new(cursor);
        tlv.write(buf.as_slice()).unwrap();

        let cursor = tlv.into_inner();
        let result = cursor.into_inner();

        assert_eq!(0xf4u8, result[0]);
        assert_eq!(&[0x00u8, 0x00, 0x01, 0x00], &result[1..5]);
        assert_eq!(buf.as_slice(), &result[5..]);
    }
}