serde_encrypt/serialize/impls/
bincode_serializer.rs1use crate::{serialize::TypedSerialized, Error};
2use alloc::{format, vec::Vec};
3use core::marker::PhantomData;
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug)]
8pub struct BincodeSerializer<T> {
9 serialized: Vec<u8>,
10 _type: PhantomData<T>,
11}
12
13impl<T> TypedSerialized for BincodeSerializer<T> {
14 type T = T;
15
16 fn new(serialized: Vec<u8>) -> Self
17 where
18 Self: Sized,
19 {
20 Self {
21 serialized,
22 _type: PhantomData::default(),
23 }
24 }
25
26 fn as_slice(&self) -> &[u8] {
27 &self.serialized
28 }
29
30 fn into_vec(self) -> Vec<u8> {
31 self.serialized
32 }
33
34 fn serialize(v: &Self::T) -> Result<Self, Error>
35 where
36 Self: Sized,
37 Self::T: Serialize,
38 {
39 let serialized = bincode::serialize(v).map_err(|e| {
40 Error::serialization_error(&format!("failed to serialize data by bincode: {:?}", e))
41 })?;
42 Ok(Self::new(serialized))
43 }
44
45 fn deserialize<'de>(&'de self) -> Result<Self::T, Error>
46 where
47 Self::T: Deserialize<'de>,
48 {
49 bincode::deserialize(self.as_slice()).map_err(|e| {
50 Error::deserialization_error(&format!(
51 "error on bincode deserialization after decryption: {:?}",
52 e
53 ))
54 })
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn test_bincode_serializer() -> Result<(), Error> {
64 #[derive(PartialEq, Debug, Serialize, Deserialize)]
65 struct Message(i32);
66
67 let msg = Message(42);
68
69 let serialized_msg = BincodeSerializer::serialize(&msg)?;
70 let deserialized_msg = serialized_msg.deserialize()?;
71
72 assert_eq!(msg, deserialized_msg);
73
74 Ok(())
75 }
76}