kekbit_codecs/codecs/
raw.rs

1use crate::codecs::DataFormat;
2use crate::codecs::Encodable;
3use std::io::Result;
4use std::io::Write;
5
6const ID: u64 = 2;
7const MEDIA_TYPE: &str = "application/octet-stream";
8
9/// The most basic data format. It just simply writes raw bytes into the channel, without
10/// any regard of the underlying data's structure
11pub struct RawBinDataFormat;
12impl DataFormat for RawBinDataFormat {
13    ///Returns 2, the id of the most basic encoder.
14    #[inline]
15    fn id() -> u64 {
16        ID
17    }
18    ///Returns "application/octet-stream"
19    #[inline]
20    fn media_type() -> &'static str {
21        MEDIA_TYPE
22    }
23}
24
25impl<T: AsRef<[u8]>> Encodable<RawBinDataFormat> for T {
26    #[inline]
27    fn encode_to(&self, _format: &RawBinDataFormat, w: &mut impl Write) -> Result<usize> {
28        w.write(self.as_ref())
29    }
30}
31
32#[cfg(test)]
33mod test {
34    use super::*;
35    use std::io::Cursor;
36    use std::io::Read;
37
38    #[test]
39    fn check_raw_binary_encoder_slice() {
40        let mut vec = Vec::<u8>::new();
41        let mut cursor = Cursor::new(&mut vec);
42        let msg = &[1u8; 10][..];
43        let df = RawBinDataFormat;
44        msg.encode_to(&df, &mut cursor).unwrap();
45        assert_eq!(cursor.position() as usize, msg.len());
46        cursor.set_position(0);
47        let expected = &mut [11u8; 10][..];
48        cursor.read_exact(expected).unwrap();
49        assert_eq!(expected, msg);
50    }
51    #[test]
52    fn check_data_format() {
53        assert_eq!(RawBinDataFormat::id(), ID);
54        assert_eq!(RawBinDataFormat::media_type(), MEDIA_TYPE);
55    }
56}