forked from Synphonyte/codee
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostcard.rs
More file actions
48 lines (41 loc) · 1.25 KB
/
postcard.rs
File metadata and controls
48 lines (41 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use crate::{Decoder, Encoder};
/// A codec that relies on `postcard` to encode data.
///
/// Postcard is a `#![no_std]` focused serializer and deserializer for Serde,
/// designed for embedded and constrained environments.
///
/// This is only available with the **`postcard` feature** enabled.
pub struct PostcardCodec;
impl<T: serde::Serialize> Encoder<T> for PostcardCodec {
type Error = postcard::Error;
type Encoded = Vec<u8>;
fn encode(val: &T) -> Result<Self::Encoded, Self::Error> {
postcard::to_allocvec(val)
}
}
impl<T: serde::de::DeserializeOwned> Decoder<T> for PostcardCodec {
type Error = postcard::Error;
type Encoded = [u8];
fn decode(val: &Self::Encoded) -> Result<T, Self::Error> {
postcard::from_bytes(val)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_postcard_codec() {
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
struct Test {
s: String,
i: i32,
}
let t = Test {
s: String::from("party time 🎉"),
i: 42,
};
let enc = PostcardCodec::encode(&t).unwrap();
let dec: Test = PostcardCodec::decode(&enc).unwrap();
assert_eq!(dec, t);
}
}