Revamp deserialize_char (#133)

* Remove unneccesary unwrap

* Use a single buffer for reading a char

* Replace while loop with read_exact

* Remove first_byte variable

* Use read_exact to avoid waiting for data after EOF

* Create error in a closure
This commit is contained in:
slyrz 2017-03-09 20:02:27 +01:00 committed by Ty Overby
parent 33b07e2bce
commit 6c3b677dd7
1 changed files with 16 additions and 26 deletions

View File

@ -151,36 +151,26 @@ impl<'a, R: Read, E: ByteOrder> serde::Deserializer for &'a mut Deserializer<R,
{ {
use std::str; use std::str;
let error = ErrorKind::InvalidEncoding{ let error = || {
desc: "Invalid char encoding", ErrorKind::InvalidEncoding{
detail: None desc: "Invalid char encoding",
}.into(); detail: None,
}.into()
};
let mut buf = [0]; let mut buf = [0u8; 4];
let _ = try!(self.reader.read(&mut buf[..])); // Look at the first byte to see how many bytes must be read
let first_byte = buf[0]; let _ = try!(self.reader.read_exact(&mut buf[..1]));
let width = utf8_char_width(first_byte); let width = utf8_char_width(buf[0]);
if width == 1 { return visitor.visit_char(first_byte as char) } if width == 1 { return visitor.visit_char(buf[0] as char) }
if width == 0 { return Err(error)} if width == 0 { return Err(error())}
let mut buf = [first_byte, 0, 0, 0]; if self.reader.read_exact(&mut buf[1..width]).is_err() {
{ return Err(error());
let mut start = 1;
while start < width {
match try!(self.reader.read(&mut buf[start .. width])) {
n if n == width - start => break,
n if n < width - start => { start += n; }
_ => return Err(error)
}
}
} }
let res = try!(match str::from_utf8(&buf[..width]).ok() { let res = try!(str::from_utf8(&buf[..width]).ok().and_then(|s| s.chars().next()).ok_or(error()));
Some(s) => Ok(s.chars().next().unwrap()),
None => Err(error)
});
visitor.visit_char(res) visitor.visit_char(res)
} }