Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions src/atom.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,14 +336,21 @@ impl<Static: StaticAtomSet> Ord for Atom<Static> {
// over the one from &str.
impl<Static: StaticAtomSet> Atom<Static> {
fn from_mutated_str<F: FnOnce(&mut str)>(s: &str, f: F) -> Self {
let mut buffer = mem::MaybeUninit::<[u8; 64]>::uninit();
let buffer = unsafe { &mut *buffer.as_mut_ptr() };

if let Some(buffer_prefix) = buffer.get_mut(..s.len()) {
buffer_prefix.copy_from_slice(s.as_bytes());
let as_str = unsafe { ::std::str::from_utf8_unchecked_mut(buffer_prefix) };
f(as_str);
Atom::from(&*as_str)
const MAX_STACK_SIZE: usize = 64;
let mut buffer = mem::MaybeUninit::<[u8; MAX_STACK_SIZE]>::uninit();

if s.len() <= MAX_STACK_SIZE {
let buffer_ptr = buffer.as_mut_ptr() as *mut u8;
// SAFETY: `buffer_ptr` points to the `MaybeUninit` array.
// We use `copy_nonoverlapping` to write valid data into it,
// and then create a slice covering ONLY the initialized portion.
unsafe {
std::ptr::copy_nonoverlapping(s.as_ptr(), buffer_ptr, s.len());
let buffer_slice = slice::from_raw_parts_mut(buffer_ptr, s.len());
let as_str = ::std::str::from_utf8_unchecked_mut(buffer_slice);
f(as_str);
Atom::from(&*as_str)
}
} else {
let mut string = s.to_owned();
f(&mut string);
Expand Down
8 changes: 8 additions & 0 deletions tests/ub_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use string_cache::DefaultAtom;

#[test]
fn test_to_ascii_uppercase() {
let s = DefaultAtom::from("hello");
let upper = s.to_ascii_uppercase();
assert_eq!(&*upper, "HELLO");
}