@@ -15,6 +15,15 @@ pub trait Map {
15
15
type Value ;
16
16
fn insert ( & mut self , key : Self :: Key , value : Self :: Value ) -> Option < Self :: Value > ;
17
17
fn remove ( & mut self , key : & Self :: Key ) -> Option < Self :: Value > ;
18
+ fn aggregate < T , F > ( & mut self , key : Self :: Key , t : T , mut operation : F )
19
+ where
20
+ F : FnMut ( Option < Self :: Value > , & Self :: Key , T ) -> Option < Self :: Value > ,
21
+ {
22
+ let opt_value = self . remove ( & key) ;
23
+ if let Some ( value) = operation ( opt_value, & key, t) {
24
+ self . insert ( key, value) ;
25
+ }
26
+ }
18
27
fn entry_or_default ( & mut self , key : Self :: Key ) -> & mut Self :: Value
19
28
where
20
29
Self :: Value : Default ;
81
90
let index = self . iter ( ) . position ( |( k, _) | k == key) ?;
82
91
Some ( self . swap_remove ( index) . 1 )
83
92
}
93
+ fn aggregate < T , F > ( & mut self , key : K , t : T , mut operation : F )
94
+ where
95
+ F : FnMut ( Option < V > , & K , T ) -> Option < V > ,
96
+ {
97
+ let opt_value = Map :: remove ( self , & key) ;
98
+ if let Some ( value) = operation ( opt_value, & key, t) {
99
+ // The key was removed so a single push is enough to insert it back.
100
+ self . push ( ( key, value) ) ;
101
+ }
102
+ }
84
103
fn entry_or_default ( & mut self , key : K ) -> & mut V
85
104
where
86
105
V : Default ,
0 commit comments