Trait massa_serialization::Serializer

source ·
pub trait Serializer<T> {
    // Required method
    fn serialize(
        &self,
        value: &T,
        buffer: &mut Vec<u8>,
    ) -> Result<(), SerializeError>;
}
Expand description

This trait must be implemented to serializes all data in Massa.

Example:

use std::ops::Bound;
use unsigned_varint::nom as varint_nom;
use nom::IResult;
use massa_serialization::Serializer;
use std::ops::RangeBounds;
use unsigned_varint::encode::u64_buffer;
use unsigned_varint::encode::u64;
use massa_serialization::SerializeError;

pub struct U64VarIntSerializer {
    range: (Bound<u64>, Bound<u64>)
}

impl U64VarIntSerializer {
    fn new(min: Bound<u64>, max: Bound<u64>) -> Self {
        Self {
            range: (min, max)
        }
    }
}

impl Serializer<u64> for U64VarIntSerializer {
    fn serialize(&self, value: &u64, buffer: &mut Vec<u8>) -> Result<(), SerializeError> {
        if !self.range.contains(value) {
            return Err(SerializeError::NumberTooBig(format!("Value {:#?} is not in range {:#?}", value, self.range)));
        }
        buffer.extend_from_slice(u64(*value, &mut u64_buffer()));
        Ok(())
    }
}

Required Methods§

source

fn serialize( &self, value: &T, buffer: &mut Vec<u8>, ) -> Result<(), SerializeError>

Serialize a value T into a buffer of u8.

§Parameters
  • value: the value to be serialized.
§Returns

A Result with the serialized data.

Implementors§