Skip to content

ACP: Add std::string::String::replace_and_count and/or replace_with #344

@alpaylan

Description

@alpaylan

Proposal

Add std::string::String::replace_and_count and/or replace_with and/or replace_and.

Problem statement

Today, standart library String replacement method does not (1) creating any type of telemetric information such as the number of replacements, or (2) allow any type of dynamic computed pattern.

For (1), such telemetry information is useful for logging or validation purposes; for (2), dynamic computed patterns allow for more complex transformation now possible str::replace today.

Motivating examples or use cases

Collection Use Case 1: Checking if count > 0 for source string validation. This is currently only achievable by doing a 2nd pass over the string, resulting in 2 full traversals in the worse case.

Collection Use Case 2: Logging the count/position of the first match/positions of all matches.

Dynamic Pattern Use Case 1: Randomizing certain patterns within the string for anonymization purposes.

Dynamic Pattern Use Case 2: Tagging each replacement with a count number.

Solution sketch

I propose 3 candidate API's.

API 1:(replace_and_count) This API changes the return type of the replace function into (String, usize) from the previous String, the second parameter being the number of changes to the original variable.

API 2:(replace_with) This API receives an FnMut that will return a &str instead of the current &str and uses that. This API can be used for dynamic patterns.

API 3:(replace_and) This API receives an additional FnMut that does not return a value for executing side effects, such as counting.

Alternatives

In the Rust Internals Forum discussion where I posted the Pre-RFC, there was also the replace_iter suggestion that I did not fully understand.

Links and related work

Rust Internals Discussion: https://internals.rust-lang.org/t/pre-rfc-std-replace-and-count/20320/7

A Reddit Question: https://www.reddit.com/r/rust/comments/m39ybn/how_to_count_string_replacements_idiomatically/

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions