Crate tlb

Source
Expand description

§TL-B de/serialization

docs.rs crates.io

§Example

Consider the following TL-B schema:

tag$10 query_id:uint64 amount:(VarUInteger 16) payload:(Maybe ^Cell) = Hello;

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

struct Hello {
    pub query_id: u64,
    pub amount: BigUint,
    pub payload: Option<Cell>,
}

§Serialization

To be able to serialize a type to Cell, we should implement CellSerialize on it:

impl CellSerialize for Hello {
    fn store(&self, builder: &mut CellBuilder) -> Result<(), CellBuilderError> {
        builder
            // tag$10
            .pack_as::<_, NBits<2>>(0b10)?
            // query_id:uint64
            .pack(self.query_id)?
            // amount:(VarUInteger 16)
            .pack_as::<_, &VarInt<4>>(&self.amount)?
            // payload:(Maybe ^Cell)
            .store_as::<_, Option<Ref>>(self.payload.as_ref())?;
        Ok(())
    }
}

// serialize value into cell
let hello = Hello {
    query_id: 0,
    amount: 1_000u64.into(),
    payload: None,
};
let cell = hello.to_cell()?;

§Deserialization

To be able to deserialize a type from Cell, we should implement CellDeserialize on it:

impl<'de> CellDeserialize<'de> for Hello {
    fn parse(parser: &mut CellParser<'de>) -> Result<Self, CellParserError<'de>> {
        // tag$10
        let tag: u8 = parser.unpack_as::<_, NBits<2>>()?;
        if tag != 0b10 {
            return Err(Error::custom(format!("unknown tag: {tag:#b}")));
        }
        Ok(Self {
            // query_id:uint64
            query_id: parser.unpack()?,
            // amount:(VarUInteger 16)
            amount: parser.unpack_as::<_, VarInt<4>>()?,
            // payload:(Maybe ^Cell)
            payload: parser.parse_as::<_, Option<Ref<ParseFully>>>()?,
        })
    }
}

let mut parser = cell.parser();
let hello: Hello = parser.parse()?;

Re-exports§

pub use tlbits as bits;
pub use tlbits::either;

Modules§

as
De/serialization helpers for TL-B.
de
Deserialization for TL-B
ser
Serialization for TL-B

Structs§

BagOfCells
Bag Of Cells is used to de/serialize a set of cells from/into bytes.
BagOfCellsArgs
BitPackWithArgs::Args for BagOfCells
Cell
A Cell.
StringError
String-backed Error

Traits§

Context
Adapter for providing context on Result
Error
De/serialization error

Type Aliases§

BoC
Alias to BagOfCells