Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ strip = false
allocator-api = []
allocator-api2 = ["dep:allocator-api2", "allocator-api"]
internals = []
may_dangle = []
proptest = ["dep:proptest", "std"]
rayon = ["std", "dep:rayon"]
serde = ["dep:serde_core"]
Expand Down
28 changes: 28 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(feature = "specialization", allow(incomplete_features))]
#![cfg_attr(feature = "specialization", feature(specialization, trusted_len))]
#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
#![cfg_attr(
all(feature = "allocator-api", not(feature = "allocator-api2")),
feature(allocator_api)
Expand Down Expand Up @@ -1492,6 +1493,33 @@ impl<Heap: Allocator> Drop for DropDealloc<'_, Heap> {
}
}

#[cfg(feature = "may_dangle")]
unsafe impl<#[may_dangle] Item, const INLINE: usize, Heap: Allocator> Drop
for SmallVec<Item, INLINE, Heap>
{
fn drop(&mut self) {
let (length, on_heap) = self.length.parts();
// SAFETY: the tag tells which member is active
let ptr = unsafe { self.raw.as_mut_ptr(on_heap) };
// SAFETY: see above
unsafe {
let _drop_dealloc = if on_heap {
let capacity = self.raw.heap.1;
Some(DropDealloc {
ptr: NonNull::new_unchecked(ptr as *mut u8),
size_bytes: capacity * size_of::<Item>(),
align: align_of::<Item>(),
allocator: &self.allocator
})
} else {
None
};
core::ptr::slice_from_raw_parts_mut(ptr, length).drop_in_place();
}
}
}

#[cfg(not(feature = "may_dangle"))]
impl<Item, const INLINE: usize, Heap: Allocator> Drop for SmallVec<Item, INLINE, Heap> {
fn drop(&mut self) {
let (length, on_heap) = self.length.parts();
Expand Down
15 changes: 15 additions & 0 deletions tests/may_dangle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#![cfg(feature = "may_dangle")]

use smallvec::SmallVec;

#[derive(Default)]
struct MyData<'a> {
arr: SmallVec<&'a u8, 5>,
dat: u8
}

#[test]
fn may_dangle_allows_borrow_of_another_field() {
let mut dat = MyData::default();
dat.arr.push(&dat.dat);
}
Loading