Created
July 27, 2016 21:21
-
-
Save 3Hren/98d5c3af4194ef4bc369af1e9f413e2e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[test] | |
fn from_str_strfix_decode_buf() { | |
// Wrap an incomplete buffer into the Cursor to see how many bytes were consumed. | |
let mut cur = Cursor::new(vec![0xaa, 0x6c, 0x65, 0x20, 0x6d, 0x65, 0x73]); | |
assert!(read_str_from_buf_read(&mut cur).is_err()); | |
// Did not read anything actually. | |
assert_eq!(0, cur.position()); | |
// ... complete the buffer and try to parse again. | |
cur.get_mut().append(&mut vec![0x73, 0x61, 0x67, 0x65]); | |
assert_eq!(("le message", cur.get_ref().len()), read_str_from_buf_read(&mut cur).unwrap()); | |
assert_eq!(0, cur.position()); | |
} | |
#[test] | |
fn from_str_strfix_decode_buf_with_trailing_bytes() { | |
let buf = vec![ | |
0xaa, 0x6c, 0x65, 0x20, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x01, 0x02, 0x03 | |
]; | |
assert_eq!(("le message", 11), read_str_from_buf_read(&mut &buf[..]).unwrap()); | |
} | |
/// Attempts to read and decode a string value from the given BufRead, returning a tuple with an | |
/// UTF-8 string decoded and number of bytes "read" to be consume. | |
/// | |
/// This function does not consume bytes read from the buffer, which makes possible safe retrying | |
/// in the case of failed read attempts, for example where the buffer isn't large enough. | |
/// | |
/// # Examples | |
/// | |
/// ``` | |
/// ``` | |
pub fn read_str_from_buf_read<R: BufRead>(rd: &mut R) -> Result<(&str, usize), DecodeStringError> { | |
let mut buf = try!(rd.fill_buf() | |
.map_err(|e| DecodeStringError::InvalidMarkerRead(From::from(e)))); | |
let len = try!(read_str_len(&mut buf)); | |
let ulen = len as usize; | |
if buf[..].len() >= ulen { | |
match from_utf8(&mut &buf[..ulen]) { | |
Ok(val) => Ok((val, 1 + ulen)), | |
Err(err) => Err(DecodeStringError::InvalidUtf8(buf, err)), | |
} | |
} else { | |
Err(DecodeStringError::BufferSizeTooSmall(len)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment