Skip to content

Commit

Permalink
Rollup merge of rust-lang#66045 - mzabaluev:unwrap-infallible, r=dtolnay
Browse files Browse the repository at this point in the history
Add method Result::into_ok

Implementation of rust-lang/rfcs#2799

Tracking issue rust-lang#61695
  • Loading branch information
JohnTitor authored Jan 10, 2020
2 parents f795e8a + 6f0672c commit 2dbcf08
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/libcore/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,44 @@ impl<T: Default, E> Result<T, E> {
}
}

#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
impl<T, E: Into<!>> Result<T, E> {
/// Unwraps a result that can never be an [`Err`], yielding the content of the [`Ok`].
///
/// Unlike [`unwrap`], this method is known to never panic on the
/// result types it is implemented for. Therefore, it can be used
/// instead of `unwrap` as a maintainability safeguard that will fail
/// to compile if the error type of the `Result` is later changed
/// to an error that can actually occur.
///
/// [`Ok`]: enum.Result.html#variant.Ok
/// [`Err`]: enum.Result.html#variant.Err
/// [`unwrap`]: enum.Result.html#method.unwrap
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # #![feature(never_type)]
/// # #![feature(unwrap_infallible)]
///
/// fn only_good_news() -> Result<String, !> {
/// Ok("this is fine".into())
/// }
///
/// let s: String = only_good_news().into_ok();
/// println!("{}", s);
/// ```
#[inline]
pub fn into_ok(self) -> T {
match self {
Ok(x) => x,
Err(e) => e.into(),
}
}
}

#[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
impl<T: Deref, E> Result<T, E> {
/// Converts from `Result<T, E>` (or `&Result<T, E>`) to `Result<&T::Target, &E>`.
Expand Down
2 changes: 2 additions & 0 deletions src/libcore/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
#![feature(slice_from_raw_parts)]
#![feature(const_slice_from_raw_parts)]
#![feature(const_raw_ptr_deref)]
#![feature(never_type)]
#![feature(unwrap_infallible)]

extern crate test;

Expand Down
22 changes: 22 additions & 0 deletions src/libcore/tests/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,28 @@ pub fn test_unwrap_or_default() {
assert_eq!(op2().unwrap_or_default(), 0);
}

#[test]
pub fn test_into_ok() {
fn infallible_op() -> Result<isize, !> {
Ok(666)
}

assert_eq!(infallible_op().into_ok(), 666);

enum MyNeverToken {}
impl From<MyNeverToken> for ! {
fn from(never: MyNeverToken) -> ! {
match never {}
}
}

fn infallible_op2() -> Result<isize, MyNeverToken> {
Ok(667)
}

assert_eq!(infallible_op2().into_ok(), 667);
}

#[test]
fn test_try() {
fn try_result_some() -> Option<u8> {
Expand Down

0 comments on commit 2dbcf08

Please sign in to comment.