bon_macros/util/
punctuated.rs

1use crate::util::prelude::*;
2use syn::punctuated::Punctuated;
3
4pub(crate) trait PunctuatedExt<T, P> {
5    /// Remove all alements from the [`Punctuated`] that do not satisfy the predicate.
6    /// Also bail on the first error that the predicate returns.
7    fn try_retain_mut(&mut self, f: impl FnMut(&mut T) -> Result<bool>) -> Result;
8}
9
10impl<T, P> PunctuatedExt<T, P> for Punctuated<T, P>
11where
12    P: Default,
13{
14    fn try_retain_mut(&mut self, mut try_predicate: impl FnMut(&mut T) -> Result<bool>) -> Result {
15        // Unforunatelly, there is no builtin `retain` or `remove` in `Punctuated`
16        // so we just re-create it from scratch.
17        for mut pair in std::mem::take(self).into_pairs() {
18            if try_predicate(pair.value_mut())? {
19                self.extend([pair]);
20            }
21        }
22        Ok(())
23    }
24}