@@ -135,7 +135,7 @@ impl<K: TotalOrd, V> Map<K, V> for TreeMap<K, V> {
135
135
mutate_values ( & mut self . root , f) ;
136
136
}
137
137
138
- /// Return the value corresponding to the key in the map
138
+ /// Return a reference to the value corresponding to the key
139
139
fn find ( & self , key : & K ) -> Option < & ' self V > {
140
140
let mut current: & ' self Option < ~TreeNode < K , V > > = & self . root ;
141
141
loop {
@@ -152,6 +152,12 @@ impl<K: TotalOrd, V> Map<K, V> for TreeMap<K, V> {
152
152
}
153
153
}
154
154
155
+ /// Return a mutable reference to the value corresponding to the key
156
+ #[ inline( always) ]
157
+ fn find_mut ( & mut self , key : & K ) -> Option < & ' self mut V > {
158
+ find_mut ( & mut self . root , key)
159
+ }
160
+
155
161
/// Insert a key-value pair into the map. An existing value for a
156
162
/// key is replaced by the new value. Return true if the key did
157
163
/// not already exist in the map.
@@ -584,8 +590,20 @@ fn split<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>) {
584
590
}
585
591
}
586
592
587
- fn insert < K : TotalOrd , V > ( node : & mut Option < ~TreeNode < K , V > > , key : K ,
588
- value : V ) -> bool {
593
+ fn find_mut < K : TotalOrd , V > ( node : & ' r mut Option < ~TreeNode < K , V > > , key : & K ) -> Option < & ' r mut V > {
594
+ match * node {
595
+ Some ( ref mut x) => {
596
+ match key. cmp ( & x. key ) {
597
+ Less => find_mut ( & mut x. left , key) ,
598
+ Greater => find_mut ( & mut x. right , key) ,
599
+ Equal => Some ( & mut x. value ) ,
600
+ }
601
+ }
602
+ None => None
603
+ }
604
+ }
605
+
606
+ fn insert < K : TotalOrd , V > ( node : & mut Option < ~TreeNode < K , V > > , key : K , value : V ) -> bool {
589
607
match * node {
590
608
Some ( ref mut save) => {
591
609
match key. cmp ( & save. key ) {
@@ -716,6 +734,19 @@ mod test_treemap {
716
734
fail_unless ! ( m. find( & 2 ) == None ) ;
717
735
}
718
736
737
+ #[ test]
738
+ fn test_find_mut ( ) {
739
+ let mut m = TreeMap :: new ( ) ;
740
+ fail_unless ! ( m. insert( 1 , 12 ) ) ;
741
+ fail_unless ! ( m. insert( 2 , 8 ) ) ;
742
+ fail_unless ! ( m. insert( 5 , 14 ) ) ;
743
+ let new = 100 ;
744
+ match m. find_mut ( & 5 ) {
745
+ None => fail ! ( ) , Some ( x) => * x = new
746
+ }
747
+ assert_eq ! ( m. find( & 5 ) , Some ( & new) ) ;
748
+ }
749
+
719
750
#[ test]
720
751
fn insert_replace ( ) {
721
752
let mut m = TreeMap :: new ( ) ;
0 commit comments