3 releases
0.1.2 | Feb 18, 2024 |
---|---|
0.1.1 | Feb 6, 2024 |
0.1.0 | Dec 29, 2023 |
#2631 in Parser implementations
41 downloads per month
Used in channels
12KB
217 lines
channels-serdes
This crate exposes the interface used by channels
to serialize and deserialize arbitrary types.
It is simply an abstraction layer for different implementations that might not necessarily rely on serde
.
The crate contains 3 reference implementations that are all usable under channels
and can be enabled with feature flags.
Name | Implemented By | Feature flag |
---|---|---|
Bincode |
bincode |
bincode |
Cbor |
ciborium |
cbor |
Json |
serde_json |
json |
Bincode
is the default implementation used by channels
.
lib.rs
:
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> {
Ok(t.to_be_bytes().to_vec())
}
}
impl Deserializer<i32> for MyI32 {
type Error = I32DeserializeError;
fn deserialize(&mut self, buf: &mut Vec<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 = sd.serialize(&42).unwrap();
assert_eq!(serialized, &[0, 0, 0, 42]);
let deserialized = sd.deserialize(&mut serialized);
assert_eq!(deserialized, Ok(42));
Dependencies
~2–445KB
~10K SLoC