In-place String::replace_first and String::replace_last (original) (raw)

Proposal

Problem statement

When replacing a substring a single time in a string, currently we can use str::replacen(haystack, needle, replacement, 1). However, this returns a newly allocated String, which may be inefficient if our original haystack was already in a String, and we are intending to overwrite it with the newly created String. In such a case, one can manually find the matched range of the needle in the haystack, and then use String::replace_range to replace the needle with the replacement in-place.

fn replace_first(haystack: &mut String, needle: &str, replacement: &str) { let range = match haystack.match_indices(needle).next() { Some((start, match_str)) => start..start + match_str.len(), None => return, }; haystack.replace_range(range, replacement); }

Additionally, though this cannot be done with replacen, you can similarly replace the last instance of a pattern by using rmatch_indices instead of match_indices.

Motivating examples or use cases

// adapted from https://github.com/rust-lang/rust/blob/master/src/tools/clippy/clippy_lints/src/unit_types/unit_arg.rs#L169 let call_snippet_with_replacements = args_snippets .iter() .fold(call_snippet.to_owned(), |acc, arg| acc.replacen(arg.as_ref(), "()", 1)); // each iteration makes a new allocation // could be let mut call_snippet_with_replacements = call_snippet.to_owned(); for arg in args_snippets { call_snippet_with_replacements.replace_first(arg.as_ref(), "()"); }

// adapted from https://github.com/cross-rs/cross/blob/main/xtask/src/crosstool.rs#L339-341 contents = contents .replacen("%CT_GCC_V%", &ct_gcc_v, 1) // this makes a new allocation .replacen("%CT_GCC%", &ct_gcc, 1); // this makes a new allocation // could instead be contents.replace_first("%CT_GCC_V%", &ct_gcc_v); // these avoid making a new allocation if possible contents.replace_first("%CT_GCC%", &ct_gcc);

// adapted from https://github.com/rust-lang/rust-clippy/blob/master/clippy_utils/src/sugg.rs#L869 let sugg = format!("{}{end_snip}", self.suggestion_start); if self.closure_arg_is_type_annotated_double_ref { sugg.replacen('&', "", 1) } else { sugg } // could be let mut sugg = format!("{}{end_snip}", self.suggestion_start); if self.closure_arg_is_type_annotated_double_ref { sugg.replace_first('&', ""); } sugg

Other places with something essentially equivalent to string = string.replacen(pattern, replacement, 1);

Solution sketch

// in alloc:🧵:String impl String { pub fn replace_first<P: Pattern>(&mut self, pattern: P, replacement: &str); pub fn replace_last<P: Pattern>(&mut self, pattern: P, replacement: &str) where for<'a> P::Searcher<'a>: ReverseSearcher<'a>; }

Alternatives

Users could use the more general str::replacen if allocation is not a bottleneck, or if the needle and replacement are not the same length and copying the haystack to a new allocation is faster than shuffling data around in one allocation.

Users could implement these manually in terms of existing String/str APIs (the implementations in rust-lang/rust#134316 use only the existing safe, stable APIs str::(r)match_indices and String::replace_range).

These could be fn(self) -> Self instead of fn(&mut self). This would make it difficult to perform on a mutably borrowed String: *string = std::mem::take(string).replace_first(...); vs string.replace_first(...);

These could be fn(&mut self) -> &mut Self to allow chaining multiple calls, but this might be less clear that it does not return a new String allocation.

The method names could include in_place or similar, to distinguish them from replace/replacen methods on str that are not in-place. There is already String::replace_range though, that is in-place but does not explicitly indicate this in its name.

@tgross35 mentioned on the implementation PR that it would make sense for there to also be an in-place str::replace alternative. If these are named replace_first_in_place, that would match nicely with a possible String::replace_in_place and/or String::replacen_in_place that do what str::replace/str::replacen do, but in-place.

Implementation PR: rust-lang/rust#134316

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: