Rollup merge of #70140 - Nemo157:result-flatten, r=Amanieu

Add Result<Result<T, E>, E>::flatten -> Result<T, E>

This PR makes this possible (modulo type inference):

```rust
assert_eq!(Ok(6), Ok(Ok(6)).flatten());
```

Tracking issue: #70142

<sub>largely cribbed directly from <https://github.com/rust-lang/rust/pull/60256></sub>
This commit is contained in:
Mazdak Farrokhzad 2020-03-29 16:48:21 +02:00 committed by GitHub
commit 8212a1c7dc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -230,9 +230,9 @@
#![stable(feature = "rust1", since = "1.0.0")]
use crate::fmt;
use crate::iter::{self, FromIterator, FusedIterator, TrustedLen};
use crate::ops::{self, Deref, DerefMut};
use crate::{convert, fmt};
/// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
///
@ -1214,6 +1214,38 @@ impl<T, E> Result<Option<T>, E> {
}
}
impl<T, E> Result<Result<T, E>, E> {
/// Converts from `Result<Result<T, E>, E>` to `Result<T, E>`
///
/// # Examples
/// Basic usage:
/// ```
/// #![feature(result_flattening)]
/// let x: Result<Result<&'static str, u32>, u32> = Ok(Ok("hello"));
/// assert_eq!(Ok("hello"), x.flatten());
///
/// let x: Result<Result<&'static str, u32>, u32> = Ok(Err(6));
/// assert_eq!(Err(6), x.flatten());
///
/// let x: Result<Result<&'static str, u32>, u32> = Err(6);
/// assert_eq!(Err(6), x.flatten());
/// ```
///
/// Flattening once only removes one level of nesting:
///
/// ```
/// #![feature(result_flattening)]
/// let x: Result<Result<Result<&'static str, u32>, u32>, u32> = Ok(Ok(Ok("hello")));
/// assert_eq!(Ok(Ok("hello")), x.flatten());
/// assert_eq!(Ok("hello"), x.flatten().flatten());
/// ```
#[inline]
#[unstable(feature = "result_flattening", issue = "70142")]
pub fn flatten(self) -> Result<T, E> {
self.and_then(convert::identity)
}
}
// This is a separate function to reduce the code size of the methods
#[inline(never)]
#[cold]