Crate channels_serdes

Source
Expand description

Utilities to serialize/deserialize types.

§Implementing a serializer/deserializer

use std::convert::Infallible;
use channels_serdes::{Serializer, Deserializer};

struct MyI32;

#[derive(Debug, PartialEq, Eq)]
enum I32DeserializeError {
    NotEnough,
}

impl Serializer<i32> for MyI32 {
    type Error = Infallible; // serializing an i32 cannot fail

    fn serialize(&mut self, t: &i32) -> Result<Vec<u8>, Self::Error> {
        let vec = t.to_be_bytes().to_vec();
        Ok(vec)
    }
}

impl Deserializer<i32> for MyI32 {
    type Error = I32DeserializeError;

    fn deserialize(&mut self, buf: &mut [u8]) -> Result<i32, Self::Error> {
        buf.get(..4)
           .map(|slice| -> [u8; 4] { slice.try_into().unwrap() })
           .map(i32::from_be_bytes)
           .ok_or(I32DeserializeError::NotEnough)
    }
}

let mut sd = MyI32;

let mut serialized: Vec<u8> = sd.serialize(&42).unwrap();
assert_eq!(serialized, [0, 0, 0, 42]);

let deserialized = sd.deserialize(&mut serialized[..]);
assert_eq!(deserialized, Ok(42));

Re-exports§

pub use self::bincode::Bincode;bincode
pub use self::cbor::Cbor;cbor
pub use self::json::Json;json
pub use self::borsh::Borsh;borsh
pub use self::crc::Crc;crc
pub use self::deflate::Deflate;deflate
pub use self::hmac::Hmac;hmac

Modules§

aeadaead
Middleware that encrypts data for transport.
bincodebincode
The bincode serializer which automatically works with all types that implement serde::Serialize and serde::Deserialize.
borshborsh
The borsh serializer which automatically works with all types that implement borsh::BorshSerialize and borsh::BorshDeserialize.
cborcbor
The ciborium serializer which automatically works with all types that implement serde::Serialize and serde::Deserialize.
crccrc
Middleware that verifies data with a CRC checksum.
deflatedeflate
Middleware that compresses data with DEFLATE.
hmachmac
Middleware that verifies data with HMAC.
jsonjson
The serde_json serializer which automatically works with all types that implement serde::Serialize and serde::Deserialize.

Traits§

Deserializer
The Deserializer trait allows converting a byte slice to a type T.
Serializer
The Serializer trait allows converting a type T to safe-to-transport byte sequences.