mirror of https://git.sr.ht/~stygianentity/bincode
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:
parent
33b07e2bce
commit
6c3b677dd7
|
|
@ -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 = || {
|
||||||
|
ErrorKind::InvalidEncoding{
|
||||||
desc: "Invalid char encoding",
|
desc: "Invalid char encoding",
|
||||||
detail: None
|
detail: None,
|
||||||
}.into();
|
}.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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue