kekbit_codecs/codecs/
text.rs1use 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
9pub struct PlainTextDataFormat;
12impl DataFormat for PlainTextDataFormat {
13 #[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}