mirror of
https://github.com/pezkuwichain/serde.git
synced 2026-06-14 04:41:01 +00:00
Make Buf::as_str private and unsafe, add safety docs
serde::de::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:
@@ -1,19 +1,19 @@
|
|||||||
use lib::fmt::{self, Write};
|
use lib::fmt::{self, Write};
|
||||||
use lib::str;
|
use lib::str;
|
||||||
|
|
||||||
pub struct Buf<'a> {
|
pub(super) struct Buf<'a> {
|
||||||
bytes: &'a mut [u8],
|
bytes: &'a mut [u8],
|
||||||
offset: usize,
|
offset: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> Buf<'a> {
|
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 }
|
Buf { bytes, offset: 0 }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
pub(super) unsafe fn as_str(&self) -> &str {
|
||||||
let slice = &self.bytes[..self.offset];
|
let slice = &self.bytes[..self.offset];
|
||||||
unsafe { str::from_utf8_unchecked(slice) }
|
str::from_utf8_unchecked(slice)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+10
-2
@@ -1376,7 +1376,11 @@ pub trait Visitor<'de>: Sized {
|
|||||||
let mut buf = [0u8; 58];
|
let mut buf = [0u8; 58];
|
||||||
let mut writer = format::Buf::new(&mut buf);
|
let mut writer = format::Buf::new(&mut buf);
|
||||||
fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as i128", v)).unwrap();
|
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 buf = [0u8; 57];
|
||||||
let mut writer = format::Buf::new(&mut buf);
|
let mut writer = format::Buf::new(&mut buf);
|
||||||
fmt::Write::write_fmt(&mut writer, format_args!("integer `{}` as u128", v)).unwrap();
|
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))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user