rust-lang/regex

Detect if a replacement may allocate

tgross35 opened this issue · 3 comments

Is it possible to determine whether a replacement will allocate before seeing the haystack?

Use case: I have an API where the user provides regex replacement queries to get used at a later time. They need to be used at a point where almost everything is borrowed data, so storing the whole Cow isn't very possible.

Ideally I would be able to immediately reject any replacements that could allocate, then just unwrap the borrowed cow when it's actually used. Roughly:

impl Regex {
    fn replaceme_may_allocate<'h, R: Replacer>(&self, rep: R) -> bool;
}

Which returns false if the re + rep are guaranteed to not allocate, i.e. more or less a specialized strip/trim function.

The only way allocation doesn't happen is if the regex doesn't match anything in the haystack. I'm not sure how one could know anything about that without seeing knowing something about the haystack. The only exception would be the regex that can never match anything, but such things don't tend to occur and are rarely useful.

Separately, I can't think of anything scenario where something about the replacement itself impacts whether allocation occurs.

Maybe you can say more? Perhaps there is some confusion or misunderstanding of how replacements work.

And this should probably be a discussion question.

Whoops, yeah, I wasn't thinking about this right. I am more or less using replacement strings as an easy way to allow specifying a single named or unnamed capture group, but I realize there is an easier way to do that.