11use std:: borrow:: Borrow ;
2+ use std:: fmt:: Debug ;
23use std:: iter:: FromIterator ;
34use std:: slice:: Iter ;
45use std:: vec:: IntoIter ;
@@ -12,7 +13,8 @@ pub struct VecMap<K, V>(Vec<(K, V)>);
1213
1314impl < K , V > VecMap < K , V >
1415where
15- K : PartialEq ,
16+ K : Debug + PartialEq ,
17+ V : Debug ,
1618{
1719 pub fn new ( ) -> Self {
1820 VecMap ( Default :: default ( ) )
@@ -37,14 +39,31 @@ where
3739 self . 0 . iter ( ) . find ( |( key, _) | k == key. borrow ( ) ) . map ( |elem| & elem. 1 )
3840 }
3941
40- /// Returns the value corresponding to the supplied predicate filter.
42+ /// Returns the any value corresponding to the supplied predicate filter.
4143 ///
4244 /// The supplied predicate will be applied to each (key, value) pair and it will return a
4345 /// reference to the values where the predicate returns `true`.
44- pub fn get_by ( & self , mut predicate : impl FnMut ( & ( K , V ) ) -> bool ) -> Option < & V > {
46+ pub fn any_value_matching ( & self , mut predicate : impl FnMut ( & ( K , V ) ) -> bool ) -> Option < & V > {
4547 self . 0 . iter ( ) . find ( |kv| predicate ( kv) ) . map ( |elem| & elem. 1 )
4648 }
4749
50+ /// Returns the value corresponding to the supplied predicate filter. It crashes if there's
51+ /// more than one matching element.
52+ ///
53+ /// The supplied predicate will be applied to each (key, value) pair and it will return a
54+ /// reference to the value where the predicate returns `true`.
55+ pub fn get_value_matching ( & self , mut predicate : impl FnMut ( & ( K , V ) ) -> bool ) -> Option < & V > {
56+ let mut filter = self . 0 . iter ( ) . filter ( |kv| predicate ( kv) ) ;
57+ let ( _, value) = filter. next ( ) ?;
58+ // This should return just one element, otherwise it's a bug
59+ assert ! (
60+ filter. next( ) . is_none( ) ,
61+ "Collection {:?} should have just one matching element" ,
62+ self
63+ ) ;
64+ Some ( value)
65+ }
66+
4867 /// Returns `true` if the map contains a value for the specified key.
4968 ///
5069 /// The key may be any borrowed form of the map's key type,
@@ -131,7 +150,7 @@ impl<K, V> IntoIterator for VecMap<K, V> {
131150 }
132151}
133152
134- impl < K : PartialEq , V > Extend < ( K , V ) > for VecMap < K , V > {
153+ impl < K : PartialEq + Debug , V : Debug > Extend < ( K , V ) > for VecMap < K , V > {
135154 fn extend < I : IntoIterator < Item = ( K , V ) > > ( & mut self , iter : I ) {
136155 for ( k, v) in iter {
137156 self . insert ( k, v) ;
0 commit comments