Skip to content

Commit

Permalink
Revert Buf::as_str safety change from PR 2319
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Nov 28, 2022
1 parent 1050f6b commit 6814f97
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 13 deletions.
6 changes: 3 additions & 3 deletions serde/src/de/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
}
}

Expand Down
12 changes: 2 additions & 10 deletions serde/src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}

Expand Down Expand Up @@ -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))
}
}

Expand Down

0 comments on commit 6814f97

Please sign in to comment.