[][src]Trait tokio_serde::Deserializer

pub trait Deserializer<T> {
    type Error;
    fn deserialize(
        self: Pin<&mut Self>,
        src: &BytesMut
    ) -> Result<T, Self::Error>; }

Deserializes a value from a source buffer

Implementatinos of Deserializer take a byte buffer and return a value by parsing the contents of the buffer according to the implementation's format. The specific byte format, i.e. JSON, protobuf, binpack, is an implementation detail

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

It is expected that the supplied buffer represents a full value and only that value. If after deserializing a value there are remaining bytes the buffer, the deserializer will return an error.

Examples

An integer deserializer that allows the width to be configured.

use tokio_serde::Deserializer;
use bytes::{BytesMut, Buf};
use std::pin::Pin;

struct IntDeserializer {
    width: usize,
}

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

impl Deserializer<u64> for IntDeserializer {
    type Error = Error;

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

        if buf.len() > self.width {
            return Err(Error::Overflow);
        }

        if buf.len() < self.width {
            return Err(Error::Underflow);
        }

        let ret = std::io::Cursor::new(buf).get_uint(self.width);
        Ok(ret)
    }
}

let mut deserializer = IntDeserializer { width: 3 };

let i = Pin::new(&mut deserializer).deserialize(&b"\x00\x00\x05"[..].into()).unwrap();
assert_eq!(i, 5);

Associated Types

type Error

Loading content...

Required methods

fn deserialize(self: Pin<&mut Self>, src: &BytesMut) -> Result<T, Self::Error>

Deserializes a value from buf

The serialization format is specific to the various implementations of Deserializer. If the deserialization is successful, the value is returned. If the deserialization is unsuccessful, an error is returned.

See the trait level docs for more detail.

Loading content...

Implementors

Loading content...