Skip to main content

blaze_pk/
codec.rs

1//! Traits for implementing encoding ([`Encodable`]) and decoding ([`Decodable`])
2//! for different types and [`ValueType`] trait for specifying the Tdf type of a type
3
4use crate::{error::DecodeResult, reader::TdfReader, tag::TdfType, writer::TdfWriter};
5
6/// Trait for something that can be decoded from a TdfReader
7pub trait Decodable: Sized {
8    /// Function for implementing decoding of Self from
9    /// the provided Reader. Will return None if self
10    /// cannot be decoded
11    ///
12    /// `reader` The reader to decode from
13    fn decode(reader: &mut TdfReader) -> DecodeResult<Self>;
14}
15
16/// Trait for something that can be encoded onto a TdfWriter
17pub trait Encodable: Sized {
18    /// Function for implementing encoding of Self to the
19    /// provided vec of bytes
20    ///
21    /// `writer` The output to encode to
22    fn encode(&self, writer: &mut TdfWriter);
23
24    /// Shortcut function for encoding self directly to
25    /// a Vec of bytes
26    fn encode_bytes(&self) -> Vec<u8> {
27        let mut output = TdfWriter::default();
28        self.encode(&mut output);
29        output.into()
30    }
31}
32
33/// Trait for a type that conforms to one of the standard TdfTypes
34/// used on structures that implement Decodable or Encodable to allow
35/// them to be encoded as tag fields
36pub trait ValueType {
37    /// The type of tdf value this is
38    fn value_type() -> TdfType;
39}
40
41/// Macro for generating the ValueType implementation for a type
42#[macro_export]
43macro_rules! value_type {
44    ($for:ty, $type:expr) => {
45        impl $crate::codec::ValueType for $for {
46            fn value_type() -> $crate::tag::TdfType {
47                $type
48            }
49        }
50    };
51}