From f46f05bae8d81246f1ad93ccee051a13c9be393e Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 29 Jun 2018 17:02:38 +1000 Subject: [PATCH] Make `BTreeMap::clone()` not allocate when cloning an empty tree. --- src/liballoc/collections/btree/map.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/liballoc/collections/btree/map.rs b/src/liballoc/collections/btree/map.rs index e6e454446e232..2aad3149bb211 100644 --- a/src/liballoc/collections/btree/map.rs +++ b/src/liballoc/collections/btree/map.rs @@ -213,7 +213,16 @@ impl Clone for BTreeMap { } } - clone_subtree(self.root.as_ref()) + if self.len() == 0 { + // Ideally we'd call `BTreeMap::new` here, but that has the `K: + // Ord` constraint, which this method lacks. + BTreeMap { + root: node::Root::shared_empty_root(), + length: 0, + } + } else { + clone_subtree(self.root.as_ref()) + } } }