1
+ use core:: convert:: Infallible ;
1
2
use std:: collections:: HashMap ;
2
3
use std:: collections:: hash_map:: Entry ;
3
4
use std:: hash:: Hash ;
@@ -9,8 +10,7 @@ use std::rc::Rc;
9
10
/// the data is wrapped inside `Rc`.
10
11
///
11
12
/// ```
12
- /// # #[cfg(feature = "code-in-doc")] {
13
- /// # use askama::{Template, filters};
13
+ /// # use askama::Template;
14
14
/// #[derive(Template)]
15
15
/// #[template(ext = "html", source = "{% for elem in example|unique %}{{ elem }},{% endfor %}")]
16
16
/// struct Example<'a> {
@@ -19,22 +19,23 @@ use std::rc::Rc;
19
19
///
20
20
/// assert_eq!(
21
21
/// Example { example: vec!["a", "b", "a", "c"] }.to_string(),
22
- /// "a,b,c"
22
+ /// "a,b,c, "
23
23
/// );
24
- /// # }
25
24
/// ```
26
- pub fn unique < T : Hash + Eq > ( it : impl IntoIterator < Item = T > ) -> impl Iterator < Item = Rc < T > > {
25
+ pub fn unique < T : Hash + Eq > (
26
+ it : impl IntoIterator < Item = T > ,
27
+ ) -> Result < impl Iterator < Item = Rc < T > > , Infallible > {
27
28
let mut set = HashMap :: new ( ) ;
28
29
29
- it. into_iter ( ) . filter_map ( move |elem| {
30
+ Ok ( it. into_iter ( ) . filter_map ( move |elem| {
30
31
// To prevent cloning the data, we need to use `Rc`, like that we can clone `elem` as
31
32
// key of the `HashSet` and return it.
32
33
if let Entry :: Vacant ( entry) = set. entry ( Rc :: new ( elem) ) {
33
34
Some ( Rc :: clone ( entry. insert_entry ( ( ) ) . key ( ) ) )
34
35
} else {
35
36
None
36
37
}
37
- } )
38
+ } ) )
38
39
}
39
40
40
41
#[ cfg( test) ]
@@ -47,15 +48,15 @@ mod test {
47
48
#[ test]
48
49
fn test_unique ( ) {
49
50
assert_eq ! (
50
- unique( [ "a" , "b" , "a" , "c" ] ) . collect:: <Vec <_>>( ) ,
51
+ unique( [ "a" , "b" , "a" , "c" ] ) . unwrap ( ) . collect:: <Vec <_>>( ) ,
51
52
vec![ Rc :: new( "a" ) , Rc :: new( "b" ) , Rc :: new( "c" ) ]
52
53
) ;
53
54
assert_eq ! (
54
- unique( [ 1 , 1 , 1 , 2 , 1 ] ) . collect:: <Vec <_>>( ) ,
55
+ unique( [ 1 , 1 , 1 , 2 , 1 ] ) . unwrap ( ) . collect:: <Vec <_>>( ) ,
55
56
vec![ Rc :: new( 1 ) , Rc :: new( 2 ) ]
56
57
) ;
57
58
assert_eq ! (
58
- unique( "hello" . chars( ) ) . collect:: <Vec <_>>( ) ,
59
+ unique( "hello" . chars( ) ) . unwrap ( ) . collect:: <Vec <_>>( ) ,
59
60
vec![ Rc :: new( 'h' ) , Rc :: new( 'e' ) , Rc :: new( 'l' ) , Rc :: new( 'o' ) ]
60
61
) ;
61
62
}
0 commit comments