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
use crate::{Decoder, Encoder};

/// A codec that relies on `bincode` adn `serde` to encode data in the bincode format.
///
/// This is only available with the **`bincode_serde` feature** enabled.
pub struct BincodeSerdeCodec;

impl<T: serde::Serialize> Encoder<T> for BincodeSerdeCodec {
    type Error = bincode::Error;
    type Encoded = Vec<u8>;

    fn encode(val: &T) -> Result<Self::Encoded, Self::Error> {
        bincode::serialize(val)
    }
}

impl<T: serde::de::DeserializeOwned> Decoder<T> for BincodeSerdeCodec {
    type Error = bincode::Error;
    type Encoded = [u8];

    fn decode(val: &Self::Encoded) -> Result<T, Self::Error> {
        bincode::deserialize(val)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bincode_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 = BincodeSerdeCodec::encode(&t).unwrap();
        let dec: Test = BincodeSerdeCodec::decode(&enc).unwrap();
        assert_eq!(dec, t);
    }
}