@@ -135,7 +135,7 @@ impl<K: TotalOrd, V> Map<K, V> for TreeMap<K, V> {
135135 mutate_values ( & mut self . root , f) ;
136136 }
137137
138- /// Return the value corresponding to the key in the map
138+ /// Return a reference to the value corresponding to the key
139139 fn find ( & self , key : & K ) -> Option < & ' self V > {
140140 let mut current: & ' self Option < ~TreeNode < K , V > > = & self . root ;
141141 loop {
@@ -152,6 +152,12 @@ impl<K: TotalOrd, V> Map<K, V> for TreeMap<K, V> {
152152 }
153153 }
154154
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+
155161 /// Insert a key-value pair into the map. An existing value for a
156162 /// key is replaced by the new value. Return true if the key did
157163 /// not already exist in the map.
@@ -584,8 +590,20 @@ fn split<K: TotalOrd, V>(node: &mut ~TreeNode<K, V>) {
584590 }
585591}
586592
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 {
589607 match * node {
590608 Some ( ref mut save) => {
591609 match key. cmp ( & save. key ) {
@@ -716,6 +734,19 @@ mod test_treemap {
716734 fail_unless ! ( m. find( & 2 ) == None ) ;
717735 }
718736
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+
719750 #[ test]
720751 fn insert_replace ( ) {
721752 let mut m = TreeMap :: new ( ) ;
0 commit comments