Skip to content

Commit

Permalink
Remove unsafe from ReadToString
Browse files Browse the repository at this point in the history
We can do everything needed with only safe code.
  • Loading branch information
goffrie authored Apr 8, 2020
1 parent de8326a commit 51876a7
Showing 1 changed file with 6 additions and 7 deletions.
13 changes: 6 additions & 7 deletions tokio/src/io/util/read_to_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ where
let start_len = buf.len();
ReadToString {
reader,
bytes: unsafe { mem::replace(buf.as_mut_vec(), Vec::new()) },
bytes: mem::replace(buf, String::new()).into_bytes(),
buf,
start_len,
}
Expand All @@ -39,18 +39,17 @@ fn read_to_string_internal<R: AsyncRead + ?Sized>(
start_len: usize,
) -> Poll<io::Result<usize>> {
let ret = ready!(read_to_end_internal(reader, cx, bytes, start_len));
if str::from_utf8(&bytes).is_err() {
if let Ok(string) = String::from_utf8(mem::take(bytes)) {
debug_assert!(buf.is_empty());
*bytes = mem::replace(buf, string).into_bytes();
Poll::Ready(ret)
} else {
Poll::Ready(ret.and_then(|_| {
Err(io::Error::new(
io::ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
))
}))
} else {
debug_assert!(buf.is_empty());
// Safety: `bytes` is a valid UTF-8 because `str::from_utf8` returned `Ok`.
mem::swap(unsafe { buf.as_mut_vec() }, bytes);
Poll::Ready(ret)
}
}

Expand Down

0 comments on commit 51876a7

Please sign in to comment.