diff options
| author | Corey Farwell <coreyf@rwell.org> | 2017-02-05 09:14:42 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2017-02-05 09:14:42 -0500 |
| commit | 76e9ea73822a859815ed78c31403e15354f3c4c3 (patch) | |
| tree | 19394d3bd75d20bdbdddc3f3d9758918593c8503 | |
| parent | 49cd748a07a1a9ea443843d3b84b620350ee9655 (diff) | |
| parent | 8e02ad0adab29c018148eaa399ccdfba9c098bb5 (diff) | |
| download | rust-76e9ea73822a859815ed78c31403e15354f3c4c3.tar.gz rust-76e9ea73822a859815ed78c31403e15354f3c4c3.zip | |
Rollup merge of #39289 - shahn:option_entry, r=alexcrichton
Provide Entry-like API for Option This implements #39288. I am wondering whether to use std::intrinsics::unreachable!() here. Both seems fine to me (the second match optimizes away in release mode).
| -rw-r--r-- | src/libcore/option.rs | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs index c4d7b2dcf96..9df8350d90f 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -633,6 +633,76 @@ impl<T> Option<T> { } ///////////////////////////////////////////////////////////////////////// + // Entry-like operations to insert if None and return a reference + ///////////////////////////////////////////////////////////////////////// + + /// Inserts `v` into the option if it is `None`, then + /// returns a mutable reference to the contained value. + /// + /// # Examples + /// + /// ``` + /// #![feature(option_entry)] + /// + /// let mut x = None; + /// + /// { + /// let y: &mut u32 = x.get_or_insert(5); + /// assert_eq!(y, &5); + /// + /// *y = 7; + /// } + /// + /// assert_eq!(x, Some(7)); + /// ``` + #[inline] + #[unstable(feature = "option_entry", issue = "39288")] + pub fn get_or_insert(&mut self, v: T) -> &mut T { + match *self { + None => *self = Some(v), + _ => (), + } + + match *self { + Some(ref mut v) => v, + _ => unreachable!(), + } + } + + /// Inserts a value computed from `f` into the option if it is `None`, then + /// returns a mutable reference to the contained value. + /// + /// # Examples + /// + /// ``` + /// #![feature(option_entry)] + /// + /// let mut x = None; + /// + /// { + /// let y: &mut u32 = x.get_or_insert_with(|| 5); + /// assert_eq!(y, &5); + /// + /// *y = 7; + /// } + /// + /// assert_eq!(x, Some(7)); + /// ``` + #[inline] + #[unstable(feature = "option_entry", issue = "39288")] + pub fn get_or_insert_with<F: FnOnce() -> T>(&mut self, f: F) -> &mut T { + match *self { + None => *self = Some(f()), + _ => (), + } + + match *self { + Some(ref mut v) => v, + _ => unreachable!(), + } + } + + ///////////////////////////////////////////////////////////////////////// // Misc ///////////////////////////////////////////////////////////////////////// |
