feat: add support for rmp-serde

This commit is contained in:
Dylan Bowker
2024-05-12 08:18:10 -06:00
committed by Vincent Herlemont
parent 736eb712f4
commit 646673efda
7 changed files with 184 additions and 42 deletions
@@ -1,18 +1,46 @@
use postcard_1_0::{from_bytes, to_allocvec, Error};
use serde::{Deserialize, Serialize};
//! ⚠️ [`Read the docs before using`](crate::postcard_1_0::PostCard#warning).
//! Annotate your type with `native_model::postcard_1_0::PostCard` to
//! use the postcard 1.0 crate for serializing & deserializing.
/// Used to specify the [postcard](https://crates.io/crates/postcard/1.0.8)
/// `1.0` crate for serialization & deserialization.
///
/// # Warning
///
/// `postcard` does not implement all [serde](https://crates.io/crates/serde)
/// features. Errors may be encountered when using this with some types.
///
/// # Basic usage
///
/// Use the [`with`](crate::native_model) attribute on your type to instruct
/// `native_model` to use `PostCard` for serialization & deserialization.
///
/// Example:
///
/// ```rust
/// #[native_model(id = 1, version = 1, with = native_model::postcard_1_0::PostCard)]
/// struct MyStruct {
/// my_string: String
/// }
/// ```
#[doc(cfg(all(feature = "serde", feature = "postcard_1_0")))]
pub struct PostCard;
impl<T: Serialize> super::Encode<T> for PostCard {
type Error = Error;
fn encode(obj: &T) -> Result<Vec<u8>, Error> {
Ok(to_allocvec(obj)?)
#[cfg(all(feature = "serde", feature = "postcard_1_0"))]
impl<T: serde::Serialize> super::Encode<T> for PostCard {
type Error = postcard_1_0::Error;
/// Serializes a type into bytes using the `postcard` `1.0` crate.
fn encode(obj: &T) -> Result<Vec<u8>, Self::Error> {
postcard_1_0::to_allocvec(obj)
}
}
impl<T: for<'a> Deserialize<'a>> super::Decode<T> for PostCard {
type Error = Error;
fn decode(data: Vec<u8>) -> Result<T, Error> {
Ok(from_bytes(&data)?)
#[cfg(all(feature = "serde", feature = "postcard_1_0"))]
impl<T: for<'de> serde::Deserialize<'de>> super::Decode<T> for PostCard {
type Error = postcard_1_0::Error;
/// Deserializes a type from bytes using the `postcard` `1.0` crate.
fn decode(data: Vec<u8>) -> Result<T, Self::Error> {
postcard_1_0::from_bytes(&data)
}
}
}