Skip to content

Commit cf78a79

Browse files
authored
Rollup merge of #118660 - cuviper:alloc_str, r=petrochenkov
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!
2 parents 1b391d4 + 92bf40f commit cf78a79

File tree

3 files changed

+24
-8
lines changed

3 files changed

+24
-8
lines changed

compiler/rustc_arena/src/lib.rs

+22
Original file line numberDiff line numberDiff line change
@@ -484,6 +484,20 @@ impl DroplessArena {
484484
}
485485
}
486486

487+
/// Allocates a string slice that is copied into the `DroplessArena`, returning a
488+
/// reference to it. Will panic if passed an empty string.
489+
///
490+
/// Panics:
491+
///
492+
/// - Zero-length string
493+
#[inline]
494+
pub fn alloc_str(&self, string: &str) -> &str {
495+
let slice = self.alloc_slice(string.as_bytes());
496+
497+
// SAFETY: the result has a copy of the same valid UTF-8 bytes.
498+
unsafe { std::str::from_utf8_unchecked(slice) }
499+
}
500+
487501
/// # Safety
488502
///
489503
/// 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,)*]) {
655669
self.dropless.alloc_slice(value)
656670
}
657671

672+
#[inline]
673+
pub fn alloc_str(&self, string: &str) -> &str {
674+
if string.is_empty() {
675+
return "";
676+
}
677+
self.dropless.alloc_str(string)
678+
}
679+
658680
#[allow(clippy::mut_from_ref)]
659681
pub fn alloc_from_iter<T: ArenaAllocatable<'tcx, C>, C>(
660682
&self,

compiler/rustc_middle/src/ty/mod.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -2614,9 +2614,7 @@ pub struct SymbolName<'tcx> {
26142614

26152615
impl<'tcx> SymbolName<'tcx> {
26162616
pub fn new(tcx: TyCtxt<'tcx>, name: &str) -> SymbolName<'tcx> {
2617-
SymbolName {
2618-
name: unsafe { str::from_utf8_unchecked(tcx.arena.alloc_slice(name.as_bytes())) },
2619-
}
2617+
SymbolName { name: tcx.arena.alloc_str(name) }
26202618
}
26212619
}
26222620

compiler/rustc_span/src/symbol.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -2119,11 +2119,7 @@ impl Interner {
21192119
return Symbol::new(idx as u32);
21202120
}
21212121

2122-
// SAFETY: we convert from `&str` to `&[u8]`, clone it into the arena,
2123-
// and immediately convert the clone back to `&[u8]`, all because there
2124-
// is no `inner.arena.alloc_str()` method. This is clearly safe.
2125-
let string: &str =
2126-
unsafe { str::from_utf8_unchecked(inner.arena.alloc_slice(string.as_bytes())) };
2122+
let string: &str = inner.arena.alloc_str(string);
21272123

21282124
// SAFETY: we can extend the arena allocation to `'static` because we
21292125
// only access these while the arena is still alive.

0 commit comments

Comments
 (0)