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

add insert to Option #77392

Merged
merged 7 commits into from
Oct 24, 2020
Merged

add insert to Option #77392

merged 7 commits into from
Oct 24, 2020

Conversation

Canop
Copy link
Contributor

@Canop Canop commented Oct 1, 2020

This removes a cause of unwrap and code complexity.

This allows replacing

option_value = Some(build());
option_value.as_mut().unwrap()

with

option_value.insert(build())

It's also useful in contexts not requiring the mutability of the reference.

Here's a typical cache example:

let checked_cache = cache.as_ref().filter(|e| e.is_valid());
let content = match checked_cache {
	Some(e) => &e.content,
	None => {
	    cache = Some(compute_cache_entry());
	    // unwrap is OK because we just filled the option
	    &cache.as_ref().unwrap().content
	}
};

It can be changed into

let checked_cache = cache.as_ref().filter(|e| e.is_valid());
let content = match checked_cache {
	Some(e) => &e.content,
	None => &cache.insert(compute_cache_entry()).content,
};

(edited: I removed insert_with)

@rust-highfive
Copy link
Collaborator

Thanks for the pull request, and welcome! The Rust team is excited to review your changes, and you should hear from @LukasKalbertodt (or someone else) soon.

If any changes to this PR are deemed necessary, please add them as extra commits. This ensures that the reviewer can see what has changed since they last reviewed the code. Due to the way GitHub handles out-of-date commits, this should also make it reasonably obvious what issues have or haven't been addressed. Large or tricky changes may require several passes of review and changes.

Please see the contribution instructions for more information.

@rust-highfive rust-highfive added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Oct 1, 2020
@timvermeulen
Copy link
Contributor

timvermeulen commented Oct 1, 2020

I've wanted this for a while. 👍 You could consider also changing Option::get_or_insert_with to call insert, getting rid of its unsafe block.

@Stargateur
Copy link
Contributor

Stargateur commented Oct 1, 2020

I will better use replace() naming and so naming it replace_and_get, also this add the old value as a return:

fn replace_and_get(&mut self) -> (&mut T, Option<T>)

This allow a more generic use of this feature

Current alternative to unwrap:

let checked_cache = cache.as_ref().filter(|e| e.is_valid());
let content = match checked_cache {
	Some(e) => &e.content,
	None => {
	    cache = None;
	    &checked_cache.get_or_insert_with(build).content
	}
};

@petervaro
Copy link

petervaro commented Oct 1, 2020

Thumbs up for replace_and_get or insert_and_get. The main problem though with these names is the addition of the _with part: it will look rather clunky: replace_with_and_get or insert_with_and_get which is breaking the current convention where _with is a suffix.

@Stargateur
Copy link
Contributor

@petervaro I see no reason to have with variant, cause the function will always be call.

@petervaro
Copy link

@Stargateur that's fair!

@Canop
Copy link
Contributor Author

Canop commented Oct 1, 2020

The name insert is consistent with the intent, with other collections and with get_or_insert.

The goal isn't to get the old value, using a tupple would add verbosity while there's already take when we need this value.

@Canop
Copy link
Contributor Author

Canop commented Oct 1, 2020

I agree insert_with doesn't bring a lot of value. I added it for consistency with previous functions but it could be removed.

@timvermeulen
Copy link
Contributor

I also think insert_with is probably best left out, existing methods such as Option::replace and Option::xor don't have a _with variant either because the argument is always evaluated.

@Canop Canop changed the title add insert and insert_with to Option add insert to Option Oct 1, 2020
@jyn514 jyn514 added the T-libs-api Relevant to the library API team, which will review and decide on the PR/issue. label Oct 1, 2020
library/core/src/option.rs Outdated Show resolved Hide resolved
library/core/src/option.rs Outdated Show resolved Hide resolved
library/core/src/option.rs Outdated Show resolved Hide resolved
library/core/src/option.rs Outdated Show resolved Hide resolved
library/core/src/option.rs Outdated Show resolved Hide resolved
match *self {
Some(ref mut v) => v,
match self {
Some(v) => v,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we're changing this method anyway, might as well call insert:

match self {
    Some(v) => v,
    None => self.insert(f()),
}

(GitHub didn't let me add this as a change suggestion)

@pickfire
Copy link
Contributor

pickfire commented Oct 1, 2020

Don't we already have Option::get_or_insert? Why do we need this? https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.get_or_insert have the exact same signature

pub fn get_or_insert(&mut self, v: T) -> &mut T

@jyn514 IMHO v is short and clear, please don't change it to val.

It even have similar code, I don't see why is this necessary. https://doc.rust-lang.org/stable/src/core/option.rs.html#852-861

@Canop maybe get_or_insert is what you are looking for? Or is there any other reason to create a similar function?

@Stargateur
Copy link
Contributor

@pickfire No there are not equivalent, if option is Some the feature proposed here discard previous value, get_or_insert() doesn't discard previous value but on the contrary discard the value given in parameter.

library/core/src/option.rs Outdated Show resolved Hide resolved
@Canop
Copy link
Contributor Author

Canop commented Oct 5, 2020

Question is: Should I do something, remove or add something, in order for the PR to be merged ?

@jyn514
Copy link
Member

jyn514 commented Oct 5, 2020

@Canop this is waiting on review from @LukasKalbertodt , no one who's reviewed so far is on T-libs.

@camelid camelid added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. A-result-option Area: Result and Option combinators and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Oct 23, 2020
@m-ou-se
Copy link
Member

m-ou-se commented Oct 23, 2020

Nice! (I was just looking for this method a few days ago.)

It might be good to consider some other possible names. insert matches nicely with get_or_insert, but maybe we can come up with something that makes it clearer any existing value is overwritten/dropped. But I think it's fine to unstably add it now as insert and leave the final naming decision until the stabilization PR. By then we'll have some experience using this, which might give some more ideas for a name, or confirm that the current name is good.

Can you open a tracking issue, add its number in the issue = ".." attribute, and address these two comments? 1 2

Thanks!

This removes a cause of `unwrap` and code complexity.

This allows replacing

```
option_value = Some(build());
option_value.as_mut().unwrap()
```

with

```
option_value.insert(build())
```

or

```
option_value.insert_with(build)
```

It's also useful in contexts not requiring the mutability of the reference.

Here's a typical cache example:

```
let checked_cache = cache.as_ref().filter(|e| e.is_valid());
let content = match checked_cache {
	Some(e) => &e.content,
	None => {
	    cache = Some(compute_cache_entry());
	    // unwrap is OK because we just filled the option
	    &cache.as_ref().unwrap().content
	}
};
```

It can be changed into

```
let checked_cache = cache.as_ref().filter(|e| e.is_valid());
let content = match checked_cache {
	Some(e) => &e.content,
	None => &cache.insert_with(compute_cache_entry).content,
};
```
Canop and others added 6 commits October 23, 2020 11:41
`option.insert` covers both needs anyway, `insert_with` is
redundant.
Code cleaning made according to suggestions in discussion
on PR #rust-lang#77392 impacts insert, get_or_insert and get_or_insert_with.
Co-authored-by: Mara Bos <m-ou.se@m-ou.se>
Co-authored-by: Ivan Tham <pickfire@riseup.net>
@m-ou-se

This comment has been minimized.

@Canop

This comment has been minimized.

@m-ou-se
Copy link
Member

m-ou-se commented Oct 23, 2020

Thanks for your contribution!

@bors r+ rollup

This PR is now approved and waiting in the queue to be tested more thoroughly before it gets merged. The queue is a bit long at the moment, so it might take a while before this PR is merged. After it's merged, your new function should be available (unstably, feature gated) in the next nightly Rust. Once it's been in a few releases and all questions on the tracking issue are resolved, stabilization can be proposed, which will then require approval from the majority of the libs team.

@bors
Copy link
Contributor

bors commented Oct 23, 2020

📌 Commit 216d0fe has been approved by m-ou-se

@bors bors added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Oct 23, 2020
@m-ou-se m-ou-se assigned m-ou-se and unassigned LukasKalbertodt Oct 23, 2020
bors added a commit to rust-lang-ci/rust that referenced this pull request Oct 24, 2020
…as-schievink

Rollup of 15 pull requests

Successful merges:

 - rust-lang#76649 (Add a spin loop hint for Arc::downgrade)
 - rust-lang#77392 (add `insert` to `Option`)
 - rust-lang#77716 (Revert "Allow dynamic linking for iOS/tvOS targets.")
 - rust-lang#78109 (Check for exhaustion in RangeInclusive::contains and slicing)
 - rust-lang#78198 (Simplify assert terminator only if condition evaluates to expected value)
 - rust-lang#78243 (--test-args flag description)
 - rust-lang#78249 (improve const infer error)
 - rust-lang#78250 (Document inline-const)
 - rust-lang#78264 (Add regression test for issue-77475)
 - rust-lang#78274 (Update description of Empty Enum for accuracy)
 - rust-lang#78278 (move `visit_predicate` into `TypeVisitor`)
 - rust-lang#78292 (Loop instead of recursion)
 - rust-lang#78293 (Always store Rustdoc theme when it's changed)
 - rust-lang#78300 (Make codegen coverage_context optional, and check)
 - rust-lang#78307 (Revert "Set .llvmbc and .llvmcmd sections as allocatable")

Failed merges:

r? `@ghost`
@bors bors merged commit d7c635b into rust-lang:master Oct 24, 2020
@rustbot rustbot added this to the 1.49.0 milestone Oct 24, 2020
@m-ou-se
Copy link
Member

m-ou-se commented Oct 25, 2020

This is now available in nightly Rust: https://doc.rust-lang.org/nightly/std/option/enum.Option.html#method.insert

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-result-option Area: Result and Option combinators S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.