actix_telepathy/serialization/mod.rs
1#[cfg(test)]
2mod tests;
3use std::fmt;
4
5use serde::{Deserialize, Serialize};
6
7/// Provides template for creating custom serializer
8///
9/// # Example Used in DefaultSerialization
10/// ```
11/// use serde::{Deserialize, Serialize};
12/// use flexbuffers;
13/// use actix_telepathy::{ CustomSerialization, CustomSerializationError };
14///
15/// pub struct DefaultSerialization {}
16///
17/// impl CustomSerialization for DefaultSerialization {
18/// fn serialize<T>(&self, value: &T) -> Result<Vec<u8>, CustomSerializationError>
19/// where
20/// T: ?Sized + Serialize,
21/// {
22/// match flexbuffers::to_vec(value) {
23/// Ok(vec) => Ok(vec),
24/// Err(_) => Err(CustomSerializationError)
25/// }
26/// }
27///
28/// fn deserialize<'a, T>(&self, s: &'a [u8]) -> Result<T, CustomSerializationError>
29/// where
30/// T: ?Sized + Deserialize<'a>,
31/// {
32/// match flexbuffers::from_slice(s) {
33/// Ok(val) => Ok(val),
34/// Err(_) => Err(CustomSerializationError)
35/// }
36/// }
37/// }
38/// ```
39///
40/// # Telling Actix-Telepathy to use Custom Serializer
41/// - create a `telepathy.yaml` file in your crates root
42/// - add your custom struct's name:
43/// ```yaml
44/// custom_serializer: "MySerializer"
45/// ```
46/// - import your custom struct whenever you are using the `RemoteMessage` derive macro.
47pub trait CustomSerialization {
48 fn serialize<T>(&self, value: &T) -> Result<Vec<u8>, CustomSerializationError>
49 where
50 T: ?Sized + Serialize;
51 fn deserialize<'a, T>(&self, s: &'a [u8]) -> Result<T, CustomSerializationError>
52 where
53 T: ?Sized + Deserialize<'a>;
54}
55
56/// Occurs if either the serialization or the deserialization fails for the `CustomSerialization`
57/// trait.
58pub struct CustomSerializationError;
59
60impl fmt::Display for CustomSerializationError {
61 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
62 write!(f, "An error occurred during the custom (de)serialization")
63 }
64}
65
66impl fmt::Debug for CustomSerializationError {
67 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68 write!(f, "{{ file: {}, line: {} }}", file!(), line!())
69 }
70}
71
72/// The default serialization used for remote messages
73///
74/// The default de/serializer is the Rust version of Flatbuffers - Flexbuffers.
75pub struct DefaultSerialization {}
76
77impl CustomSerialization for DefaultSerialization {
78 fn serialize<T>(&self, value: &T) -> Result<Vec<u8>, CustomSerializationError>
79 where
80 T: ?Sized + Serialize,
81 {
82 match flexbuffers::to_vec(value) {
83 Ok(vec) => Ok(vec),
84 Err(_) => Err(CustomSerializationError),
85 }
86 }
87
88 fn deserialize<'a, T>(&self, s: &'a [u8]) -> Result<T, CustomSerializationError>
89 where
90 T: ?Sized + Deserialize<'a>,
91 {
92 match flexbuffers::from_slice(s) {
93 Ok(val) => Ok(val),
94 Err(_) => Err(CustomSerializationError),
95 }
96 }
97}