|
| 1 | +/// A codec that relies on `bitcode` to encode data. |
| 2 | +/// |
| 3 | +/// This is only available with the **`bitcode` feature** feature enabled. |
| 4 | +/// |
| 5 | +/// If you want to use `serde` with bitcode, please use the `bitcode_serde` feature instead. |
| 6 | +pub struct BitcodeCodec; |
| 7 | + |
| 8 | +impl<T: bitcode::Encode> crate::Encoder<T> for BitcodeCodec { |
| 9 | + type Error = (); |
| 10 | + type Encoded = Vec<u8>; |
| 11 | + |
| 12 | + fn encode(val: &T) -> Result<Self::Encoded, Self::Error> { |
| 13 | + Ok(bitcode::encode(val)) |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +impl<T: for<'a> bitcode::Decode<'a>> crate::Decoder<T> for BitcodeCodec { |
| 18 | + type Error = bitcode::Error; |
| 19 | + type Encoded = [u8]; |
| 20 | + |
| 21 | + fn decode(val: &Self::Encoded) -> Result<T, Self::Error> { |
| 22 | + bitcode::decode(val) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +#[cfg(test)] |
| 27 | +mod tests { |
| 28 | + use crate::{Decoder, Encoder}; |
| 29 | + |
| 30 | + use super::*; |
| 31 | + |
| 32 | + #[test] |
| 33 | + fn test_bitcode_codec() { |
| 34 | + #[derive(Clone, Debug, PartialEq, bitcode::Encode, bitcode::Decode)] |
| 35 | + struct Test { |
| 36 | + s: String, |
| 37 | + i: i32, |
| 38 | + } |
| 39 | + let t = Test { |
| 40 | + s: String::from("party time 🎉"), |
| 41 | + i: 42, |
| 42 | + }; |
| 43 | + let enc = BitcodeCodec::encode(&t).unwrap(); |
| 44 | + let dec: Test = BitcodeCodec::decode(&enc).unwrap(); |
| 45 | + assert_eq!(dec, t); |
| 46 | + } |
| 47 | + |
| 48 | + #[test] |
| 49 | + fn test_bitcode_codec_complex() { |
| 50 | + use std::collections::BTreeMap; |
| 51 | + use std::collections::HashMap; |
| 52 | + use std::sync::Arc; |
| 53 | + |
| 54 | + #[derive(Debug, PartialEq, bitcode::Encode, bitcode::Decode)] |
| 55 | + struct Test { |
| 56 | + s: String, |
| 57 | + i: i32, |
| 58 | + m: HashMap<String, i32>, |
| 59 | + b: BTreeMap<String, i32>, |
| 60 | + a: Arc<String>, |
| 61 | + } |
| 62 | + let t = Test { |
| 63 | + s: String::from("party time 🎉"), |
| 64 | + i: 42, |
| 65 | + m: HashMap::from([("a".to_string(), 1), ("b".to_string(), 2)]), |
| 66 | + b: BTreeMap::from([("a".to_string(), 1), ("b".to_string(), 2)]), |
| 67 | + a: Arc::new(String::from("party time 🎉")) |
| 68 | + }; |
| 69 | + let enc = BitcodeCodec::encode(&t).unwrap(); |
| 70 | + let dec: Test = BitcodeCodec::decode(&enc).unwrap(); |
| 71 | + assert_eq!(dec, t); |
| 72 | + } |
| 73 | + |
| 74 | + #[test] |
| 75 | + fn test_bitcode_codec_error() { |
| 76 | + #[derive(bitcode::Encode, bitcode::Decode)] |
| 77 | + struct Test; |
| 78 | + let enc = [0]; |
| 79 | + let dec: Result<Test, bitcode::Error> = BitcodeCodec::decode(&enc); |
| 80 | + assert!(dec.is_err()); |
| 81 | + } |
| 82 | +} |
0 commit comments