26 releases

0.3.2 Aug 31, 2024
0.3.1 Aug 31, 2024
0.2.22 Jun 16, 2024
0.2.19 May 28, 2024
0.1.1 Apr 24, 2024

#2281 in Encoding

Download history 390/week @ 2024-08-26 85/week @ 2024-09-02 93/week @ 2024-09-09 74/week @ 2024-09-16 82/week @ 2024-09-23 94/week @ 2024-09-30 31/week @ 2024-10-07 47/week @ 2024-10-14 118/week @ 2024-10-21 213/week @ 2024-10-28 61/week @ 2024-11-04 33/week @ 2024-11-11 39/week @ 2024-11-18 115/week @ 2024-11-25 101/week @ 2024-12-02 102/week @ 2024-12-09

358 downloads per month
Used in 4 crates (via tlb)

Custom license

115KB
3.5K SLoC

Binary TL-B de/serialization

docs.rs crates.io


lib.rs:

Example

Consider the following TL-B schema:

tag$10 query_id:uint64 amount:(VarUInteger 16) = Hello;

Let's first define a struct Hello that holds these parameters:

struct Hello {
    pub query_id: u64,
    pub amount: BigUint,
}

Serialization

To be able to serialize a type to BitWriter, we should implement BitPack on it:

#
impl BitPack for Hello {
    fn pack<W>(&self, mut writer: W) -> Result<(), W::Error>
        where W: BitWriter,
    {
        writer
            // tag$10
            .pack_as::<_, NBits<2>>(0b10)?
            // query_id:uint64
            .pack(self.query_id)?
            // amount:(VarUInteger 16)
            .pack_as::<_, &VarInt<4>>(&self.amount)?;
        Ok(())
    }
}

writer.pack(Hello {
    query_id: 0,
    amount: 1_000u64.into(),
})?;

Deserialization

To be able to deserialize a type from BitReader, we should implement BitUnpack on it:

impl BitUnpack for Hello {
    fn unpack<R>(mut reader: R) -> Result<Self, R::Error>
        where R: BitReader,
    {
        // tag$10
        let tag: u8 = reader.unpack_as::<_, NBits<2>>()?;
        if tag != 0b10 {
            return Err(Error::custom(format!("unknown tag: {tag:#b}")));
        }
        Ok(Self {
            // query_id:uint64
            query_id: reader.unpack()?,
            // amount:(VarUInteger 16)
            amount: reader.unpack_as::<_, VarInt<4>>()?,
        })
    }
}

let hello: Hello = parser.unpack()?;

Dependencies

~2.5MB
~54K SLoC