1+ use core:: convert:: Infallible ;
12use std:: collections:: HashMap ;
23use std:: collections:: hash_map:: Entry ;
34use std:: hash:: Hash ;
@@ -9,8 +10,7 @@ use std::rc::Rc;
910/// the data is wrapped inside `Rc`.
1011///
1112/// ```
12- /// # #[cfg(feature = "code-in-doc")] {
13- /// # use askama::{Template, filters};
13+ /// # use askama::Template;
1414/// #[derive(Template)]
1515/// #[template(ext = "html", source = "{% for elem in example|unique %}{{ elem }},{% endfor %}")]
1616/// struct Example<'a> {
@@ -19,22 +19,23 @@ use std::rc::Rc;
1919///
2020/// assert_eq!(
2121/// Example { example: vec!["a", "b", "a", "c"] }.to_string(),
22- /// "a,b,c"
22+ /// "a,b,c, "
2323/// );
24- /// # }
2524/// ```
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 > {
2728 let mut set = HashMap :: new ( ) ;
2829
29- it. into_iter ( ) . filter_map ( move |elem| {
30+ Ok ( it. into_iter ( ) . filter_map ( move |elem| {
3031 // To prevent cloning the data, we need to use `Rc`, like that we can clone `elem` as
3132 // key of the `HashSet` and return it.
3233 if let Entry :: Vacant ( entry) = set. entry ( Rc :: new ( elem) ) {
3334 Some ( Rc :: clone ( entry. insert_entry ( ( ) ) . key ( ) ) )
3435 } else {
3536 None
3637 }
37- } )
38+ } ) )
3839}
3940
4041#[ cfg( test) ]
@@ -47,15 +48,15 @@ mod test {
4748 #[ test]
4849 fn test_unique ( ) {
4950 assert_eq ! (
50- unique( [ "a" , "b" , "a" , "c" ] ) . collect:: <Vec <_>>( ) ,
51+ unique( [ "a" , "b" , "a" , "c" ] ) . unwrap ( ) . collect:: <Vec <_>>( ) ,
5152 vec![ Rc :: new( "a" ) , Rc :: new( "b" ) , Rc :: new( "c" ) ]
5253 ) ;
5354 assert_eq ! (
54- unique( [ 1 , 1 , 1 , 2 , 1 ] ) . collect:: <Vec <_>>( ) ,
55+ unique( [ 1 , 1 , 1 , 2 , 1 ] ) . unwrap ( ) . collect:: <Vec <_>>( ) ,
5556 vec![ Rc :: new( 1 ) , Rc :: new( 2 ) ]
5657 ) ;
5758 assert_eq ! (
58- unique( "hello" . chars( ) ) . collect:: <Vec <_>>( ) ,
59+ unique( "hello" . chars( ) ) . unwrap ( ) . collect:: <Vec <_>>( ) ,
5960 vec![ Rc :: new( 'h' ) , Rc :: new( 'e' ) , Rc :: new( 'l' ) , Rc :: new( 'o' ) ]
6061 ) ;
6162 }
0 commit comments