Reorganize and refactor, adding integration test for common library stuff
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
use std::io::{Error, ErrorKind, Read, Write};
|
||||
|
||||
/// The saslauthd protocol transmits strings as
|
||||
/// 16-bit unsigned network-byte-order lengths followed
|
||||
/// by the string itself.
|
||||
///
|
||||
pub fn read_string(stream: &mut impl Read) -> Result<String, Error> {
|
||||
let mut length_buffer = [0u8, 0u8];
|
||||
|
||||
stream.read_exact(&mut length_buffer)?;
|
||||
let length = u16::from_be_bytes(length_buffer);
|
||||
|
||||
let mut string_buffer = vec![0u8; length as usize];
|
||||
|
||||
stream.read_exact(&mut string_buffer)?;
|
||||
|
||||
match String::from_utf8(string_buffer) {
|
||||
Ok(str) => Ok(str),
|
||||
Err(_err) => Err(Error::new(ErrorKind::Other, "Invalid UTF-8 sent")),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_string(stream: &mut impl Write, s: &str) -> Result<(), Error> {
|
||||
let length = s.len();
|
||||
|
||||
if length > 0xffff {
|
||||
return Err(Error::new(ErrorKind::Other, "String too long to write"));
|
||||
}
|
||||
|
||||
let length_buffer = [(length >> 8) as u8, (length & 0xff) as u8];
|
||||
|
||||
stream.write_all(&length_buffer)?;
|
||||
stream.write_all(s.as_bytes())?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user