Skip to content

Commit

Permalink
[wip] UnalignUnsized
Browse files Browse the repository at this point in the history
  • Loading branch information
jswrenn committed Oct 8, 2024
1 parent 5908912 commit a081f40
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -783,6 +783,9 @@ pub unsafe trait KnownLayout {
// resulting size would not fit in a `usize`.
meta.size_for_metadata(Self::LAYOUT)
}

#[doc(hidden)]
unsafe fn drop(slf: &mut UnalignUnsized<Self>);
}

/// The metadata associated with a [`KnownLayout`] type.
Expand Down Expand Up @@ -898,6 +901,25 @@ unsafe impl<T> KnownLayout for [T] {
// struct `Foo(i32, [u8])` or `(u64, Foo)`.
slc.len()
}

#[cfg(feature = "alloc")]
unsafe fn drop(slf: &mut UnalignUnsized<Self>) {
let meta = KnownLayout::pointer_to_metadata(slf);
let size = meta.size_for_metadata(Self::LAYOUT).unwrap();
let aligned = MaybeUninit::<Self>::new_boxed_uninit(meta).unwrap();
let aligned = Box::into_raw(aligned);
// SAFETY: todo
unsafe {
core::ptr::copy_nonoverlapping(slf as *mut _ as *mut u8, aligned as *mut u8, size);
}
let _ = Box::from_raw(aligned);
}

#[cfg(not(feature = "alloc"))]
unsafe fn drop(_: &mut UnalignUnsized<Self>) {
// PME if T needs drop.
static_assert!(T=> !core::mem::needs_drop::<T>());
}
}

#[rustfmt::skip]
Expand Down
8 changes: 8 additions & 0 deletions src/util/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,10 @@ macro_rules! impl_known_layout {
#[inline(always)]
fn pointer_to_metadata(_ptr: *mut Self) -> () {
}

unsafe fn drop(slf: &mut crate::UnalignUnsized<Self>) {
let _ = unsafe { slf.take() };
}
}
};
};
Expand Down Expand Up @@ -597,6 +601,10 @@ macro_rules! unsafe_impl_known_layout {
let ptr = ptr as *mut $repr;
<$repr>::pointer_to_metadata(ptr)
}

unsafe fn drop(_slf: &mut UnalignUnsized<Self>) {
todo!()
}
}
};
};
Expand Down
27 changes: 27 additions & 0 deletions src/wrappers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,33 @@ impl<T: Unaligned + Display> Display for Unalign<T> {
}
}

/// TODO
#[derive(Debug)]
#[repr(C, packed)]
pub struct UnalignUnsized<T: ?Sized>(ManuallyDrop<T>)
where
T: KnownLayout;

impl<T> UnalignUnsized<T>
where
T: KnownLayout,
{
pub(crate) unsafe fn take(&mut self) -> T {
todo!()
}
}

impl<T: ?Sized> Drop for UnalignUnsized<T>
where
T: KnownLayout,
{
fn drop(&mut self) {
if core::mem::needs_drop::<T>() {
unsafe { T::drop(self) }
}
}
}

/// A wrapper type to construct uninitialized instances of `T`.
///
/// `MaybeUninit` is identical to the [standard library
Expand Down

0 comments on commit a081f40

Please sign in to comment.