Skip to content

Commit f73db82

Browse files
committed
More generic impl of Replacer for closures
Implement `Replacer` also for closures that return a type which depends on lifetime of the argument. This allows performing a no-op replacement where the closure returns the whole match, for example, without needing to clone the captured string.
1 parent 855c5c4 commit f73db82

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

src/regex/string.rs

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2371,6 +2371,22 @@ impl<'c, 'h> ExactSizeIterator for SubCaptureMatches<'c, 'h> {}
23712371

23722372
impl<'c, 'h> core::iter::FusedIterator for SubCaptureMatches<'c, 'h> {}
23732373

2374+
/// Trait alias for `FnMut` with one argument, which allows adding a bound
2375+
/// without specifying the closure's return type.
2376+
pub trait GenericFnMut1Arg<Arg>
2377+
where
2378+
Self: FnMut(Arg) -> <Self as GenericFnMut1Arg<Arg>>::Output
2379+
{
2380+
/// Return type of the closure.
2381+
type Output;
2382+
}
2383+
2384+
impl<T: ?Sized, Arg, Ret> GenericFnMut1Arg<Arg> for T
2385+
where T: FnMut(Arg) -> Ret,
2386+
{
2387+
type Output = Ret;
2388+
}
2389+
23742390
/// A trait for types that can be used to replace matches in a haystack.
23752391
///
23762392
/// In general, users of this crate shouldn't need to implement this trait,
@@ -2501,10 +2517,10 @@ impl<'a> Replacer for &'a Cow<'a, str> {
25012517
}
25022518
}
25032519

2504-
impl<F, T> Replacer for F
2520+
impl<F> Replacer for F
25052521
where
2506-
F: FnMut(&Captures<'_>) -> T,
2507-
T: AsRef<str>,
2522+
F: for<'a> GenericFnMut1Arg<&'a Captures<'a>>,
2523+
for<'a> <F as GenericFnMut1Arg<&'a Captures<'a>>>::Output: AsRef<str>,
25082524
{
25092525
fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) {
25102526
dst.push_str((*self)(caps).as_ref());

0 commit comments

Comments
 (0)