Skip to content

Commit 77777b4

Browse files
authored
Rollup merge of rust-lang#49525 - varkor:sort_by_cached_key-conversion, r=scottmcm
Use sort_by_cached_key where appropriate A follow-up to rust-lang#48639, converting various slice sorting calls to `sort_by_cached_key` when the key functions are more expensive.
2 parents ca26ef3 + e7aa139 commit 77777b4

File tree

17 files changed

+33
-34
lines changed

17 files changed

+33
-34
lines changed

src/liballoc/slice.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1400,6 +1400,7 @@ impl<T> [T] {
14001400
let sz_usize = mem::size_of::<(K, usize)>();
14011401

14021402
let len = self.len();
1403+
if len < 2 { return }
14031404
if sz_u8 < sz_u16 && len <= ( u8::MAX as usize) { return sort_by_key!( u8, self, f) }
14041405
if sz_u16 < sz_u32 && len <= (u16::MAX as usize) { return sort_by_key!(u16, self, f) }
14051406
if sz_u32 < sz_usize && len <= (u32::MAX as usize) { return sort_by_key!(u32, self, f) }

src/librustc/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
#![feature(refcell_replace_swap)]
6161
#![feature(rustc_diagnostic_macros)]
6262
#![feature(slice_patterns)]
63+
#![feature(slice_sort_by_cached_key)]
6364
#![feature(specialization)]
6465
#![feature(unboxed_closures)]
6566
#![feature(trace_macros)]

src/librustc/middle/cstore.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ pub fn used_crates(tcx: TyCtxt, prefer: LinkagePreference)
401401
.collect::<Vec<_>>();
402402
let mut ordering = tcx.postorder_cnums(LOCAL_CRATE);
403403
Lrc::make_mut(&mut ordering).reverse();
404-
libs.sort_by_key(|&(a, _)| {
404+
libs.sort_by_cached_key(|&(a, _)| {
405405
ordering.iter().position(|x| *x == a)
406406
});
407407
libs

src/librustc_driver/lib.rs

+3-8
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#![cfg_attr(unix, feature(libc))]
2323
#![feature(quote)]
2424
#![feature(rustc_diagnostic_macros)]
25+
#![feature(slice_sort_by_cached_key)]
2526
#![feature(set_stdio)]
2627
#![feature(rustc_stack_internals)]
2728

@@ -82,7 +83,6 @@ use rustc_trans_utils::trans_crate::TransCrate;
8283
use serialize::json::ToJson;
8384

8485
use std::any::Any;
85-
use std::cmp::Ordering::Equal;
8686
use std::cmp::max;
8787
use std::default::Default;
8888
use std::env::consts::{DLL_PREFIX, DLL_SUFFIX};
@@ -1176,13 +1176,8 @@ Available lint options:
11761176

11771177
fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> {
11781178
let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect();
1179-
lints.sort_by(|x: &&Lint, y: &&Lint| {
1180-
match x.default_level(sess).cmp(&y.default_level(sess)) {
1181-
// The sort doesn't case-fold but it's doubtful we care.
1182-
Equal => x.name.cmp(y.name),
1183-
r => r,
1184-
}
1185-
});
1179+
// The sort doesn't case-fold but it's doubtful we care.
1180+
lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name));
11861181
lints
11871182
}
11881183

src/librustc_metadata/encoder.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1414,15 +1414,15 @@ impl<'a, 'b: 'a, 'tcx: 'b> IsolatedEncoder<'a, 'b, 'tcx> {
14141414
let mut all_impls: Vec<_> = visitor.impls.into_iter().collect();
14151415

14161416
// Bring everything into deterministic order for hashing
1417-
all_impls.sort_unstable_by_key(|&(trait_def_id, _)| {
1417+
all_impls.sort_by_cached_key(|&(trait_def_id, _)| {
14181418
tcx.def_path_hash(trait_def_id)
14191419
});
14201420

14211421
let all_impls: Vec<_> = all_impls
14221422
.into_iter()
14231423
.map(|(trait_def_id, mut impls)| {
14241424
// Bring everything into deterministic order for hashing
1425-
impls.sort_unstable_by_key(|&def_index| {
1425+
impls.sort_by_cached_key(|&def_index| {
14261426
tcx.hir.definitions().def_path_hash(def_index)
14271427
});
14281428

src/librustc_metadata/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#![feature(macro_lifetime_matcher)]
2121
#![feature(quote)]
2222
#![feature(rustc_diagnostic_macros)]
23+
#![feature(slice_sort_by_cached_key)]
2324
#![feature(specialization)]
2425
#![feature(rustc_private)]
2526

src/librustc_mir/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ Rust MIR: a lowered representation of Rust. Also: an experiment!
1515
*/
1616

1717
#![feature(slice_patterns)]
18+
#![feature(slice_sort_by_cached_key)]
1819
#![feature(from_ref)]
1920
#![feature(box_patterns)]
2021
#![feature(box_syntax)]

src/librustc_mir/monomorphize/partitioning.rs

+5-7
Original file line numberDiff line numberDiff line change
@@ -112,11 +112,11 @@ use rustc::ty::{self, TyCtxt, InstanceDef};
112112
use rustc::ty::item_path::characteristic_def_id_of_type;
113113
use rustc::util::nodemap::{FxHashMap, FxHashSet};
114114
use std::collections::hash_map::Entry;
115+
use std::cmp;
115116
use syntax::ast::NodeId;
116117
use syntax::symbol::{Symbol, InternedString};
117118
use rustc::mir::mono::MonoItem;
118119
use monomorphize::item::{MonoItemExt, InstantiationMode};
119-
use core::usize;
120120

121121
pub use rustc::mir::mono::CodegenUnit;
122122

@@ -189,11 +189,9 @@ pub trait CodegenUnitExt<'tcx> {
189189
}, item.symbol_name(tcx))
190190
}
191191

192-
let items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect();
193-
let mut items : Vec<_> = items.iter()
194-
.map(|il| (il, item_sort_key(tcx, il.0))).collect();
195-
items.sort_by(|&(_, ref key1), &(_, ref key2)| key1.cmp(key2));
196-
items.into_iter().map(|(&item_linkage, _)| item_linkage).collect()
192+
let mut items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect();
193+
items.sort_by_cached_key(|&(i, _)| item_sort_key(tcx, i));
194+
items
197195
}
198196
}
199197

@@ -509,7 +507,7 @@ fn merge_codegen_units<'tcx>(initial_partitioning: &mut PreInliningPartitioning<
509507
// Merge the two smallest codegen units until the target size is reached.
510508
while codegen_units.len() > target_cgu_count {
511509
// Sort small cgus to the back
512-
codegen_units.sort_by_key(|cgu| usize::MAX - cgu.size_estimate());
510+
codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
513511
let mut smallest = codegen_units.pop().unwrap();
514512
let second_smallest = codegen_units.last_mut().unwrap();
515513

src/librustc_resolve/lib.rs

+8-9
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
html_root_url = "https://doc.rust-lang.org/nightly/")]
1414

1515
#![feature(rustc_diagnostic_macros)]
16+
#![feature(slice_sort_by_cached_key)]
1617

1718
#[macro_use]
1819
extern crate log;
@@ -1149,13 +1150,9 @@ impl<'a> ModuleData<'a> {
11491150

11501151
fn for_each_child_stable<F: FnMut(Ident, Namespace, &'a NameBinding<'a>)>(&self, mut f: F) {
11511152
let resolutions = self.resolutions.borrow();
1152-
let mut resolutions = resolutions.iter().map(|(&(ident, ns), &resolution)| {
1153-
// Pre-compute keys for sorting
1154-
(ident.name.as_str(), ns, ident, resolution)
1155-
})
1156-
.collect::<Vec<_>>();
1157-
resolutions.sort_unstable_by_key(|&(str, ns, ..)| (str, ns));
1158-
for &(_, ns, ident, resolution) in resolutions.iter() {
1153+
let mut resolutions = resolutions.iter().collect::<Vec<_>>();
1154+
resolutions.sort_by_cached_key(|&(&(ident, ns), _)| (ident.name.as_str(), ns));
1155+
for &(&(ident, ns), &resolution) in resolutions.iter() {
11591156
resolution.borrow().binding.map(|binding| f(ident, ns, binding));
11601157
}
11611158
}
@@ -3340,7 +3337,9 @@ impl<'a> Resolver<'a> {
33403337
let is_mod = |def| match def { Def::Mod(..) => true, _ => false };
33413338
let mut candidates =
33423339
self.lookup_import_candidates(name, TypeNS, is_mod);
3343-
candidates.sort_by_key(|c| (c.path.segments.len(), c.path.to_string()));
3340+
candidates.sort_by_cached_key(|c| {
3341+
(c.path.segments.len(), c.path.to_string())
3342+
});
33443343
if let Some(candidate) = candidates.get(0) {
33453344
format!("Did you mean `{}`?", candidate.path)
33463345
} else {
@@ -3578,7 +3577,7 @@ impl<'a> Resolver<'a> {
35783577

35793578
let name = path[path.len() - 1].name;
35803579
// Make sure error reporting is deterministic.
3581-
names.sort_by_key(|name| name.as_str());
3580+
names.sort_by_cached_key(|name| name.as_str());
35823581
match find_best_match_for_name(names.iter(), &name.as_str(), None) {
35833582
Some(found) if found != name => Some(found),
35843583
_ => None,

src/librustc_trans/base.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,8 @@ use std::ffi::CString;
8282
use std::str;
8383
use std::sync::Arc;
8484
use std::time::{Instant, Duration};
85-
use std::{i32, usize};
85+
use std::i32;
86+
use std::cmp;
8687
use std::sync::mpsc;
8788
use syntax_pos::Span;
8889
use syntax_pos::symbol::InternedString;
@@ -830,7 +831,7 @@ pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
830831
// a bit more efficiently.
831832
let codegen_units = {
832833
let mut codegen_units = codegen_units;
833-
codegen_units.sort_by_key(|cgu| usize::MAX - cgu.size_estimate());
834+
codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
834835
codegen_units
835836
};
836837

src/librustc_trans/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#![feature(libc)]
2727
#![feature(quote)]
2828
#![feature(rustc_diagnostic_macros)]
29+
#![feature(slice_sort_by_cached_key)]
2930
#![feature(optin_builtin_traits)]
3031
#![feature(inclusive_range_fields)]
3132
#![feature(underscore_lifetimes)]

src/librustc_typeck/check/method/probe.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -799,7 +799,7 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
799799
.collect();
800800

801801
// sort them by the name so we have a stable result
802-
names.sort_by_key(|n| n.as_str());
802+
names.sort_by_cached_key(|n| n.as_str());
803803
names
804804
}
805805

src/librustc_typeck/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ This API is completely unstable and subject to change.
8181
#![feature(refcell_replace_swap)]
8282
#![feature(rustc_diagnostic_macros)]
8383
#![feature(slice_patterns)]
84+
#![feature(slice_sort_by_cached_key)]
8485
#![feature(dyn_trait)]
8586

8687
#[macro_use] extern crate log;

src/librustdoc/clean/auto_trait.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -1437,9 +1437,7 @@ impl<'a, 'tcx, 'rcx> AutoTraitFinder<'a, 'tcx, 'rcx> {
14371437
// involved (impls rarely have more than a few bounds) means that it
14381438
// shouldn't matter in practice.
14391439
fn unstable_debug_sort<T: Debug>(&self, vec: &mut Vec<T>) {
1440-
vec.sort_unstable_by(|first, second| {
1441-
format!("{:?}", first).cmp(&format!("{:?}", second))
1442-
});
1440+
vec.sort_by_cached_key(|x| format!("{:?}", x))
14431441
}
14441442

14451443
fn is_fn_ty(&self, tcx: &TyCtxt, ty: &Type) -> bool {

src/librustdoc/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#![feature(box_syntax)]
2020
#![feature(fs_read_write)]
2121
#![feature(set_stdio)]
22+
#![feature(slice_sort_by_cached_key)]
2223
#![feature(test)]
2324
#![feature(unicode)]
2425
#![feature(vec_remove_item)]

src/libsyntax/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
#![feature(unicode)]
2323
#![feature(rustc_diagnostic_macros)]
24+
#![feature(slice_sort_by_cached_key)]
2425
#![feature(non_exhaustive)]
2526
#![feature(const_atomic_usize_new)]
2627
#![feature(rustc_attrs)]

src/libsyntax/parse/parser.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -689,7 +689,7 @@ impl<'a> Parser<'a> {
689689
.chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
690690
.chain(self.expected_tokens.iter().cloned())
691691
.collect::<Vec<_>>();
692-
expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
692+
expected.sort_by_cached_key(|x| x.to_string());
693693
expected.dedup();
694694
let expect = tokens_to_string(&expected[..]);
695695
let actual = self.this_token_to_string();

0 commit comments

Comments
 (0)