tvm_cell_serde.rs

Overview

This file provides serialization and deserialization logic for the tvm_types::Cell type using the serde_with crate's traits. It defines a custom format handler, CellFormat, which implements both SerializeAs and DeserializeAs traits to enable converting a Cell instance to and from a binary representation suitable for serialization frameworks supported by serde.

The serialization process converts a Cell into a binary Bag of Cells (BOC) format, while deserialization reconstructs the Cell from the BOC bytes. This allows seamless integration of Cell objects with formats like JSON, CBOR, or others that serde supports, by encoding the cell data as a byte vector.


Detailed Components

CellFormat Struct

pub struct CellFormat;

Implementation of SerializeAs for CellFormat

impl serde_with::SerializeAs<tvm_types::Cell> for CellFormat {
    fn serialize_as<S>(value: &tvm_types::Cell, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let buffer: Vec<u8> = tvm_types::write_boc(value)
            .map_err(|e| <S as serde::Serializer>::Error::custom(format!("{e}, ")))?;
        <Vec<u8> as serde::Serialize>::serialize(&buffer, serializer)
    }
}
let cell: tvm_types::Cell = ...; // some cell instance
let serialized_bytes = serde_with::SerializeAs::<tvm_types::Cell>::serialize_as(&CellFormat, &cell, serializer)?;

Implementation of DeserializeAs for CellFormat

impl<'de> serde_with::DeserializeAs<'de, tvm_types::Cell> for CellFormat {
    fn deserialize_as<D>(deserializer: D) -> Result<tvm_types::Cell, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let buffer: Vec<u8> = <Vec<u8> as serde::Deserialize>::deserialize(deserializer)?;
        let cell = tvm_types::read_single_root_boc(&buffer)
            .map_err(|e| <D as serde::Deserializer>::Error::custom(format!("{e}")))?;
        Ok(cell)
    }
}
let deserialized_cell: tvm_types::Cell = serde_with::DeserializeAs::<tvm_types::Cell>::deserialize_as(&CellFormat, deserializer)?;

Important Implementation Details


Interaction with Other System Components


Visual Diagram

classDiagram
class CellFormat {
+serialize_as()
+deserialize_as()
}
CellFormat ..> tvm_types::Cell : SerializeAs / DeserializeAs
CellFormat --> serde::Serializer : uses
CellFormat --> serde::Deserializer : uses
CellFormat --> Vec~u8~ : intermediate BOC format
tvm_types::Cell --> tvm_types::write_boc : serialization
tvm_types::Cell --> tvm_types::read_single_root_boc : deserialization

This diagram depicts the CellFormat struct implementing serialization and deserialization methods for the tvm_types::Cell type, using BOC binary encoding as an intermediate format. It shows dependencies on serde serializer/deserializer traits and the tvm_types functions for reading and writing BOC.