Skip to content

Commit

Permalink
ThinBoxSlice::empty is safe
Browse files Browse the repository at this point in the history
Reviewed By: ndmitchell

Differential Revision: D66454375

fbshipit-source-id: 8d843b80361b93524a5b6c1b187773791469e897
  • Loading branch information
stepancheg authored and facebook-github-bot committed Nov 25, 2024
1 parent d1780f9 commit c781c9c
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions app/buck2_util/src/thin_box.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,25 @@ impl<T> ThinBoxSliceLayout<T> {
/// `Box<[T]>` but thin pointer.
///
/// Statically allocated for empty slice.
pub struct ThinBoxSlice<T> {
// We don't really need `'static` here, but we hit type checker limitations.
pub struct ThinBoxSlice<T: 'static> {
/// Pointer to the first element, `ThinBoxSliceLayout.data`.
ptr: NonNull<T>,
}

unsafe impl<T: Sync> Sync for ThinBoxSlice<T> {}
unsafe impl<T: Send> Send for ThinBoxSlice<T> {}

impl<T> ThinBoxSlice<T> {
impl<T: 'static> ThinBoxSlice<T> {
#[inline]
pub const fn empty() -> ThinBoxSlice<T> {
let instance = &ThinBoxSliceLayout::<T> { len: 0, data: [] };
const fn instance<T>() -> &'static ThinBoxSliceLayout<T> {
&ThinBoxSliceLayout::<T> { len: 0, data: [] }
}

unsafe {
ThinBoxSlice {
ptr: NonNull::new_unchecked(instance.data.as_ptr() as *mut T),
ptr: NonNull::new_unchecked(instance::<T>().data.as_ptr() as *mut T),
}
}
}
Expand Down Expand Up @@ -106,7 +110,7 @@ impl<T> ThinBoxSlice<T> {
}
}

impl<T> Deref for ThinBoxSlice<T> {
impl<T: 'static> Deref for ThinBoxSlice<T> {
type Target = [T];

#[inline]
Expand All @@ -115,7 +119,7 @@ impl<T> Deref for ThinBoxSlice<T> {
}
}

impl<T> DerefMut for ThinBoxSlice<T> {
impl<T: 'static> DerefMut for ThinBoxSlice<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.read_len()) }
Expand All @@ -133,7 +137,7 @@ impl<T> ThinBoxSlice<MaybeUninit<T>> {
}
}

impl<T> Drop for ThinBoxSlice<T> {
impl<T: 'static> Drop for ThinBoxSlice<T> {
#[inline]
fn drop(&mut self) {
unsafe {
Expand All @@ -148,7 +152,7 @@ impl<T> Drop for ThinBoxSlice<T> {
}
}

impl<T> Default for ThinBoxSlice<T> {
impl<T: 'static> Default for ThinBoxSlice<T> {
#[inline]
fn default() -> Self {
ThinBoxSlice::empty()
Expand Down

0 comments on commit c781c9c

Please sign in to comment.