From 10277d739cae2b98b6629b52c64664bb2975e366 Mon Sep 17 00:00:00 2001 From: yossyJ <28825627+yossyJ@users.noreply.github.com> Date: Mon, 7 Jan 2019 22:37:23 +0900 Subject: Fix loop.last --- askama_shared/src/helpers/mod.rs | 59 ++++++++++++++++++++-------------------- 1 file changed, 30 insertions(+), 29 deletions(-) (limited to 'askama_shared') diff --git a/askama_shared/src/helpers/mod.rs b/askama_shared/src/helpers/mod.rs index 1a3fd7b..87316fd 100644 --- a/askama_shared/src/helpers/mod.rs +++ b/askama_shared/src/helpers/mod.rs @@ -1,48 +1,49 @@ +use std::iter::Enumerate; use std::iter::Peekable; -pub struct Enumerate +pub struct TemplateLoop where I: Iterator, { - iter: Peekable, - count: usize, + iter: Peekable>, } -impl Iterator for Enumerate +impl TemplateLoop where I: Iterator, { - type Item = (usize, bool, ::Item); - #[inline] - fn next(&mut self) -> Option<(usize, bool, ::Item)> { - self.iter.next().map(|a| { - let last = self.iter.peek().is_none(); - let ret = (self.count, last, a); - // Possible undefined overflow. - self.count += 1; - ret - }) - } - - #[inline] - fn size_hint(&self) -> (usize, Option) { - self.iter.size_hint() - } - - #[inline] - fn count(self) -> usize { - self.iter.count() + pub fn new(iter: I) -> Self { + TemplateLoop { + iter: iter.enumerate().peekable(), + } } } -#[inline] -pub fn enumerate(iter: I) -> Enumerate +impl Iterator for TemplateLoop where I: Iterator, { - Enumerate { - iter: iter.peekable(), - count: 0, + type Item = (::Item, LoopItem); + + #[inline] + fn next(&mut self) -> Option<(::Item, LoopItem)> { + self.iter.next().map(|(index, item)| { + ( + item, + LoopItem { + index, + first: index == 0, + last: self.iter.peek().is_none(), + }, + ) + }) } } + +#[derive(Copy, Clone)] +pub struct LoopItem { + pub index: usize, + pub first: bool, + pub last: bool, +} -- cgit