1
+ use crate :: vec:: Vec ;
1
2
use core:: borrow:: Borrow ;
2
3
use core:: cmp:: Ordering ;
3
4
use core:: fmt:: { self , Debug } ;
@@ -9,6 +10,7 @@ use core::ops::{Index, RangeBounds};
9
10
use core:: ptr;
10
11
11
12
use super :: borrow:: DormantMutRef ;
13
+ use super :: dedup_sorted_iter:: DedupSortedIter ;
12
14
use super :: navigate:: { LazyLeafRange , LeafRange } ;
13
15
use super :: node:: { self , marker, ForceResult :: * , Handle , NodeRef , Root } ;
14
16
use super :: search:: SearchResult :: * ;
@@ -1290,6 +1292,18 @@ impl<K, V> BTreeMap<K, V> {
1290
1292
pub fn into_values ( self ) -> IntoValues < K , V > {
1291
1293
IntoValues { inner : self . into_iter ( ) }
1292
1294
}
1295
+
1296
+ /// Makes a `BTreeMap` from a sorted iterator.
1297
+ pub ( crate ) fn bulk_build_from_sorted_iter < I > ( iter : I ) -> Self
1298
+ where
1299
+ K : Ord ,
1300
+ I : Iterator < Item = ( K , V ) > ,
1301
+ {
1302
+ let mut root = Root :: new ( ) ;
1303
+ let mut length = 0 ;
1304
+ root. bulk_push ( DedupSortedIter :: new ( iter) , & mut length) ;
1305
+ BTreeMap { root : Some ( root) , length }
1306
+ }
1293
1307
}
1294
1308
1295
1309
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
@@ -1914,9 +1928,15 @@ impl<K, V> FusedIterator for RangeMut<'_, K, V> {}
1914
1928
#[ stable( feature = "rust1" , since = "1.0.0" ) ]
1915
1929
impl < K : Ord , V > FromIterator < ( K , V ) > for BTreeMap < K , V > {
1916
1930
fn from_iter < T : IntoIterator < Item = ( K , V ) > > ( iter : T ) -> BTreeMap < K , V > {
1917
- let mut map = BTreeMap :: new ( ) ;
1918
- map. extend ( iter) ;
1919
- map
1931
+ let mut inputs: Vec < _ > = iter. into_iter ( ) . collect ( ) ;
1932
+
1933
+ if inputs. is_empty ( ) {
1934
+ return BTreeMap :: new ( ) ;
1935
+ }
1936
+
1937
+ // use stable sort to preserve the insertion order.
1938
+ inputs. sort_by ( |a, b| a. 0 . cmp ( & b. 0 ) ) ;
1939
+ BTreeMap :: bulk_build_from_sorted_iter ( inputs. into_iter ( ) )
1920
1940
}
1921
1941
}
1922
1942
@@ -2025,8 +2045,14 @@ impl<K: Ord, V, const N: usize> From<[(K, V); N]> for BTreeMap<K, V> {
2025
2045
/// let map2: BTreeMap<_, _> = [(1, 2), (3, 4)].into();
2026
2046
/// assert_eq!(map1, map2);
2027
2047
/// ```
2028
- fn from ( arr : [ ( K , V ) ; N ] ) -> Self {
2029
- core:: array:: IntoIter :: new ( arr) . collect ( )
2048
+ fn from ( mut arr : [ ( K , V ) ; N ] ) -> Self {
2049
+ if N == 0 {
2050
+ return BTreeMap :: new ( ) ;
2051
+ }
2052
+
2053
+ // use stable sort to preserve the insertion order.
2054
+ arr. sort_by ( |a, b| a. 0 . cmp ( & b. 0 ) ) ;
2055
+ BTreeMap :: bulk_build_from_sorted_iter ( core:: array:: IntoIter :: new ( arr) )
2030
2056
}
2031
2057
}
2032
2058
0 commit comments