Add encode for File message
use nom::IResult;
use std::str::FromStr;
+use std::io::Write;
#[derive(Debug, PartialEq)]
pub struct File {
@@ -34,6 +35,16 @@ impl File {
let body = Vec::from(body);
Ok((input, File { name, body }))
}
+
+ pub fn encode(&self) -> Vec<u8> {
+ let mut output: Vec<u8> = Vec::new();
+ let name = self.name.as_bytes();
+ write!(&mut output, "GU{:03}{:06}", name.len(), self.body.len(),)
+ .expect("Problem encoding lengths");
+ output.extend_from_slice(&name);
+ output.extend_from_slice(&self.body);
+ output
+ }
}
#[cfg(test)]
@@ -52,4 +63,27 @@ mod tests {
File::parse(b"GU008000012test.txtHello World\nextra")
);
}
+
+ #[test]
+ fn it_encodes() {
+ let file = File {
+ name: String::from("test.txt"),
+ body: b"Hello World\n".to_vec(),
+ };
+ let expected: &[u8] = b"GU008000012test.txtHello World\n";
+ let actual: &[u8] = &file.encode();
+ assert_eq!(expected, actual);
+ }
+
+ #[test]
+ fn it_roundtrips() {
+ let file = File {
+ name: String::from("test.txt"),
+ body: b"Hello World\n".to_vec(),
+ };
+ let encoded = file.encode();
+ let expected = Ok((&b""[..], file));
+ let actual = File::parse(&encoded);
+ assert_eq!(expected, actual);
+ }
}
