[][src]Trait tokio_serde::Serializer

pub trait Serializer<T> {
    type Error;
    fn serialize(self: Pin<&mut Self>, item: &T) -> Result<Bytes, Self::Error>;
}

Serializes a value into a destination buffer

Implementations of Serializer are able to take values of type T and convert them to a byte representation. The specific byte format, i.e. JSON, protobuf, binpack, ... is an implementation detail.

The serialize function takes &mut self, allowing for Serializer instances to be created with runtime configuration settings.

Examples

An integer serializer that allows the width to be configured.

use tokio_serde::Serializer;
use bytes::{Buf, Bytes, BytesMut, BufMut};
use std::pin::Pin;

struct IntSerializer {
    width: usize,
}

#[derive(Debug)]
enum Error {
    Overflow,
}

impl Serializer<u64> for IntSerializer {
    type Error = Error;

    fn serialize(self: Pin<&mut Self>, item: &u64) -> Result<Bytes, Self::Error> {
        assert!(self.width <= 8);

        let max = (1 << (self.width * 8)) - 1;

        if *item > max {
            return Err(Error::Overflow);
        }

        let mut ret = BytesMut::with_capacity(self.width);
        ret.put_uint(*item, self.width);
        Ok(ret.to_bytes())
    }
}

let mut serializer = IntSerializer { width: 3 };

let buf = Pin::new(&mut serializer).serialize(&5).unwrap();
assert_eq!(buf, &b"\x00\x00\x05"[..]);

Associated Types

type Error

Loading content...

Required methods

fn serialize(self: Pin<&mut Self>, item: &T) -> Result<Bytes, Self::Error>

Serializes item into a new buffer

The serialization format is specific to the various implementations of Serializer. If the serialization is successful, a buffer containing the serialized item is returned. If the serialization is unsuccessful, an error is returned.

Implementations of this function should not mutate item via any sort of internal mutability strategy.

See the trait level docs for more detail.

Loading content...

Implementors

Loading content...