Skip to content

Commit

Permalink
Use Vec to implement the Events iterators
Browse files Browse the repository at this point in the history
Using `vec::IntoIter` is much simpler than a deeply nested `Chain`,
compiling faster and avoiding the deeper recursion limit reported in
[rust#71359](rust-lang/rust#71359).
  • Loading branch information
cuviper committed Apr 22, 2020
1 parent e65a960 commit e753516
Showing 1 changed file with 18 additions and 22 deletions.
40 changes: 18 additions & 22 deletions typed-html/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
use crate::OutputType;
use htmlescape::encode_attribute;
use std::fmt::{Display, Error, Formatter};
use std::iter;

/// Trait for event handlers.
pub trait EventHandler<T: OutputType + Send, E: Send> {
Expand Down Expand Up @@ -34,41 +33,38 @@ macro_rules! declare_events_struct {

impl<T: Send> Events<T> {
pub fn iter(&self) -> impl Iterator<Item = (&'static str, &T)> {
iter::empty()
let mut vec = Vec::new();
$(
.chain(
self.$name.iter()
.map(|value| (stringify!($name), value))
)
if let Some(ref value) = self.$name {
vec.push((stringify!($name), value));
}
)*
vec.into_iter()
}

pub fn iter_mut(&mut self) -> impl Iterator<Item = (&'static str, &mut T)> {
iter::empty()
let mut vec = Vec::new();
$(
.chain(
self.$name.iter_mut()
.map(|value| (stringify!($name), value))
)
if let Some(ref mut value) = self.$name {
vec.push((stringify!($name), value));
}
)*
vec.into_iter()
}
}

impl<T: 'static + Send> IntoIterator for Events<T> {
type Item = (&'static str, T);
type IntoIter = Box<dyn Iterator<Item = Self::Item>>;

fn into_iter(mut self) -> Self::IntoIter {
Box::new(
iter::empty()
$(
.chain(
iter::once(self.$name.take())
.filter(Option::is_some)
.map(|value| (stringify!($name), value.unwrap()))
)
)*
)
fn into_iter(self) -> Self::IntoIter {
let mut vec = Vec::new();
$(
if let Some(value) = self.$name {
vec.push((stringify!($name), value));
}
)*
Box::new(vec.into_iter())
}
}

Expand Down

0 comments on commit e753516

Please sign in to comment.