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
10 changes: 8 additions & 2 deletions library/alloc/src/collections/btree/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,14 @@ pub struct BTreeMap<
#[stable(feature = "btree_drop", since = "1.7.0")]
unsafe impl<#[may_dangle] K, #[may_dangle] V, A: AllocatorClone> Drop for BTreeMap<K, V, A> {
fn drop(&mut self) {
// ignore-tidy-undocumented-unsafe
drop(unsafe { ptr::read(self) }.into_iter())
if self.root.is_some() {
// ignore-tidy-undocumented-unsafe
drop(unsafe { ptr::read(self) }.into_iter())
} else {
// SAFETY: With no root there are no nodes to free, so only the allocator needs
// dropping. `self` is not used after this, and `alloc` is dropped only here.
unsafe { ManuallyDrop::drop(&mut self.alloc) }
}
}
}

Expand Down
15 changes: 15 additions & 0 deletions tests/codegen-llvm/btree-empty-drop.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Regression test for https://github.com/rust-lang/rust/issues/161375
// Checking that an empty BTree's drop is optimized away.
//@ compile-flags: -Copt-level=3

#![crate_type = "lib"]

use std::collections::BTreeMap;

// CHECK-LABEL: @drop_btree(
// CHECK-NEXT: {{.*}}:
// CHECK-NEXT: ret void
#[no_mangle]
pub fn drop_btree() {
let _ = BTreeMap::<(), ()>::new();
}
Loading