Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: Change return type of str::replace to MaybeOwned to avoid a copy #33

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions active/0000-str-replace-maybeowned.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
- Start Date: 2014-04-04
- RFC PR #:
- Rust Issue #:

# Summary

Strings have a `fn replace(&self, from: &str, to: &str) -> ~str` method.
The return value type could be changed to `MaybeOwned`.

# Motivation

When `from` does not appear at all in `self`, the return value equals `self`.
This is an allocation and a copy that are not strictly necessary.
With a `MaybeOwned` return value type, we could just return a slice in this case.

# Drawbacks

The API becomes more complex.
For example, multiple `.replace()` calls can not be chained anymore
without adding `.as_slice()` calls in-between.
This could be addressed by implementing string methods for `MaybeOwned`.

# Detailed design

The `MaybeOwned` type already exists in `std::str`
and is used for the return value of `std::str::from_utf8_lossy`.
It is either a slice or an owned string.

The change itself is easy enough
(see my [work-in-progress branch](https://github.com/SimonSapin/rust/compare/str-replace-maybeowned)),
but see Unresolved questions.

# Alternatives

Status quo: keep `~str` as the return value type of `replace()` for simplicity,
and accept the cost on unnecessary allocations and copies.

# Unresolved questions

The compiler uses `replace()`.
How can this change be made without breaking bootstraping?