@@ -499,13 +499,18 @@ impl CrateGraph {
499499 /// Extends this crate graph by adding a complete second crate
500500 /// graph and adjust the ids in the [`ProcMacroPaths`] accordingly.
501501 ///
502+ /// This will deduplicate the crates of the graph where possible.
503+ /// Note that for deduplication to fully work, `self`'s crate dependencies must be sorted by crate id.
504+ /// If the crate dependencies were sorted, the resulting graph from this `extend` call will also
505+ /// have the crate dependencies sorted.
506+ ///
502507 /// Returns a map mapping `other`'s IDs to the new IDs in `self`.
503508 pub fn extend (
504509 & mut self ,
505510 mut other : CrateGraph ,
506511 proc_macros : & mut ProcMacroPaths ,
507512 ) -> FxHashMap < CrateId , CrateId > {
508- self . sort_deps ( ) ;
513+ let m = self . len ( ) ;
509514 let topo = other. crates_in_topological_order ( ) ;
510515 let mut id_map: FxHashMap < CrateId , CrateId > = FxHashMap :: default ( ) ;
511516 for topo in topo {
@@ -514,9 +519,8 @@ impl CrateGraph {
514519 crate_data. dependencies . iter_mut ( ) . for_each ( |dep| dep. crate_id = id_map[ & dep. crate_id ] ) ;
515520 crate_data. dependencies . sort_by_key ( |dep| dep. crate_id ) ;
516521
517- let find = self . arena . iter ( ) . find ( |( _, v) | * v == crate_data) ;
518- let new_id =
519- if let Some ( ( k, _) ) = find { k } else { self . arena . alloc ( crate_data. clone ( ) ) } ;
522+ let find = self . arena . iter ( ) . take ( m) . find_map ( |( k, v) | ( v == crate_data) . then_some ( k) ) ;
523+ let new_id = find. unwrap_or_else ( || self . arena . alloc ( crate_data. clone ( ) ) ) ;
520524 id_map. insert ( topo, new_id) ;
521525 }
522526
0 commit comments