Skip to content

Commit 12c9562

Browse files
authored
Rollup merge of #66648 - crgl:btree-clone-from, r=Amanieu
Implement clone_from for BTreeMap and BTreeSet See #28481. This results in up to 90% speedups on simple data types when `self` and `other` are the same size, and is generally comparable or faster. Some concerns: 1. This implementation requires an `Ord` bound on the `Clone` implementation for `BTreeMap` and `BTreeSet`. Since these structs can only be created externally for keys with `Ord` implemented, this should be fine? If not, there's certainly a less safe way to do this. 2. Changing `next_unchecked` on `RangeMut` to return mutable key references allows for replacing the entire overlapping portion of both maps without changing the external interface in any way. However, if `clone_from` fails it can leave the `BTreeMap` in an invalid state, which might be unacceptable. ~This probably needs an FCP since it changes a trait bound, but (as far as I know?) that change cannot break any external code.~
2 parents 9ed29b6 + 6c3e477 commit 12c9562

File tree

3 files changed

+106
-9
lines changed

3 files changed

+106
-9
lines changed

src/liballoc/collections/btree/map.rs

+74-8
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,60 @@ impl<K: Clone, V: Clone> Clone for BTreeMap<K, V> {
207207
clone_subtree(self.root.as_ref())
208208
}
209209
}
210+
211+
fn clone_from(&mut self, other: &Self) {
212+
BTreeClone::clone_from(self, other);
213+
}
214+
}
215+
216+
trait BTreeClone {
217+
fn clone_from(&mut self, other: &Self);
218+
}
219+
220+
impl<K: Clone, V: Clone> BTreeClone for BTreeMap<K, V> {
221+
default fn clone_from(&mut self, other: &Self) {
222+
*self = other.clone();
223+
}
224+
}
225+
226+
impl<K: Clone + Ord, V: Clone> BTreeClone for BTreeMap<K, V> {
227+
fn clone_from(&mut self, other: &Self) {
228+
// This truncates `self` to `other.len()` by calling `split_off` on
229+
// the first key after `other.len()` elements if it exists
230+
let split_off_key = if self.len() > other.len() {
231+
let diff = self.len() - other.len();
232+
if diff <= other.len() {
233+
self.iter().nth_back(diff - 1).map(|pair| (*pair.0).clone())
234+
} else {
235+
self.iter().nth(other.len()).map(|pair| (*pair.0).clone())
236+
}
237+
} else {
238+
None
239+
};
240+
if let Some(key) = split_off_key {
241+
self.split_off(&key);
242+
}
243+
244+
let mut siter = self.range_mut(..);
245+
let mut oiter = other.iter();
246+
// After truncation, `self` is at most as long as `other` so this loop
247+
// replaces every key-value pair in `self`. Since `oiter` is in sorted
248+
// order and the structure of the `BTreeMap` stays the same,
249+
// the BTree invariants are maintained at the end of the loop
250+
while !siter.is_empty() {
251+
if let Some((ok, ov)) = oiter.next() {
252+
// SAFETY: This is safe because the `siter.front != siter.back` check
253+
// ensures that `siter` is nonempty
254+
let (sk, sv) = unsafe { siter.next_unchecked() };
255+
sk.clone_from(ok);
256+
sv.clone_from(ov);
257+
} else {
258+
break;
259+
}
260+
}
261+
// If `other` is longer than `self`, the remaining elements are inserted
262+
self.extend(oiter.map(|(k, v)| ((*k).clone(), (*v).clone())));
263+
}
210264
}
211265

212266
impl<K, Q: ?Sized> super::Recover<Q> for BTreeMap<K, ()>
@@ -1357,7 +1411,10 @@ impl<'a, K: 'a, V: 'a> Iterator for IterMut<'a, K, V> {
13571411
None
13581412
} else {
13591413
self.length -= 1;
1360-
unsafe { Some(self.range.next_unchecked()) }
1414+
unsafe {
1415+
let (k, v) = self.range.next_unchecked();
1416+
Some((k, v)) // coerce k from `&mut K` to `&K`
1417+
}
13611418
}
13621419
}
13631420

@@ -1736,7 +1793,14 @@ impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
17361793
type Item = (&'a K, &'a mut V);
17371794

17381795
fn next(&mut self) -> Option<(&'a K, &'a mut V)> {
1739-
if self.front == self.back { None } else { unsafe { Some(self.next_unchecked()) } }
1796+
if self.is_empty() {
1797+
None
1798+
} else {
1799+
unsafe {
1800+
let (k, v) = self.next_unchecked();
1801+
Some((k, v)) // coerce k from `&mut K` to `&K`
1802+
}
1803+
}
17401804
}
17411805

17421806
fn last(mut self) -> Option<(&'a K, &'a mut V)> {
@@ -1745,16 +1809,19 @@ impl<'a, K, V> Iterator for RangeMut<'a, K, V> {
17451809
}
17461810

17471811
impl<'a, K, V> RangeMut<'a, K, V> {
1748-
unsafe fn next_unchecked(&mut self) -> (&'a K, &'a mut V) {
1812+
fn is_empty(&self) -> bool {
1813+
self.front == self.back
1814+
}
1815+
1816+
unsafe fn next_unchecked(&mut self) -> (&'a mut K, &'a mut V) {
17491817
let handle = ptr::read(&self.front);
17501818

17511819
let mut cur_handle = match handle.right_kv() {
17521820
Ok(kv) => {
17531821
self.front = ptr::read(&kv).right_edge();
17541822
// Doing the descend invalidates the references returned by `into_kv_mut`,
17551823
// so we have to do this last.
1756-
let (k, v) = kv.into_kv_mut();
1757-
return (k, v); // coerce k from `&mut K` to `&K`
1824+
return kv.into_kv_mut();
17581825
}
17591826
Err(last_edge) => {
17601827
let next_level = last_edge.into_node().ascend().ok();
@@ -1768,8 +1835,7 @@ impl<'a, K, V> RangeMut<'a, K, V> {
17681835
self.front = first_leaf_edge(ptr::read(&kv).right_edge().descend());
17691836
// Doing the descend invalidates the references returned by `into_kv_mut`,
17701837
// so we have to do this last.
1771-
let (k, v) = kv.into_kv_mut();
1772-
return (k, v); // coerce k from `&mut K` to `&K`
1838+
return kv.into_kv_mut();
17731839
}
17741840
Err(last_edge) => {
17751841
let next_level = last_edge.into_node().ascend().ok();
@@ -1783,7 +1849,7 @@ impl<'a, K, V> RangeMut<'a, K, V> {
17831849
#[stable(feature = "btree_range", since = "1.17.0")]
17841850
impl<'a, K, V> DoubleEndedIterator for RangeMut<'a, K, V> {
17851851
fn next_back(&mut self) -> Option<(&'a K, &'a mut V)> {
1786-
if self.front == self.back { None } else { unsafe { Some(self.next_back_unchecked()) } }
1852+
if self.is_empty() { None } else { unsafe { Some(self.next_back_unchecked()) } }
17871853
}
17881854
}
17891855

src/liballoc/collections/btree/set.rs

+12-1
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,23 @@ use crate::collections::btree_map::{self, BTreeMap, Keys};
5656
/// println!("{}", book);
5757
/// }
5858
/// ```
59-
#[derive(Clone, Hash, PartialEq, Eq, Ord, PartialOrd)]
59+
#[derive(Hash, PartialEq, Eq, Ord, PartialOrd)]
6060
#[stable(feature = "rust1", since = "1.0.0")]
6161
pub struct BTreeSet<T> {
6262
map: BTreeMap<T, ()>,
6363
}
6464

65+
#[stable(feature = "rust1", since = "1.0.0")]
66+
impl<T: Clone> Clone for BTreeSet<T> {
67+
fn clone(&self) -> Self {
68+
BTreeSet { map: self.map.clone() }
69+
}
70+
71+
fn clone_from(&mut self, other: &Self) {
72+
self.map.clone_from(&other.map);
73+
}
74+
}
75+
6576
/// An iterator over the items of a `BTreeSet`.
6677
///
6778
/// This `struct` is created by the [`iter`] method on [`BTreeSet`].

src/liballoc/tests/btree/map.rs

+20
Original file line numberDiff line numberDiff line change
@@ -785,6 +785,26 @@ fn test_clone() {
785785
}
786786
}
787787

788+
#[test]
789+
fn test_clone_from() {
790+
let mut map1 = BTreeMap::new();
791+
let size = 30;
792+
793+
for i in 0..size {
794+
let mut map2 = BTreeMap::new();
795+
for j in 0..i {
796+
let mut map1_copy = map2.clone();
797+
map1_copy.clone_from(&map1);
798+
assert_eq!(map1_copy, map1);
799+
let mut map2_copy = map1.clone();
800+
map2_copy.clone_from(&map2);
801+
assert_eq!(map2_copy, map2);
802+
map2.insert(100 * j + 1, 2 * j + 1);
803+
}
804+
map1.insert(i, 10 * i);
805+
}
806+
}
807+
788808
#[test]
789809
#[allow(dead_code)]
790810
fn test_variance() {

0 commit comments

Comments
 (0)