Revert Buf::as_str safety change from PR 2319

This commit is contained in:
David Tolnay 2022-11-27 16:56:31 -08:00
parent 1050f6b808
commit 6814f978d7
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
2 changed files with 5 additions and 13 deletions

View File

@ -7,13 +7,13 @@ pub(super) struct Buf<'a> {
}
impl<'a> Buf<'a> {
pub(super) fn new(bytes: &'a mut [u8]) -> Self {
pub fn new(bytes: &'a mut [u8]) -> Self {
Buf { bytes, offset: 0 }
}
pub(super) unsafe fn as_str(&self) -> &str {
pub fn as_str(&self) -> &str {
let slice = &self.bytes[..self.offset];
str::from_utf8_unchecked(slice)
unsafe { str::from_utf8_unchecked(slice) }
}
}

View File

@ -1376,11 +1376,7 @@ pub trait Visitor<'de>: Sized {
let mut buf = [0u8; 58];
let mut writer = format::Buf::new(&mut buf);
fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as i128", v)).unwrap();
// Safety: This is safe because we only wrote UTF-8 into the buffer.
let s = unsafe { writer.as_str() };
Err(Error::invalid_type(Unexpected::Other(s), &self))
Err(Error::invalid_type(Unexpected::Other(writer.as_str()), &self))
}
}
@ -1442,11 +1438,7 @@ pub trait Visitor<'de>: Sized {
let mut buf = [0u8; 57];
let mut writer = format::Buf::new(&mut buf);
fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as u128", v)).unwrap();
// Safety: This is safe because we only wrote UTF-8 into the buffer.
let s = unsafe { writer.as_str() };
Err(Error::invalid_type(Unexpected::Other(s), &self))
Err(Error::invalid_type(Unexpected::Other(writer.as_str()), &self))
}
}