serde_encrypt/serialize/impls/
cbor_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 CborSerializer<T> {
9 serialized: Vec<u8>,
10 _type: PhantomData<T>,
11}
12
13impl<T> TypedSerialized for CborSerializer<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>
38 where
39 Self: Sized,
40 Self::T: Serialize,
41 {
42 let serialized = serde_cbor::to_vec(v).map_err(|e| {
43 Error::serialization_error(&format!("failed to serialize data by serde_cbor: {:?}", e))
44 })?;
45 Ok(Self::new(serialized))
46 }
47
48 fn deserialize<'de>(&'de self) -> Result<Self::T, Error>
52 where
53 Self::T: Deserialize<'de>,
54 {
55 serde_cbor::from_slice(self.as_slice()).map_err(|e| {
56 Error::deserialization_error(&format!(
57 "error on serde_cbor deserialization after decryption: {:?}",
58 e
59 ))
60 })
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 #[test]
69 fn test_cbor_serializer() -> Result<(), Error> {
70 #[derive(PartialEq, Debug, Serialize, Deserialize)]
71 struct Message(i32);
72
73 let msg = Message(42);
74
75 let serialized_msg = CborSerializer::serialize(&msg)?;
76 let deserialized_msg = serialized_msg.deserialize()?;
77
78 assert_eq!(msg, deserialized_msg);
79
80 Ok(())
81 }
82}