From eb4dfc391cfe76c983c821124e83224dc66de585 Mon Sep 17 00:00:00 2001 From: Mykolas Peteraitis Date: Sun, 22 Dec 2024 12:53:48 +0300 Subject: [PATCH] make SmallBox covariant over T (#40) --- src/smallbox.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/smallbox.rs b/src/smallbox.rs index 96b8bec..d4e6289 100644 --- a/src/smallbox.rs +++ b/src/smallbox.rs @@ -69,7 +69,7 @@ macro_rules! smallbox { /// An optimized box that store value on stack or on heap depending on its size pub struct SmallBox { space: MaybeUninit>, - ptr: *mut T, + ptr: *const T, _phantom: PhantomData, } @@ -229,7 +229,7 @@ impl SmallBox { #[inline] unsafe fn as_mut_ptr(&mut self) -> *mut T { if self.is_heap() { - self.ptr + self.ptr as *mut T } else { sptr::with_metadata_of_mut(self.space.as_mut_ptr(), self.ptr) } @@ -260,7 +260,7 @@ impl SmallBox { if this.is_heap() { let layout = Layout::new::(); unsafe { - alloc::dealloc(this.ptr.cast(), layout); + alloc::dealloc(this.ptr as *const u8 as *mut u8, layout); } } @@ -364,7 +364,7 @@ impl ops::Drop for SmallBox { let layout = Layout::for_value::(&*self); ptr::drop_in_place::(&mut **self); if self.is_heap() { - alloc::dealloc(self.ptr.cast(), layout); + alloc::dealloc(self.ptr as *const u8 as *mut u8, layout); } } } @@ -665,4 +665,12 @@ mod tests { cellbox.set(1); assert_eq!(cellbox.get(), 1); } + + #[test] + fn test_variance() { + #[allow(dead_code)] + fn test<'short, 'long: 'short>(val: SmallBox<&'long str, S1>) -> SmallBox<&'short str, S1> { + val + } + } }