Skip to content

Commit

Permalink
Merge pull request #1667 from dtolnay/punctuatedfold
Browse files Browse the repository at this point in the history
Optimize punctuated::fold
  • Loading branch information
dtolnay authored May 19, 2024
2 parents 3dfacc1 + 9d95cab commit 6e20bb8
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 53 deletions.
2 changes: 1 addition & 1 deletion codegen/src/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ fn visit(
let Type::Syn(t) = t else { unimplemented!() };
let method = method_name(t);
Some(quote! {
FoldHelper::lift(#name, f, F::#method)
crate::punctuated::fold(#name, f, F::#method)
})
}
Type::Option(t) => {
Expand Down
74 changes: 39 additions & 35 deletions src/gen/fold.rs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 0 additions & 17 deletions src/gen_helper.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#[cfg(feature = "fold")]
pub(crate) mod fold {
use crate::fold::Fold;
use crate::punctuated::{Pair, Punctuated};

pub(crate) trait FoldHelper {
type Item;
Expand All @@ -21,20 +20,4 @@ pub(crate) mod fold {
self.into_iter().map(|it| f(fold, it)).collect()
}
}

impl<T, P> FoldHelper for Punctuated<T, P> {
type Item = T;
fn lift<V, F>(self, fold: &mut V, mut f: F) -> Self
where
V: Fold + ?Sized,
F: FnMut(&mut V, Self::Item) -> Self::Item,
{
self.into_pairs()
.map(|pair| match pair {
Pair::Punctuated(t, p) => Pair::Punctuated(f(fold, t), p),
Pair::End(t) => Pair::End(f(fold, t)),
})
.collect()
}
}
}
23 changes: 23 additions & 0 deletions src/punctuated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1073,6 +1073,29 @@ impl<T, P> IndexMut<usize> for Punctuated<T, P> {
}
}

#[cfg(all(feature = "fold", any(feature = "full", feature = "derive")))]
pub(crate) fn fold<T, P, V, F>(
punctuated: Punctuated<T, P>,
fold: &mut V,
mut f: F,
) -> Punctuated<T, P>
where
V: ?Sized,
F: FnMut(&mut V, T) -> T,
{
Punctuated {
inner: punctuated
.inner
.into_iter()
.map(|(t, p)| (f(fold, t), p))
.collect(),
last: match punctuated.last {
Some(t) => Some(Box::new(f(fold, *t))),
None => None,
},
}
}

#[cfg(feature = "printing")]
mod printing {
use crate::punctuated::{Pair, Punctuated};
Expand Down

0 comments on commit 6e20bb8

Please sign in to comment.