kekbit_codecs/codecs/
text.rs

1use crate::codecs::DataFormat;
2use crate::codecs::Encodable;
3use std::io::Result;
4use std::io::Write;
5
6const ID: u64 = 3;
7const MEDIA_TYPE: &str = "text/plain";
8
9///Simple unstructured text format. Any applications which just want to exchange plain text may used
10/// (e.g. a chat clients, or an application used to exchang text files between peers).
11pub struct PlainTextDataFormat;
12impl DataFormat for PlainTextDataFormat {
13    ///Returns three, the id of the most simple text encoder
14    #[inline]
15    fn id() -> u64 {
16        ID
17    }
18    #[inline]
19    fn media_type() -> &'static str {
20        MEDIA_TYPE
21    }
22}
23
24impl<T: AsRef<str>> Encodable<PlainTextDataFormat> for T {
25    #[inline]
26    fn encode_to(&self, _format: &PlainTextDataFormat, w: &mut impl Write) -> Result<usize> {
27        w.write(self.as_ref().as_bytes())
28    }
29}
30
31#[cfg(test)]
32mod test {
33    use super::*;
34    use std::io::Cursor;
35
36    #[test]
37    fn check_plain_text_encoder() {
38        let mut vec = Vec::<u8>::new();
39        let mut cursor = Cursor::new(&mut vec);
40        let df = PlainTextDataFormat;
41        let msg = "They are who we thought they are";
42        msg.encode_to(&df, &mut cursor).unwrap();
43        assert_eq!(cursor.position() as usize, msg.len());
44        msg.to_string().encode_to(&df, &mut cursor).unwrap();
45        assert_eq!(cursor.position() as usize, 2 * msg.len());
46    }
47
48    #[test]
49    fn check_data_format() {
50        assert_eq!(PlainTextDataFormat::id(), ID);
51        assert_eq!(PlainTextDataFormat::media_type(), MEDIA_TYPE);
52    }
53}