From 15ec95a98de3e135b89c81a369f6013004e89cae Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Wed, 9 Nov 2022 22:28:55 +0000 Subject: [PATCH] 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. --- serde/src/de/format.rs | 8 ++++---- serde/src/de/mod.rs | 12 ++++++++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/serde/src/de/format.rs b/serde/src/de/format.rs index 58ec0968..aa4d53f9 100644 --- a/serde/src/de/format.rs +++ b/serde/src/de/format.rs @@ -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) } } diff --git a/serde/src/de/mod.rs b/serde/src/de/mod.rs index d9dafbe1..43084a48 100644 --- a/serde/src/de/mod.rs +++ b/serde/src/de/mod.rs @@ -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)) } }