From 417b20835d9409ecfc9aa62e25368a5c1040b7ee Mon Sep 17 00:00:00 2001 From: Jacob Hughes Date: Mon, 14 Mar 2022 06:55:36 -0400 Subject: [PATCH] btreemap-alloc: fix clear impl --- library/alloc/src/collections/btree/map.rs | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index da2964aa5d7..95d9c3142dd 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -571,11 +571,12 @@ impl BTreeMap { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn clear(&mut self) { - let alloc = unsafe { - // drop all elements and retrieve allocator - ptr::read(self).into_iter().into_alloc() - }; - *self = BTreeMap::new_in(alloc); + // avoid moving the allocator + mem::drop(BTreeMap { + root: mem::replace(&mut self.root, None), + length: mem::replace(&mut self.length, 0), + alloc: ManuallyDrop::new(&*self.alloc), + }); } /// Makes a new empty BTreeMap with a reasonable choice for B. @@ -1594,11 +1595,6 @@ impl IntoIterator for BTreeMap { #[stable(feature = "btree_drop", since = "1.7.0")] impl Drop for IntoIter { fn drop(&mut self) { - self.dealloc() - } -} -impl IntoIter { - fn dealloc(&mut self) { struct DropGuard<'a, K, V, A: Allocator>(&'a mut IntoIter); impl<'a, K, V, A: Allocator> Drop for DropGuard<'a, K, V, A> { @@ -1649,11 +1645,6 @@ impl IntoIter { Some(unsafe { self.range.deallocating_next_back_unchecked(&self.alloc) }) } } - fn into_alloc(mut self) -> A { - self.dealloc(); // Deallocate, then don't drop as drop will also call dealloc - let iter = ManuallyDrop::new(self); - unsafe { ptr::read(&iter.alloc) } - } } #[stable(feature = "rust1", since = "1.0.0")]