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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
/*
 * BSD 3-Clause License
 *
 * Copyright (c) 2020, InterlockLedger Network
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
//! This module contains the implementation of the **IL2 ILTags** standard.
//!
//! ## Implicit vs Explicit tags
//!
//! This library contains 2 types of tags, the implicit and the explicit tags.
//!
//! The implicit tags have their value lengths predefined. This allows them
//! to be more compact because they do not not store the size of the values in
//! the tag serialization. Only the standard built-in tags with IDs lower than
//! 16 are defined as such.
//!
//! All tags with ID greater than 15 are considered explicit. Explicit tags
//! encode all fields and have no such limitations.
//!
//! ## Standard vs custom tags
//!
//! The **IL2 ILTags** standard defined 2 classes of tags, the standard tags and
//! custom tags.
//!
//! The standard tags are defined by **IL2 ILTags** and defines most of basic
//! data types that can be used by all applications. The standard tags are
//! reserved by the standard and should not be redefined by applications
//! in order to avoid conflicts with future versions of the standard.
//! All tags with IDs up to 31 are considered reserved.
//!
//! The custom tags can be freely defined by the applications and must have
//! the ID greater than 31.
//!
#[macro_use]
mod macros;

pub mod standard;
pub mod util;

#[cfg(test)]
mod tests;

use crate::ilint::encoded_size;
use crate::io::data::*;
use crate::io::{Reader, Writer};
use ::std::any::Any;
use ::std::collections::HashMap;

/// Maximum tag size that can be handled by this library. It in this version it is set to 512MB.
pub const MAX_TAG_SIZE: u64 = 1024 * 1024 * 512;

/// Definition of the errors from this package.
pub enum ErrorKind {
    /// If an unknown tag is found.
    UnknownTag,
    /// If an unsupported tag is found.
    UnsupportedTag,
    /// If the tag data is corrupted.
    CorruptedData,
    /// If the tag cannot be handled due to memory constraints.
    TagTooLarge,
    /// If an unexpected tag type is found in the data stream.
    UnexpectedTagType,
    /// If the tag cannot be serialized.
    UnableToSerialize,
    /// Wraper to I/O errors.
    IOError(crate::io::ErrorKind),
    /// Wrapper to boxed errors.
    Boxed(Box<dyn ::std::error::Error>),
}

/// A specialized [`std::result::Result`] generated by functions and methods from this package.
pub type Result<T> = ::std::result::Result<T, ErrorKind>;

/// Maximum tag id value for implicit tags.
pub const IMPLICIT_ID_MAX: u64 = 0x0F;

/// Maximum tag id value for reserved tags.
pub const RESERVED_ID_MAX: u64 = 0x1F;

/// Verifies if a given tag id represents an implicit tag.
///
/// Arguments:
///
/// * `id`: The tag id to be verified;
///
/// Returns:
///
/// * true if the tag id is implicit or false otherwise.
///
pub fn is_implicit_tag(id: u64) -> bool {
    id <= IMPLICIT_ID_MAX
}

/// Verifies if a given tag id represents a reserved tag.
///
/// Arguments:
///
/// * `id`: The tag id to be verified;
///
/// Returns:
///
/// * true if the tag id is reserved or false otherwise.
///
pub fn is_reserved_tag(id: u64) -> bool {
    id <= RESERVED_ID_MAX
}

/// This function converts the tag size as u64 into
/// a usize value. It checks if the tag size falls within
/// the maximum size of a tag that this library accepts.
///
/// It can be used to detect potential corruptions in the
/// data stream.
///
/// Arguments:
/// - `size`: The size read from the tag.
///
/// Returns:
/// - Ok(size): The size as u64;
/// - Err(ErrorKind::TagTooLarge): If the tag is too large;
pub fn tag_size_to_usize(size: u64) -> Result<usize> {
    if size > MAX_TAG_SIZE {
        Err(ErrorKind::TagTooLarge)
    } else {
        Ok(size as usize)
    }
}

/// Serializes an u64 as an ILInt value.
///
/// Arguments:
/// - `value`: The value to write;
/// - `writer`: The writer;
///
/// Returns:
/// - Ok(v): The value read;
/// - Err(x): In case of error;
pub fn serialize_ilint(value: u64, writer: &mut dyn Writer) -> Result<()> {
    match write_ilint(value, writer) {
        Ok(()) => Ok(()),
        Err(e) => Err(ErrorKind::IOError(e)),
    }
}

/// Unserializes an ILInt value.
///
/// Arguments:
/// - `reader`: The reader;
///
/// Returns:
/// - Ok(v): The value read;
/// - Err(x): In case of error;
pub fn deserialize_ilint(reader: &mut dyn Reader) -> Result<u64> {
    match read_ilint(reader) {
        Ok(v) => Ok(v),
        Err(e) => Err(ErrorKind::IOError(e)),
    }
}

/// Serializes a byte array.
///
/// Arguments:
/// - `bytes`: The bytes to be written;
/// - `writer`: The writer;
///
/// Returns:
/// - Ok(()): On success;
/// - Err(e): In case of error;
pub fn serialize_bytes(bytes: &[u8], writer: &mut dyn Writer) -> Result<()> {
    match writer.write_all(bytes) {
        Ok(()) => Ok(()),
        Err(e) => Err(ErrorKind::IOError(e)),
    }
}

/// Deserializes a byte array of a given size.
///
/// Arguments:
/// - `reader`: The reader;
/// - `size`: The number of bytes to read;
///
/// Returns:
/// - Ok(v): A vector with the bytes read;
/// - Err(e): In case of error;
pub fn deserialize_bytes(size: usize, reader: &mut dyn Reader) -> Result<Vec<u8>> {
    let mut ret: Vec<u8> = vec![0; size];
    match reader.read_all(ret.as_mut_slice()) {
        Ok(()) => Ok(ret),
        Err(e) => Err(ErrorKind::IOError(e)),
    }
}

/// Deserializes a byte array of a given size into a vector.
///
/// Arguments:
/// - `reader`: The reader;
/// - `size`: The number of bytes to read;
/// - `vec`: The vector that will receive the data;
///
/// Returns:
/// - Ok(v): A vector with the bytes read;
/// - Err(e): In case of error;
pub fn deserialize_bytes_into_vec(
    size: usize,
    reader: &mut dyn Reader,
    vec: &mut Vec<u8>,
) -> Result<()> {
    vec.resize(size, 0);
    match reader.read_all(vec.as_mut_slice()) {
        Ok(()) => Ok(()),
        Err(e) => Err(ErrorKind::IOError(e)),
    }
}

//=============================================================================
// ILTag
//-----------------------------------------------------------------------------
/// This trait must be implemented by all **ILTags** on this library. It defines
/// the basic methods for tag identification, serialization and deserialization
/// of values.
///
/// The actual manipulation of the information inside the tags must be handled
/// directly by each tag implementation by the use of [`std::any::Any`] trait.
pub trait ILTag: Any + Send {
    /// Returns the ID of the tag.
    fn id(&self) -> u64;

    /// Verifies if this tag is implicity.
    fn is_implicity(&self) -> bool {
        is_implicit_tag(self.id())
    }

    /// Verifies if this tag is reserved.
    fn is_reserved(&self) -> bool {
        is_reserved_tag(self.id())
    }

    /// Retuns the size of the serialized value in bytes.
    fn value_size(&self) -> u64;

    /// Returns the total size of the tag in bytes.
    fn size(&self) -> u64 {
        let mut size: u64 = encoded_size(self.id()) as u64;
        if !self.is_implicity() {
            size += encoded_size(self.value_size()) as u64;
        }
        size + self.value_size()
    }

    /// Serializes the payload of this tag.
    ///
    /// Arguments:
    ///
    /// * `writer`: The writer that will receive the encoded value;
    ///
    /// Returns:
    ///
    /// * `Ok()`: On success.
    /// * `Err(())`: If the buffer is too small to hold the encoded value.
    ///
    fn serialize_value(&self, writer: &mut dyn Writer) -> Result<()>;

    /// Serializes this tag.
    ///
    /// Arguments:
    ///
    /// * `writer`: The writer that will receive the encoded value;
    ///
    /// Returns:
    ///
    /// * `Ok()`: On success.
    /// * `Err(())`: If the buffer is too small to hold the encoded value.
    ///
    fn serialize(&self, writer: &mut dyn Writer) -> Result<()> {
        serialize_ilint(self.id(), writer)?;
        if !self.is_implicity() {
            serialize_ilint(self.value_size(), writer)?;
        }
        self.serialize_value(writer)
    }

    /// Deserializes the value.
    ///
    /// Arguments:
    ///
    /// * `factory`: The current tag factory. It is used to create new inner tags if necessary.
    /// * `value_size`: Size of the value in bytes;
    /// * `reader`: The tag reader to be used;
    ///
    /// Returns:
    ///
    /// * `Ok()`: On success.
    /// * `Err(())`: In case of error.
    fn deserialize_value(
        &mut self,
        factory: &dyn ILTagFactory,
        value_size: usize,
        reader: &mut dyn Reader,
    ) -> Result<()>;

    /// Returns a reference as Any.
    fn as_any(&self) -> &dyn Any;

    /// Returns a mutable reference as Any.
    fn as_mut_any(&mut self) -> &mut dyn Any;
}

/// Downcasts a [`ILTag`] to its concrete type.
///
/// Arguments:
/// * `tag`: The tag to be downcast;
///
/// Returns:
/// An option with a reference to the concrete type or None if
/// the conversion is not possible.
#[inline]
pub fn tag_downcast_ref<T: ILTag + Any>(tag: &dyn ILTag) -> Option<&T> {
    tag.as_any().downcast_ref::<T>()
}

/// Downcasts a [`ILTag`] to its concrete type as a mutable reference.
///
/// Arguments:
/// * `tag`: The tag to be downcast;
///
/// Returns:
/// An option with a reference to the concrete type or None if
/// the conversion is not possible.
#[inline]
pub fn tag_downcast_mut<T: ILTag + Any>(tag: &mut dyn ILTag) -> Option<&mut T> {
    tag.as_mut_any().downcast_mut::<T>()
}

/// Downcasts a [`ILTag`] to its concrete type. It fails if the tag id or
/// the concrete type does not match.
///
/// Arguments:
/// - `tag_id`: The expected tag id;
/// - `tag`: The tag to be downcast;
///
/// Returns:
/// - Ok(v): ;
/// - Err(ErrorKind::UnexpectedTagType): If the conversion is not possible;
#[inline]
pub fn tag_id_downcast_ref<T: ILTag + Any>(tag_id: u64, tag: &dyn ILTag) -> Result<&T> {
    if tag.id() != tag_id {
        Err(ErrorKind::UnexpectedTagType)
    } else {
        match tag_downcast_ref::<T>(tag) {
            Some(v) => Ok(v),
            None => Err(ErrorKind::UnexpectedTagType),
        }
    }
}

/// Downcasts a [`ILTag`] to its concrete type as a mutable reference. It fails
/// if the tag id or the concrete type does not match.
///
/// Arguments:
/// - `tag_id`: The expected tag id;
/// * `tag`: The tag to be downcast;
///
/// Returns:
/// An option with a reference to the concrete type or None if
/// the conversion is not possible.
#[inline]
pub fn tag_id_downcast_mut<T: ILTag + Any>(tag_id: u64, tag: &mut dyn ILTag) -> Result<&mut T> {
    if tag.id() != tag_id {
        Err(ErrorKind::UnexpectedTagType)
    } else {
        match tag_downcast_mut::<T>(tag) {
            Some(v) => Ok(v),
            None => Err(ErrorKind::UnexpectedTagType),
        }
    }
}

//=============================================================================
// DefaultWithId
//-----------------------------------------------------------------------------
/// This trait defines a variant of the [`std::default::Default`] trait that
/// takes an id as a parameter.
///
/// Most of the tags implemented by this library do implement this trait but it
/// is not mandatory.
pub trait DefaultWithId {
    /// Creates a default tag with.
    ///
    /// Arguments:
    ///
    /// * `id`: The id.
    fn default_with_id(id: u64) -> Self;
}

//=============================================================================
// ILTagFactory
//-----------------------------------------------------------------------------
/// This trait must be implemented by all tag factories. Factories are used
/// to deserialize tags into the most appropriate concreate implemetation that
/// will handle a given tag id.
pub trait ILTagFactory: Send {
    /// Creates an empty tag for the given id.
    ///
    /// Arguments:
    /// - `tag_id`: The tag id;
    ///
    /// Returns:
    /// - Some(t): A boxed tag that implements the given tag id;
    /// - None: If the tag id does not have a suitable implementation;
    fn create_tag(&self, tag_id: u64) -> Option<Box<dyn ILTag>>;

    /// Deserializes a tag from a reader.
    ///
    /// Arguments:
    /// - `reader`: The reader that contains the tag;
    ///
    /// Retunrs:
    /// The boxed deserialized tag or an error in case of failure.
    fn deserialize(&self, reader: &mut dyn Reader) -> Result<Box<dyn ILTag>>;
}

//=============================================================================
// ILTagCreator
//-----------------------------------------------------------------------------
/// This trait must be implemented by all tag creators. A tag creator is used
///  by [`ILTagCreatorEngine`] to create new tag instances.
pub trait ILTagCreator: Send {
    /// Creates a new boxed instance of the the class.
    ///
    /// Arguments:
    ///
    /// * `tag_id`: The tag id.
    ///
    /// Returns:
    /// * `Box<dyn ILTag>`: The new empty boxed tag.
    fn create_empty_tag(&self, tag_id: u64) -> Box<dyn ILTag>;
}

//=============================================================================
// ILDefaultTagCreator
//-----------------------------------------------------------------------------
/// This template struct is used to implement the `ILTagCreator` trait for all
/// `ILTags` that also implement `Default`.
pub struct ILDefaultTagCreator<T: ILTag + Default> {
    phantom: ::std::marker::PhantomData<T>,
}

impl<T: ILTag + Default> ILDefaultTagCreator<T> {
    /// Creates a new instance of this struct.
    pub fn new() -> Self {
        Self {
            phantom: ::std::marker::PhantomData,
        }
    }
}

impl<T: ILTag + Default> Default for ILDefaultTagCreator<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: ILTag + Default> ILTagCreator for ILDefaultTagCreator<T> {
    fn create_empty_tag(&self, tag_id: u64) -> Box<dyn ILTag> {
        let ret = Box::new(T::default());
        assert!(ret.id() == tag_id); // Just to detect potential errors
        ret
    }
}

//=============================================================================
// ILDefaultWithIdTagCreator
//-----------------------------------------------------------------------------
/// This template struct is used to implement the `ILTagCreator` trait for all
/// `ILTags` that also implement `DefaultWithId`.
pub struct ILDefaultWithIdTagCreator<T: ILTag + DefaultWithId> {
    phantom: ::std::marker::PhantomData<T>,
}

impl<T: ILTag + DefaultWithId> ILDefaultWithIdTagCreator<T> {
    /// Creates a new instance of this struct.
    pub fn new() -> Self {
        Self {
            phantom: ::std::marker::PhantomData,
        }
    }
}

impl<T: ILTag + DefaultWithId> Default for ILDefaultWithIdTagCreator<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: ILTag + DefaultWithId> ILTagCreator for ILDefaultWithIdTagCreator<T> {
    fn create_empty_tag(&self, tag_id: u64) -> Box<dyn ILTag> {
        Box::new(T::default_with_id(tag_id))
    }
}

//=============================================================================
// ILTagCreatorEngine
//-----------------------------------------------------------------------------
/// This struct implements an engine that maps the ILTagCreators
/// to the associated tag ID. It can be used as a component to implement
/// ILTagFactory trait.
pub struct ILTagCreatorEngine {
    creators: HashMap<u64, Box<dyn ILTagCreator>>,
    strict: bool,
}

impl ILTagCreatorEngine {
    /// Creates a new instance of the ILTagCreatorEngine.
    ///
    /// Arguments:
    /// * `strict`: Strict mode. If false, unknown tags will be mapped to RawTag
    /// instances.
    pub fn new(strict: bool) -> ILTagCreatorEngine {
        ILTagCreatorEngine {
            creators: HashMap::new(),
            strict,
        }
    }

    /// Returns the current strict flag.
    pub fn strict(&self) -> bool {
        self.strict
    }

    /// Registers a new ILTagCreator.
    ///
    /// Arguments:
    /// * `tag_id`: The tag id;
    /// * `creator`: The new creator;
    ///
    /// Returns:
    /// * `Some<Box<dyn ILTagCreator>>`: The previously registered creator for the specified id;
    /// * `None`: If the id is not associated with a new creator;
    pub fn register(
        &mut self,
        tag_id: u64,
        creator: Box<dyn ILTagCreator>,
    ) -> Option<Box<dyn ILTagCreator>> {
        self.creators.insert(tag_id, creator)
    }

    /// Deregisters a ILTagCreator.
    ///
    /// Arguments:
    /// * `tag_id`: The tag id;
    ///
    /// Returns:
    /// * `Some<Box<dyn ILTagCreator>>`: The previously registered creator for the specified id;
    /// * `None`: If the id is not associated with a new creator;
    pub fn deregister(&mut self, tag_id: u64) -> Option<Box<dyn ILTagCreator>> {
        self.creators.remove(&tag_id)
    }

    /// Creates a new empty tag for the given id. It uses the registered creators
    /// to perform the operation.
    ///
    /// Arguments:
    /// * `tag_id`: The tag id;
    ///
    /// Returns:
    /// * `Some<Box<dyn ILTag>>`: The new empty tag instance;
    /// * `None`: If the tag id is unknown (only if strict mode is enabled);
    pub fn create_tag(&self, tag_id: u64) -> Option<Box<dyn ILTag>> {
        match self.creators.get(&tag_id) {
            Some(c) => Some(c.create_empty_tag(tag_id)),
            None => {
                if !self.strict && !is_implicit_tag(tag_id) {
                    Some(Box::new(ILRawTag::new(tag_id)))
                } else {
                    None
                }
            }
        }
    }
}

//=============================================================================
// ILRawTag
//-----------------------------------------------------------------------------
/// This struct implements a raw tag. It can be used to store any non
/// explicit tag.
pub struct ILRawTag {
    id: u64,
    value: Vec<u8>,
}

impl ILRawTag {
    /// Creates a new instance of this struct.
    ///
    /// Arguments:
    /// * `id`: The tag id;
    ///
    /// Returns:
    /// * The new instance of RawTag.
    pub fn new(id: u64) -> ILRawTag {
        assert!(!is_implicit_tag(id));
        ILRawTag {
            id,
            value: Vec::new(),
        }
    }

    /// Initializes a new RawTag with a given capacity.
    ///
    /// Arguments:
    /// * `id`: The tag id;
    /// * `capacity`: The expected initial capacity;
    ///
    /// Returns:
    /// * The new instance of RawTag.
    pub fn with_capacity(id: u64, capacity: usize) -> ILRawTag {
        assert!(!is_implicit_tag(id));
        ILRawTag {
            id,
            value: Vec::with_capacity(capacity),
        }
    }

    /// Initializes a new RawTag with an initial value.
    ///
    /// Arguments:
    /// * `id`: The tag id;
    /// * `value`: A byte slice with the initial value;
    ///
    /// Returns:
    /// * The new instance of RawTag.
    pub fn with_value(id: u64, value: &[u8]) -> ILRawTag {
        assert!(!is_implicit_tag(id));
        let mut v: Vec<u8> = Vec::with_capacity(value.len());
        v.extend_from_slice(value);
        ILRawTag { id, value: v }
    }

    /// Returns an immutable reference to the payload.
    pub fn value(&self) -> &Vec<u8> {
        &self.value
    }

    /// Returns a mutable reference to the payload.
    pub fn mut_value(&mut self) -> &mut Vec<u8> {
        &mut self.value
    }
}

impl ILTag for ILRawTag {
    iltag_base_func_impl!();

    fn value_size(&self) -> u64 {
        self.value.len() as u64
    }

    fn serialize_value(&self, writer: &mut dyn Writer) -> Result<()> {
        serialize_bytes(self.value.as_slice(), writer)
    }

    fn deserialize_value(
        &mut self,
        _factory: &dyn ILTagFactory,
        value_size: usize,
        reader: &mut dyn Reader,
    ) -> Result<()> {
        deserialize_bytes_into_vec(value_size, reader, &mut self.value)
    }
}

impl DefaultWithId for ILRawTag {
    fn default_with_id(id: u64) -> Self {
        Self::new(id)
    }
}