Skip to content

Commit

Permalink
make SmallBox covariant over T
Browse files Browse the repository at this point in the history
  • Loading branch information
PonasKovas committed Dec 2, 2024
1 parent e2dbc84 commit ef1ca3b
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/smallbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: ?Sized, Space> {
space: MaybeUninit<UnsafeCell<Space>>,
ptr: *mut T,
ptr: *const T,
_phantom: PhantomData<T>,
}

Expand Down Expand Up @@ -229,7 +229,7 @@ impl<T: ?Sized, Space> SmallBox<T, Space> {
#[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)
}
Expand Down Expand Up @@ -260,7 +260,7 @@ impl<T: ?Sized, Space> SmallBox<T, Space> {
if this.is_heap() {
let layout = Layout::new::<T>();
unsafe {
alloc::dealloc(this.ptr.cast(), layout);
alloc::dealloc(this.ptr as *const u8 as *mut u8, layout);
}
}

Expand Down Expand Up @@ -364,7 +364,7 @@ impl<T: ?Sized, Space> ops::Drop for SmallBox<T, Space> {
let layout = Layout::for_value::<T>(&*self);
ptr::drop_in_place::<T>(&mut **self);
if self.is_heap() {
alloc::dealloc(self.ptr.cast(), layout);
alloc::dealloc(self.ptr as *const u8 as *mut u8, layout);
}
}
}
Expand Down Expand Up @@ -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
}
}
}

0 comments on commit ef1ca3b

Please sign in to comment.