1
Fork 0

rustc_arena: add alloc_str

Two places called `from_utf8_unchecked` for strings from `alloc_slice`,
and one's SAFETY comment said this was for lack of `alloc_str` -- so
let's just add that instead!
This commit is contained in:
Josh Stone 2023-12-05 17:33:16 -08:00
parent e9013ac0e4
commit 92bf40ffe3
3 changed files with 24 additions and 8 deletions

View file

@ -484,6 +484,20 @@ impl DroplessArena {
}
}
/// Allocates a string slice that is copied into the `DroplessArena`, returning a
/// reference to it. Will panic if passed an empty string.
///
/// Panics:
///
/// - Zero-length string
#[inline]
pub fn alloc_str(&self, string: &str) -> &str {
let slice = self.alloc_slice(string.as_bytes());
// SAFETY: the result has a copy of the same valid UTF-8 bytes.
unsafe { std::str::from_utf8_unchecked(slice) }
}
/// # Safety
///
/// The caller must ensure that `mem` is valid for writes up to `size_of::<T>() * len`, and that
@ -655,6 +669,14 @@ pub macro declare_arena([$($a:tt $name:ident: $ty:ty,)*]) {
self.dropless.alloc_slice(value)
}
#[inline]
pub fn alloc_str(&self, string: &str) -> &str {
if string.is_empty() {
return "";
}
self.dropless.alloc_str(string)
}
#[allow(clippy::mut_from_ref)]
pub fn alloc_from_iter<T: ArenaAllocatable<'tcx, C>, C>(
&self,