{str|slice}::strip_circumfix (original) (raw)

Proposal

impl str { pub fn strip_circumfix<P: Pattern, S: Pattern>(&self, prefix: P, suffix: S) -> Option<&str> where for<'a> S::Searcher<'a>: ReverseSearcher<'a>;

// possibly, also...
pub fn trim_circumfix<P: Pattern, S: Pattern>(&self, prefix: P, suffix: S) -> &str
where
    for<'a> P::Searcher<'a>: ReverseSearcher<'a>;

}

impl slice { // same as for str }

Problem statement

I've written and seen a lot of code that looks like one of these:

if let Some(a) = a.strip_prefix('<') && let Some(a) = a.strip_suffix('>') {}

or

let a = a.strip_prefix('<').and_then(|a| a.strip_suffix('>'));

and IMHO it would be nice to have a more concise way to express this in the std.

Motivating examples or use cases

Here are a few examples from the rust-lang org that I've gathered from a very, very quick search. I'm sure there are endless examples in the wild that can be found with more advanced grepping:

https://github.com/rust-lang/cargo/blob/40076eaa5c48fd793d583df2647b25fb626c14a4/crates/cargo-platform/src/lib.rs#L166
https://github.com/rust-lang/team/blob/0a2b13222f6afa352bc9e1118e44162f1cb9e458/rust_team_data/src/email_encryption.rs#L42-L44
https://github.com/rust-lang/rust/blob/bd4a8004c2f3b73795cb4c03bf8e7634e4d89677/compiler/rustc_metadata/src/errors.rs#L254-L255

Solution sketch

Basically:

pub fn strip_circumfix<P: Pattern, S: Suffix>(&self, prefix: P, suffix: S) -> Option<&str> where for<'a> S::Searcher<'a>: ReverseSearcher<'a> { self.strip_prefix(prefix)?.strip_suffix(suffix) }

Alternatives

I think the obvious alternative would be to not add this API and keep on calling strip_prefix and strip_suffix separately, but seeing as this usage is quite widespread, I think that it's definitely something that could go in the std.

What happens now?

This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.

Possible responses

The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):

Second, if there's a concrete solution: