From a5b43c0aa2c98182a9a09940b2f6b7250e0a1b19 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 22 Apr 2025 23:04:39 +0200 Subject: [PATCH] Fix `unique` filter implementation --- askama/src/filters/std.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/askama/src/filters/std.rs b/askama/src/filters/std.rs index 2665247f..08f7912d 100644 --- a/askama/src/filters/std.rs +++ b/askama/src/filters/std.rs @@ -1,3 +1,4 @@ +use core::convert::Infallible; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::hash::Hash; @@ -9,8 +10,7 @@ use std::rc::Rc; /// the data is wrapped inside `Rc`. /// /// ``` -/// # #[cfg(feature = "code-in-doc")] { -/// # use askama::{Template, filters}; +/// # use askama::Template; /// #[derive(Template)] /// #[template(ext = "html", source = "{% for elem in example|unique %}{{ elem }},{% endfor %}")] /// struct Example<'a> { @@ -19,14 +19,15 @@ use std::rc::Rc; /// /// assert_eq!( /// Example { example: vec!["a", "b", "a", "c"] }.to_string(), -/// "a,b,c" +/// "a,b,c," /// ); -/// # } /// ``` -pub fn unique(it: impl IntoIterator) -> impl Iterator> { +pub fn unique( + it: impl IntoIterator, +) -> Result>, Infallible> { let mut set = HashMap::new(); - it.into_iter().filter_map(move |elem| { + Ok(it.into_iter().filter_map(move |elem| { // To prevent cloning the data, we need to use `Rc`, like that we can clone `elem` as // key of the `HashSet` and return it. if let Entry::Vacant(entry) = set.entry(Rc::new(elem)) { @@ -34,7 +35,7 @@ pub fn unique(it: impl IntoIterator) -> impl Iterator>(), + unique(["a", "b", "a", "c"]).unwrap().collect::>(), vec![Rc::new("a"), Rc::new("b"), Rc::new("c")] ); assert_eq!( - unique([1, 1, 1, 2, 1]).collect::>(), + unique([1, 1, 1, 2, 1]).unwrap().collect::>(), vec![Rc::new(1), Rc::new(2)] ); assert_eq!( - unique("hello".chars()).collect::>(), + unique("hello".chars()).unwrap().collect::>(), vec![Rc::new('h'), Rc::new('e'), Rc::new('l'), Rc::new('o')] ); }