Make Buf::as_str private and unsafe, add safety docs

serde:🇩🇪:format::Buf is a private type, so this makes it explicit by
declaring the type `pub(super)`. In addition, it marks the function
`Buf::as_str` as unsafe, which lets us document the callsites with
`// Safety: ...` comments to explain why it is safe to use.
This commit is contained in:
Erick Tryzelaar 2022-11-09 22:28:55 +00:00
parent 072145e0e9
commit 15ec95a98d
2 changed files with 14 additions and 6 deletions

View File

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

View File

@ -1376,7 +1376,11 @@ 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();
Err(Error::invalid_type(Unexpected::Other(writer.as_str()), &self))
// 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))
}
}
@ -1438,7 +1442,11 @@ 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();
Err(Error::invalid_type(Unexpected::Other(writer.as_str()), &self))
// 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))
}
}