Skip to content

Commit

Permalink
Rollup merge of rust-lang#39289 - shahn:option_entry, r=alexcrichton
Browse files Browse the repository at this point in the history
Provide Entry-like API for Option

This implements rust-lang#39288.

I am wondering whether to use std::intrinsics::unreachable!() here. Both seems fine to me (the second match optimizes away in release mode).
  • Loading branch information
frewsxcv committed Feb 5, 2017
2 parents 49cd748 + 8e02ad0 commit 76e9ea7
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,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
/////////////////////////////////////////////////////////////////////////
Expand Down

0 comments on commit 76e9ea7

Please sign in to comment.