Skip to content

Commit

Permalink
Rollup merge of #110921 - JohnBobbo96:rustc_arena_nonnull, r=Nilstrieb
Browse files Browse the repository at this point in the history
Use `NonNull::new_unchecked` and `NonNull::len` in `rustc_arena`.

This avoids a few extra dereferences as well as an `unwrap`.

According to the docs for [`NonNull::len`](https://doc.rust-lang.org/std/ptr/struct.NonNull.html#method.len) this also ensures that:

> This function is safe, even when the non-null raw slice cannot be dereferenced to a slice because the pointer does not have a valid address.

I am also fairly sure that the `unwrap` is unneeded in this case, as the docs for [`Box::into_raw`](https://doc.rust-lang.org/std/boxed/struct.Box.html#method.into_raw) also state:

> Consumes the Box, returning a wrapped raw pointer.
**The pointer will be properly aligned and non-null.**
  • Loading branch information
GuillaumeGomez authored Apr 28, 2023
2 parents 48413b8 + 618841b commit 3962bfd
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions compiler/rustc_arena/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ impl<T> ArenaChunk<T> {
#[inline]
unsafe fn new(capacity: usize) -> ArenaChunk<T> {
ArenaChunk {
storage: NonNull::new(Box::into_raw(Box::new_uninit_slice(capacity))).unwrap(),
storage: NonNull::new_unchecked(Box::into_raw(Box::new_uninit_slice(capacity))),
entries: 0,
}
}
Expand All @@ -85,7 +85,7 @@ impl<T> ArenaChunk<T> {
// The branch on needs_drop() is an -O1 performance optimization.
// Without the branch, dropping TypedArena<u8> takes linear time.
if mem::needs_drop::<T>() {
let slice = &mut *(self.storage.as_mut());
let slice = self.storage.as_mut();
ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(&mut slice[..len]));
}
}
Expand All @@ -104,7 +104,7 @@ impl<T> ArenaChunk<T> {
// A pointer as large as possible for zero-sized elements.
ptr::invalid_mut(!0)
} else {
self.start().add((*self.storage.as_ptr()).len())
self.start().add(self.storage.len())
}
}
}
Expand Down Expand Up @@ -288,7 +288,7 @@ impl<T> TypedArena<T> {
// If the previous chunk's len is less than HUGE_PAGE
// bytes, then this chunk will be least double the previous
// chunk's size.
new_cap = (*last_chunk.storage.as_ptr()).len().min(HUGE_PAGE / elem_size / 2);
new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2);
new_cap *= 2;
} else {
new_cap = PAGE / elem_size;
Expand Down Expand Up @@ -396,7 +396,7 @@ impl DroplessArena {
// If the previous chunk's len is less than HUGE_PAGE
// bytes, then this chunk will be least double the previous
// chunk's size.
new_cap = (*last_chunk.storage.as_ptr()).len().min(HUGE_PAGE / 2);
new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2);
new_cap *= 2;
} else {
new_cap = PAGE;
Expand Down

0 comments on commit 3962bfd

Please sign in to comment.