Skip to content

Commit

Permalink
Replace read_to_string -> read_to_end to improve UTF-8 deserialization
Browse files Browse the repository at this point in the history
See c1692e9
There are two more instances, encountered when debugging #148

> Instead of read_to_string(), use read_to_end() to read into a buffer,
> then convert using String::from_utf8() and unwrap it. This gives a
> better error message when UTF-8 fails to decode.

which includes the offending bytes that can't be converted
  • Loading branch information
iceiix committed May 12, 2019
1 parent b98ba3a commit 10e5d6f
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
5 changes: 3 additions & 2 deletions src/nbt/mod.rs
Expand Up @@ -304,7 +304,8 @@ pub fn write_string<W: io::Write>(buf: &mut W, s: &str) -> Result<(), protocol::

pub fn read_string<R: io::Read>(buf: &mut R) -> Result<String, protocol::Error> {
let len: i16 = buf.read_i16::<BigEndian>()?;
let mut ret = String::new();
buf.take(len as u64).read_to_string(&mut ret)?;
let mut bytes = Vec::<u8>::new();
buf.take(len as u64).read_to_end(&mut bytes)?;
let ret = String::from_utf8(bytes).unwrap();
Result::Ok(ret)
}
5 changes: 3 additions & 2 deletions src/protocol/mod.rs
Expand Up @@ -275,8 +275,9 @@ impl Serializable for String {
impl Serializable for format::Component {
fn read_from<R: io::Read>(buf: &mut R) -> Result<Self, Error> {
let len = VarInt::read_from(buf)?.0;
let mut ret = String::new();
buf.take(len as u64).read_to_string(&mut ret)?;
let mut bytes = Vec::<u8>::new();
buf.take(len as u64).read_to_end(&mut bytes)?;
let ret = String::from_utf8(bytes).unwrap();
Result::Ok(Self::from_string(&ret[..]))
}
fn write_to<W: io::Write>(&self, buf: &mut W) -> Result<(), Error> {
Expand Down

0 comments on commit 10e5d6f

Please sign in to comment.