1
1
use std:: borrow:: Borrow ;
2
+ use std:: fmt:: Debug ;
2
3
use std:: iter:: FromIterator ;
3
4
use std:: slice:: Iter ;
4
5
use std:: vec:: IntoIter ;
@@ -12,7 +13,8 @@ pub struct VecMap<K, V>(Vec<(K, V)>);
12
13
13
14
impl < K , V > VecMap < K , V >
14
15
where
15
- K : PartialEq ,
16
+ K : Debug + PartialEq ,
17
+ V : Debug ,
16
18
{
17
19
pub fn new ( ) -> Self {
18
20
VecMap ( Default :: default ( ) )
@@ -37,14 +39,31 @@ where
37
39
self . 0 . iter ( ) . find ( |( key, _) | k == key. borrow ( ) ) . map ( |elem| & elem. 1 )
38
40
}
39
41
40
- /// Returns the value corresponding to the supplied predicate filter.
42
+ /// Returns the any value corresponding to the supplied predicate filter.
41
43
///
42
44
/// The supplied predicate will be applied to each (key, value) pair and it will return a
43
45
/// 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 > {
45
47
self . 0 . iter ( ) . find ( |kv| predicate ( kv) ) . map ( |elem| & elem. 1 )
46
48
}
47
49
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
+
48
67
/// Returns `true` if the map contains a value for the specified key.
49
68
///
50
69
/// 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> {
131
150
}
132
151
}
133
152
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 > {
135
154
fn extend < I : IntoIterator < Item = ( K , V ) > > ( & mut self , iter : I ) {
136
155
for ( k, v) in iter {
137
156
self . insert ( k, v) ;
0 commit comments