codeq/codec/impls/
string_impl.rs1use std::io;
2
3use byteorder::BigEndian;
4use byteorder::ReadBytesExt;
5use byteorder::WriteBytesExt;
6
7use crate::Decode;
8use crate::Encode;
9
10impl Encode for String {
11 fn encode<W: io::Write>(&self, mut w: W) -> Result<usize, io::Error> {
12 let bytes = self.as_bytes();
13 w.write_u32::<BigEndian>(bytes.len() as u32)?;
14 w.write_all(bytes)?;
15 Ok(bytes.len() + 4)
16 }
17}
18
19impl Decode for String {
20 fn decode<R: io::Read>(mut r: R) -> Result<Self, io::Error> {
21 let len = r.read_u32::<BigEndian>()? as usize;
22 let mut buf = vec![0; len];
23 r.read_exact(&mut buf)?;
24 String::from_utf8(buf).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
25 }
26}
27
28#[cfg(test)]
29mod tests {
30
31 use std::io;
32
33 use crate::Decode;
34 use crate::Encode;
35
36 #[test]
37 fn test_string_codec() -> Result<(), io::Error> {
38 let s = "hello".to_string();
39 let mut buf = Vec::new();
40 let n = s.encode(&mut buf)?;
41 assert_eq!(n, buf.len());
42 assert_eq!(buf.len(), 4 + s.len());
43
44 let b = String::decode(&mut buf.as_slice())?;
45 assert_eq!(s, b);
46
47 Ok(())
48 }
49}