]> git.lizzy.rs Git - rust.git/blobdiff - library/core/src/result.rs
Rollup merge of #92559 - durin42:llvm-14-attributemask, r=nikic
[rust.git] / library / core / src / result.rs
index e74e70125b81589b6d2076766acd3a8d46f19306..575fd2b42d2132d72c9c91f7323542056a9145ea 100644 (file)
@@ -563,64 +563,6 @@ pub const fn is_err(&self) -> bool {
         !self.is_ok()
     }
 
-    /// Returns `true` if the result is an [`Ok`] value containing the given value.
-    ///
-    /// # Examples
-    ///
-    /// ```
-    /// #![feature(option_result_contains)]
-    ///
-    /// let x: Result<u32, &str> = Ok(2);
-    /// assert_eq!(x.contains(&2), true);
-    ///
-    /// let x: Result<u32, &str> = Ok(3);
-    /// assert_eq!(x.contains(&2), false);
-    ///
-    /// let x: Result<u32, &str> = Err("Some error message");
-    /// assert_eq!(x.contains(&2), false);
-    /// ```
-    #[must_use]
-    #[inline]
-    #[unstable(feature = "option_result_contains", issue = "62358")]
-    pub fn contains<U>(&self, x: &U) -> bool
-    where
-        U: PartialEq<T>,
-    {
-        match self {
-            Ok(y) => x == y,
-            Err(_) => false,
-        }
-    }
-
-    /// Returns `true` if the result is an [`Err`] value containing the given value.
-    ///
-    /// # Examples
-    ///
-    /// ```
-    /// #![feature(result_contains_err)]
-    ///
-    /// let x: Result<u32, &str> = Ok(2);
-    /// assert_eq!(x.contains_err(&"Some error message"), false);
-    ///
-    /// let x: Result<u32, &str> = Err("Some error message");
-    /// assert_eq!(x.contains_err(&"Some error message"), true);
-    ///
-    /// let x: Result<u32, &str> = Err("Some other error message");
-    /// assert_eq!(x.contains_err(&"Some error message"), false);
-    /// ```
-    #[must_use]
-    #[inline]
-    #[unstable(feature = "result_contains_err", issue = "62358")]
-    pub fn contains_err<F>(&self, f: &F) -> bool
-    where
-        F: PartialEq<E>,
-    {
-        match self {
-            Ok(_) => false,
-            Err(e) => f == e,
-        }
-    }
-
     /////////////////////////////////////////////////////////////////////////
     // Adapter for each variant
     /////////////////////////////////////////////////////////////////////////
@@ -1001,373 +943,412 @@ pub fn iter_mut(&mut self) -> IterMut<'_, T> {
         IterMut { inner: self.as_mut().ok() }
     }
 
-    ////////////////////////////////////////////////////////////////////////
-    // Boolean operations on the values, eager and lazy
+    /////////////////////////////////////////////////////////////////////////
+    // Extract a value
     /////////////////////////////////////////////////////////////////////////
 
-    /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
-    ///
+    /// Returns the contained [`Ok`] value, consuming the `self` value.
     ///
-    /// # Examples
+    /// # Panics
     ///
-    /// Basic usage:
+    /// Panics if the value is an [`Err`], with a panic message including the
+    /// passed message, and the content of the [`Err`].
     ///
-    /// ```
-    /// let x: Result<u32, &str> = Ok(2);
-    /// let y: Result<&str, &str> = Err("late error");
-    /// assert_eq!(x.and(y), Err("late error"));
     ///
-    /// let x: Result<u32, &str> = Err("early error");
-    /// let y: Result<&str, &str> = Ok("foo");
-    /// assert_eq!(x.and(y), Err("early error"));
+    /// # Examples
     ///
-    /// let x: Result<u32, &str> = Err("not a 2");
-    /// let y: Result<&str, &str> = Err("late error");
-    /// assert_eq!(x.and(y), Err("not a 2"));
+    /// Basic usage:
     ///
-    /// let x: Result<u32, &str> = Ok(2);
-    /// let y: Result<&str, &str> = Ok("different result type");
-    /// assert_eq!(x.and(y), Ok("different result type"));
+    /// ```should_panic
+    /// let x: Result<u32, &str> = Err("emergency failure");
+    /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
     /// ```
     #[inline]
-    #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
+    #[track_caller]
+    #[stable(feature = "result_expect", since = "1.4.0")]
+    pub fn expect(self, msg: &str) -> T
+    where
+        E: fmt::Debug,
+    {
         match self {
-            Ok(_) => res,
-            Err(e) => Err(e),
+            Ok(t) => t,
+            Err(e) => unwrap_failed(msg, &e),
         }
     }
 
-    /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
+    /// Returns the contained [`Ok`] value, consuming the `self` value.
     ///
+    /// Because this function may panic, its use is generally discouraged.
+    /// Instead, prefer to use pattern matching and handle the [`Err`]
+    /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
+    /// [`unwrap_or_default`].
+    ///
+    /// [`unwrap_or`]: Result::unwrap_or
+    /// [`unwrap_or_else`]: Result::unwrap_or_else
+    /// [`unwrap_or_default`]: Result::unwrap_or_default
+    ///
+    /// # Panics
+    ///
+    /// Panics if the value is an [`Err`], with a panic message provided by the
+    /// [`Err`]'s value.
     ///
-    /// This function can be used for control flow based on `Result` values.
     ///
     /// # Examples
     ///
     /// Basic usage:
     ///
     /// ```
-    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
-    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
+    /// let x: Result<u32, &str> = Ok(2);
+    /// assert_eq!(x.unwrap(), 2);
+    /// ```
     ///
-    /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
-    /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
-    /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
-    /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
+    /// ```should_panic
+    /// let x: Result<u32, &str> = Err("emergency failure");
+    /// x.unwrap(); // panics with `emergency failure`
     /// ```
     #[inline]
+    #[track_caller]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
+    pub fn unwrap(self) -> T
+    where
+        E: fmt::Debug,
+    {
         match self {
-            Ok(t) => op(t),
-            Err(e) => Err(e),
+            Ok(t) => t,
+            Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
         }
     }
 
-    /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
-    ///
-    /// Arguments passed to `or` are eagerly evaluated; if you are passing the
-    /// result of a function call, it is recommended to use [`or_else`], which is
-    /// lazily evaluated.
+    /// Returns the contained [`Ok`] value or a default
     ///
-    /// [`or_else`]: Result::or_else
+    /// Consumes the `self` argument then, if [`Ok`], returns the contained
+    /// value, otherwise if [`Err`], returns the default value for that
+    /// type.
     ///
     /// # Examples
     ///
-    /// Basic usage:
+    /// Converts a string to an integer, turning poorly-formed strings
+    /// into 0 (the default value for integers). [`parse`] converts
+    /// a string to any other type that implements [`FromStr`], returning an
+    /// [`Err`] on error.
     ///
     /// ```
-    /// let x: Result<u32, &str> = Ok(2);
-    /// let y: Result<u32, &str> = Err("late error");
-    /// assert_eq!(x.or(y), Ok(2));
-    ///
-    /// let x: Result<u32, &str> = Err("early error");
-    /// let y: Result<u32, &str> = Ok(2);
-    /// assert_eq!(x.or(y), Ok(2));
-    ///
-    /// let x: Result<u32, &str> = Err("not a 2");
-    /// let y: Result<u32, &str> = Err("late error");
-    /// assert_eq!(x.or(y), Err("late error"));
+    /// let good_year_from_input = "1909";
+    /// let bad_year_from_input = "190blarg";
+    /// let good_year = good_year_from_input.parse().unwrap_or_default();
+    /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
     ///
-    /// let x: Result<u32, &str> = Ok(2);
-    /// let y: Result<u32, &str> = Ok(100);
-    /// assert_eq!(x.or(y), Ok(2));
+    /// assert_eq!(1909, good_year);
+    /// assert_eq!(0, bad_year);
     /// ```
+    ///
+    /// [`parse`]: str::parse
+    /// [`FromStr`]: crate::str::FromStr
     #[inline]
-    #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
+    #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
+    pub fn unwrap_or_default(self) -> T
+    where
+        T: Default,
+    {
         match self {
-            Ok(v) => Ok(v),
-            Err(_) => res,
+            Ok(x) => x,
+            Err(_) => Default::default(),
         }
     }
 
-    /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
+    /// Returns the contained [`Err`] value, consuming the `self` value.
     ///
-    /// This function can be used for control flow based on result values.
+    /// # Panics
+    ///
+    /// Panics if the value is an [`Ok`], with a panic message including the
+    /// passed message, and the content of the [`Ok`].
     ///
     ///
     /// # Examples
     ///
     /// Basic usage:
     ///
-    /// ```
-    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
-    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
-    ///
-    /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
-    /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
-    /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
-    /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
+    /// ```should_panic
+    /// let x: Result<u32, &str> = Ok(10);
+    /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
     /// ```
     #[inline]
-    #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
+    #[track_caller]
+    #[stable(feature = "result_expect_err", since = "1.17.0")]
+    pub fn expect_err(self, msg: &str) -> E
+    where
+        T: fmt::Debug,
+    {
         match self {
-            Ok(t) => Ok(t),
-            Err(e) => op(e),
+            Ok(t) => unwrap_failed(msg, &t),
+            Err(e) => e,
         }
     }
 
-    /// Returns the contained [`Ok`] value or a provided default.
+    /// Returns the contained [`Err`] value, consuming the `self` value.
     ///
-    /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
-    /// the result of a function call, it is recommended to use [`unwrap_or_else`],
-    /// which is lazily evaluated.
+    /// # Panics
     ///
-    /// [`unwrap_or_else`]: Result::unwrap_or_else
+    /// Panics if the value is an [`Ok`], with a custom panic message provided
+    /// by the [`Ok`]'s value.
     ///
     /// # Examples
     ///
-    /// Basic usage:
-    ///
+    /// ```should_panic
+    /// let x: Result<u32, &str> = Ok(2);
+    /// x.unwrap_err(); // panics with `2`
     /// ```
-    /// let default = 2;
-    /// let x: Result<u32, &str> = Ok(9);
-    /// assert_eq!(x.unwrap_or(default), 9);
     ///
-    /// let x: Result<u32, &str> = Err("error");
-    /// assert_eq!(x.unwrap_or(default), default);
+    /// ```
+    /// let x: Result<u32, &str> = Err("emergency failure");
+    /// assert_eq!(x.unwrap_err(), "emergency failure");
     /// ```
     #[inline]
+    #[track_caller]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn unwrap_or(self, default: T) -> T {
+    pub fn unwrap_err(self) -> E
+    where
+        T: fmt::Debug,
+    {
         match self {
-            Ok(t) => t,
-            Err(_) => default,
+            Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
+            Err(e) => e,
         }
     }
 
-    /// Returns the contained [`Ok`] value or computes it from a closure.
+    /// Returns the contained [`Ok`] value, but never panics.
     ///
+    /// 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.
+    ///
+    /// [`unwrap`]: Result::unwrap
     ///
     /// # Examples
     ///
     /// Basic usage:
     ///
     /// ```
-    /// fn count(x: &str) -> usize { x.len() }
+    /// # #![feature(never_type)]
+    /// # #![feature(unwrap_infallible)]
     ///
-    /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
-    /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
-    /// ```
-    #[inline]
-    #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
+    /// fn only_good_news() -> Result<String, !> {
+    ///     Ok("this is fine".into())
+    /// }
+    ///
+    /// let s: String = only_good_news().into_ok();
+    /// println!("{}", s);
+    /// ```
+    #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
+    #[inline]
+    pub fn into_ok(self) -> T
+    where
+        E: Into<!>,
+    {
         match self {
-            Ok(t) => t,
-            Err(e) => op(e),
+            Ok(x) => x,
+            Err(e) => e.into(),
         }
     }
 
-    /// Returns the contained [`Ok`] value, consuming the `self` value,
-    /// without checking that the value is not an [`Err`].
-    ///
-    /// # Safety
+    /// Returns the contained [`Err`] value, but never panics.
     ///
-    /// Calling this method on an [`Err`] is *[undefined behavior]*.
+    /// Unlike [`unwrap_err`], this method is known to never panic on the
+    /// result types it is implemented for. Therefore, it can be used
+    /// instead of `unwrap_err` as a maintainability safeguard that will fail
+    /// to compile if the ok type of the `Result` is later changed
+    /// to a type that can actually occur.
     ///
-    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
+    /// [`unwrap_err`]: Result::unwrap_err
     ///
     /// # Examples
     ///
+    /// Basic usage:
+    ///
     /// ```
-    /// let x: Result<u32, &str> = Ok(2);
-    /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
-    /// ```
+    /// # #![feature(never_type)]
+    /// # #![feature(unwrap_infallible)]
     ///
-    /// ```no_run
-    /// let x: Result<u32, &str> = Err("emergency failure");
-    /// unsafe { x.unwrap_unchecked(); } // Undefined behavior!
+    /// fn only_bad_news() -> Result<!, String> {
+    ///     Err("Oops, it failed".into())
+    /// }
+    ///
+    /// let error: String = only_bad_news().into_err();
+    /// println!("{}", error);
     /// ```
+    #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
     #[inline]
-    #[track_caller]
-    #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
-    pub unsafe fn unwrap_unchecked(self) -> T {
-        debug_assert!(self.is_ok());
+    pub fn into_err(self) -> E
+    where
+        T: Into<!>,
+    {
         match self {
-            Ok(t) => t,
-            // SAFETY: the safety contract must be upheld by the caller.
-            Err(_) => unsafe { hint::unreachable_unchecked() },
+            Ok(x) => x.into(),
+            Err(e) => e,
         }
     }
 
-    /// Returns the contained [`Err`] value, consuming the `self` value,
-    /// without checking that the value is not an [`Ok`].
-    ///
-    /// # Safety
-    ///
-    /// Calling this method on an [`Ok`] is *[undefined behavior]*.
+    ////////////////////////////////////////////////////////////////////////
+    // Boolean operations on the values, eager and lazy
+    /////////////////////////////////////////////////////////////////////////
+
+    /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
     ///
-    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
     ///
     /// # Examples
     ///
-    /// ```no_run
-    /// let x: Result<u32, &str> = Ok(2);
-    /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
-    /// ```
+    /// Basic usage:
     ///
     /// ```
-    /// let x: Result<u32, &str> = Err("emergency failure");
-    /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
+    /// let x: Result<u32, &str> = Ok(2);
+    /// let y: Result<&str, &str> = Err("late error");
+    /// assert_eq!(x.and(y), Err("late error"));
+    ///
+    /// let x: Result<u32, &str> = Err("early error");
+    /// let y: Result<&str, &str> = Ok("foo");
+    /// assert_eq!(x.and(y), Err("early error"));
+    ///
+    /// let x: Result<u32, &str> = Err("not a 2");
+    /// let y: Result<&str, &str> = Err("late error");
+    /// assert_eq!(x.and(y), Err("not a 2"));
+    ///
+    /// let x: Result<u32, &str> = Ok(2);
+    /// let y: Result<&str, &str> = Ok("different result type");
+    /// assert_eq!(x.and(y), Ok("different result type"));
     /// ```
     #[inline]
-    #[track_caller]
-    #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
-    pub unsafe fn unwrap_err_unchecked(self) -> E {
-        debug_assert!(self.is_err());
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
         match self {
-            // SAFETY: the safety contract must be upheld by the caller.
-            Ok(_) => unsafe { hint::unreachable_unchecked() },
-            Err(e) => e,
+            Ok(_) => res,
+            Err(e) => Err(e),
         }
     }
-}
 
-impl<T: Copy, E> Result<&T, E> {
-    /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
-    /// `Ok` part.
+    /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
     ///
-    /// # Examples
     ///
-    /// ```
-    /// #![feature(result_copied)]
-    /// let val = 12;
-    /// let x: Result<&i32, i32> = Ok(&val);
-    /// assert_eq!(x, Ok(&12));
-    /// let copied = x.copied();
-    /// assert_eq!(copied, Ok(12));
-    /// ```
-    #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
-    pub fn copied(self) -> Result<T, E> {
-        self.map(|&t| t)
-    }
-}
-
-impl<T: Copy, E> Result<&mut T, E> {
-    /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
-    /// `Ok` part.
+    /// This function can be used for control flow based on `Result` values.
     ///
     /// # Examples
     ///
+    /// Basic usage:
+    ///
     /// ```
-    /// #![feature(result_copied)]
-    /// let mut val = 12;
-    /// let x: Result<&mut i32, i32> = Ok(&mut val);
-    /// assert_eq!(x, Ok(&mut 12));
-    /// let copied = x.copied();
-    /// assert_eq!(copied, Ok(12));
+    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
+    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
+    ///
+    /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
+    /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
+    /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
+    /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
     /// ```
-    #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")]
-    pub fn copied(self) -> Result<T, E> {
-        self.map(|&mut t| t)
+    #[inline]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
+        match self {
+            Ok(t) => op(t),
+            Err(e) => Err(e),
+        }
     }
-}
 
-impl<T: Clone, E> Result<&T, E> {
-    /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
-    /// `Ok` part.
+    /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
+    ///
+    /// Arguments passed to `or` are eagerly evaluated; if you are passing the
+    /// result of a function call, it is recommended to use [`or_else`], which is
+    /// lazily evaluated.
+    ///
+    /// [`or_else`]: Result::or_else
     ///
     /// # Examples
     ///
+    /// Basic usage:
+    ///
     /// ```
-    /// #![feature(result_cloned)]
-    /// let val = 12;
-    /// let x: Result<&i32, i32> = Ok(&val);
-    /// assert_eq!(x, Ok(&12));
-    /// let cloned = x.cloned();
-    /// assert_eq!(cloned, Ok(12));
+    /// let x: Result<u32, &str> = Ok(2);
+    /// let y: Result<u32, &str> = Err("late error");
+    /// assert_eq!(x.or(y), Ok(2));
+    ///
+    /// let x: Result<u32, &str> = Err("early error");
+    /// let y: Result<u32, &str> = Ok(2);
+    /// assert_eq!(x.or(y), Ok(2));
+    ///
+    /// let x: Result<u32, &str> = Err("not a 2");
+    /// let y: Result<u32, &str> = Err("late error");
+    /// assert_eq!(x.or(y), Err("late error"));
+    ///
+    /// let x: Result<u32, &str> = Ok(2);
+    /// let y: Result<u32, &str> = Ok(100);
+    /// assert_eq!(x.or(y), Ok(2));
     /// ```
-    #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
-    pub fn cloned(self) -> Result<T, E> {
-        self.map(|t| t.clone())
+    #[inline]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
+        match self {
+            Ok(v) => Ok(v),
+            Err(_) => res,
+        }
     }
-}
 
-impl<T: Clone, E> Result<&mut T, E> {
-    /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
-    /// `Ok` part.
+    /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
+    ///
+    /// This function can be used for control flow based on result values.
+    ///
     ///
     /// # Examples
     ///
+    /// Basic usage:
+    ///
     /// ```
-    /// #![feature(result_cloned)]
-    /// let mut val = 12;
-    /// let x: Result<&mut i32, i32> = Ok(&mut val);
-    /// assert_eq!(x, Ok(&mut 12));
-    /// let cloned = x.cloned();
-    /// assert_eq!(cloned, Ok(12));
+    /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
+    /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
+    ///
+    /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
+    /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
+    /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
+    /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
     /// ```
-    #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")]
-    pub fn cloned(self) -> Result<T, E> {
-        self.map(|t| t.clone())
+    #[inline]
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
+        match self {
+            Ok(t) => Ok(t),
+            Err(e) => op(e),
+        }
     }
-}
 
-impl<T, E: fmt::Debug> Result<T, E> {
-    /// Returns the contained [`Ok`] value, consuming the `self` value.
-    ///
-    /// # Panics
+    /// Returns the contained [`Ok`] value or a provided default.
     ///
-    /// Panics if the value is an [`Err`], with a panic message including the
-    /// passed message, and the content of the [`Err`].
+    /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
+    /// the result of a function call, it is recommended to use [`unwrap_or_else`],
+    /// which is lazily evaluated.
     ///
+    /// [`unwrap_or_else`]: Result::unwrap_or_else
     ///
     /// # Examples
     ///
     /// Basic usage:
     ///
-    /// ```should_panic
-    /// let x: Result<u32, &str> = Err("emergency failure");
-    /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
+    /// ```
+    /// let default = 2;
+    /// let x: Result<u32, &str> = Ok(9);
+    /// assert_eq!(x.unwrap_or(default), 9);
+    ///
+    /// let x: Result<u32, &str> = Err("error");
+    /// assert_eq!(x.unwrap_or(default), default);
     /// ```
     #[inline]
-    #[track_caller]
-    #[stable(feature = "result_expect", since = "1.4.0")]
-    pub fn expect(self, msg: &str) -> T {
+    #[stable(feature = "rust1", since = "1.0.0")]
+    pub fn unwrap_or(self, default: T) -> T {
         match self {
             Ok(t) => t,
-            Err(e) => unwrap_failed(msg, &e),
+            Err(_) => default,
         }
     }
 
-    /// Returns the contained [`Ok`] value, consuming the `self` value.
-    ///
-    /// Because this function may panic, its use is generally discouraged.
-    /// Instead, prefer to use pattern matching and handle the [`Err`]
-    /// case explicitly, or call [`unwrap_or`], [`unwrap_or_else`], or
-    /// [`unwrap_or_default`].
-    ///
-    /// [`unwrap_or`]: Result::unwrap_or
-    /// [`unwrap_or_else`]: Result::unwrap_or_else
-    /// [`unwrap_or_default`]: Result::unwrap_or_default
-    ///
-    /// # Panics
-    ///
-    /// Panics if the value is an [`Err`], with a panic message provided by the
-    /// [`Err`]'s value.
+    /// Returns the contained [`Ok`] value or computes it from a closure.
     ///
     ///
     /// # Examples
@@ -1375,186 +1356,232 @@ pub fn expect(self, msg: &str) -> T {
     /// Basic usage:
     ///
     /// ```
-    /// let x: Result<u32, &str> = Ok(2);
-    /// assert_eq!(x.unwrap(), 2);
-    /// ```
+    /// fn count(x: &str) -> usize { x.len() }
     ///
-    /// ```should_panic
-    /// let x: Result<u32, &str> = Err("emergency failure");
-    /// x.unwrap(); // panics with `emergency failure`
+    /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
+    /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
     /// ```
     #[inline]
-    #[track_caller]
     #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn unwrap(self) -> T {
+    pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
         match self {
             Ok(t) => t,
-            Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
+            Err(e) => op(e),
         }
     }
-}
 
-impl<T: fmt::Debug, E> Result<T, E> {
-    /// Returns the contained [`Err`] value, consuming the `self` value.
+    /// Returns the contained [`Ok`] value, consuming the `self` value,
+    /// without checking that the value is not an [`Err`].
     ///
-    /// # Panics
+    /// # Safety
     ///
-    /// Panics if the value is an [`Ok`], with a panic message including the
-    /// passed message, and the content of the [`Ok`].
+    /// Calling this method on an [`Err`] is *[undefined behavior]*.
     ///
+    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
     ///
     /// # Examples
     ///
-    /// Basic usage:
+    /// ```
+    /// let x: Result<u32, &str> = Ok(2);
+    /// assert_eq!(unsafe { x.unwrap_unchecked() }, 2);
+    /// ```
     ///
-    /// ```should_panic
-    /// let x: Result<u32, &str> = Ok(10);
-    /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
+    /// ```no_run
+    /// let x: Result<u32, &str> = Err("emergency failure");
+    /// unsafe { x.unwrap_unchecked(); } // Undefined behavior!
     /// ```
     #[inline]
     #[track_caller]
-    #[stable(feature = "result_expect_err", since = "1.17.0")]
-    pub fn expect_err(self, msg: &str) -> E {
+    #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
+    pub unsafe fn unwrap_unchecked(self) -> T {
+        debug_assert!(self.is_ok());
         match self {
-            Ok(t) => unwrap_failed(msg, &t),
-            Err(e) => e,
+            Ok(t) => t,
+            // SAFETY: the safety contract must be upheld by the caller.
+            Err(_) => unsafe { hint::unreachable_unchecked() },
         }
     }
 
-    /// Returns the contained [`Err`] value, consuming the `self` value.
+    /// Returns the contained [`Err`] value, consuming the `self` value,
+    /// without checking that the value is not an [`Ok`].
     ///
-    /// # Panics
+    /// # Safety
     ///
-    /// Panics if the value is an [`Ok`], with a custom panic message provided
-    /// by the [`Ok`]'s value.
+    /// Calling this method on an [`Ok`] is *[undefined behavior]*.
+    ///
+    /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
     ///
     /// # Examples
     ///
-    /// ```should_panic
+    /// ```no_run
     /// let x: Result<u32, &str> = Ok(2);
-    /// x.unwrap_err(); // panics with `2`
+    /// unsafe { x.unwrap_err_unchecked() }; // Undefined behavior!
     /// ```
     ///
     /// ```
     /// let x: Result<u32, &str> = Err("emergency failure");
-    /// assert_eq!(x.unwrap_err(), "emergency failure");
+    /// assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure");
     /// ```
     #[inline]
     #[track_caller]
-    #[stable(feature = "rust1", since = "1.0.0")]
-    pub fn unwrap_err(self) -> E {
+    #[stable(feature = "option_result_unwrap_unchecked", since = "1.58.0")]
+    pub unsafe fn unwrap_err_unchecked(self) -> E {
+        debug_assert!(self.is_err());
         match self {
-            Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
+            // SAFETY: the safety contract must be upheld by the caller.
+            Ok(_) => unsafe { hint::unreachable_unchecked() },
             Err(e) => e,
         }
     }
-}
 
-impl<T: Default, E> Result<T, E> {
-    /// Returns the contained [`Ok`] value or a default
-    ///
-    /// Consumes the `self` argument then, if [`Ok`], returns the contained
-    /// value, otherwise if [`Err`], returns the default value for that
-    /// type.
+    /////////////////////////////////////////////////////////////////////////
+    // Misc or niche
+    /////////////////////////////////////////////////////////////////////////
+
+    /// Returns `true` if the result is an [`Ok`] value containing the given value.
     ///
     /// # Examples
     ///
-    /// Converts a string to an integer, turning poorly-formed strings
-    /// into 0 (the default value for integers). [`parse`] converts
-    /// a string to any other type that implements [`FromStr`], returning an
-    /// [`Err`] on error.
-    ///
     /// ```
-    /// let good_year_from_input = "1909";
-    /// let bad_year_from_input = "190blarg";
-    /// let good_year = good_year_from_input.parse().unwrap_or_default();
-    /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
+    /// #![feature(option_result_contains)]
     ///
-    /// assert_eq!(1909, good_year);
-    /// assert_eq!(0, bad_year);
-    /// ```
+    /// let x: Result<u32, &str> = Ok(2);
+    /// assert_eq!(x.contains(&2), true);
     ///
-    /// [`parse`]: str::parse
-    /// [`FromStr`]: crate::str::FromStr
+    /// let x: Result<u32, &str> = Ok(3);
+    /// assert_eq!(x.contains(&2), false);
+    ///
+    /// let x: Result<u32, &str> = Err("Some error message");
+    /// assert_eq!(x.contains(&2), false);
+    /// ```
+    #[must_use]
     #[inline]
-    #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
-    pub fn unwrap_or_default(self) -> T {
+    #[unstable(feature = "option_result_contains", issue = "62358")]
+    pub fn contains<U>(&self, x: &U) -> bool
+    where
+        U: PartialEq<T>,
+    {
         match self {
-            Ok(x) => x,
-            Err(_) => Default::default(),
+            Ok(y) => x == y,
+            Err(_) => false,
         }
     }
-}
 
-#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
-impl<T, E: Into<!>> Result<T, E> {
-    /// Returns the contained [`Ok`] value, but never panics.
-    ///
-    /// 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.
-    ///
-    /// [`unwrap`]: Result::unwrap
+    /// Returns `true` if the result is an [`Err`] value containing the given value.
     ///
     /// # Examples
     ///
-    /// Basic usage:
-    ///
     /// ```
-    /// # #![feature(never_type)]
-    /// # #![feature(unwrap_infallible)]
+    /// #![feature(result_contains_err)]
     ///
-    /// fn only_good_news() -> Result<String, !> {
-    ///     Ok("this is fine".into())
-    /// }
+    /// let x: Result<u32, &str> = Ok(2);
+    /// assert_eq!(x.contains_err(&"Some error message"), false);
     ///
-    /// let s: String = only_good_news().into_ok();
-    /// println!("{}", s);
+    /// let x: Result<u32, &str> = Err("Some error message");
+    /// assert_eq!(x.contains_err(&"Some error message"), true);
+    ///
+    /// let x: Result<u32, &str> = Err("Some other error message");
+    /// assert_eq!(x.contains_err(&"Some error message"), false);
     /// ```
+    #[must_use]
     #[inline]
-    pub fn into_ok(self) -> T {
+    #[unstable(feature = "result_contains_err", issue = "62358")]
+    pub fn contains_err<F>(&self, f: &F) -> bool
+    where
+        F: PartialEq<E>,
+    {
         match self {
-            Ok(x) => x,
-            Err(e) => e.into(),
+            Ok(_) => false,
+            Err(e) => f == e,
         }
     }
 }
 
-#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")]
-impl<T: Into<!>, E> Result<T, E> {
-    /// Returns the contained [`Err`] value, but never panics.
+impl<T, E> Result<&T, E> {
+    /// Maps a `Result<&T, E>` to a `Result<T, E>` by copying the contents of the
+    /// `Ok` part.
     ///
-    /// Unlike [`unwrap_err`], this method is known to never panic on the
-    /// result types it is implemented for. Therefore, it can be used
-    /// instead of `unwrap_err` as a maintainability safeguard that will fail
-    /// to compile if the ok type of the `Result` is later changed
-    /// to a type that can actually occur.
+    /// # Examples
     ///
-    /// [`unwrap_err`]: Result::unwrap_err
+    /// ```
+    /// let val = 12;
+    /// let x: Result<&i32, i32> = Ok(&val);
+    /// assert_eq!(x, Ok(&12));
+    /// let copied = x.copied();
+    /// assert_eq!(copied, Ok(12));
+    /// ```
+    #[inline]
+    #[stable(feature = "result_copied", since = "1.59.0")]
+    pub fn copied(self) -> Result<T, E>
+    where
+        T: Copy,
+    {
+        self.map(|&t| t)
+    }
+
+    /// Maps a `Result<&T, E>` to a `Result<T, E>` by cloning the contents of the
+    /// `Ok` part.
     ///
     /// # Examples
     ///
-    /// Basic usage:
+    /// ```
+    /// let val = 12;
+    /// let x: Result<&i32, i32> = Ok(&val);
+    /// assert_eq!(x, Ok(&12));
+    /// let cloned = x.cloned();
+    /// assert_eq!(cloned, Ok(12));
+    /// ```
+    #[inline]
+    #[stable(feature = "result_cloned", since = "1.59.0")]
+    pub fn cloned(self) -> Result<T, E>
+    where
+        T: Clone,
+    {
+        self.map(|t| t.clone())
+    }
+}
+
+impl<T, E> Result<&mut T, E> {
+    /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by copying the contents of the
+    /// `Ok` part.
+    ///
+    /// # Examples
     ///
     /// ```
-    /// # #![feature(never_type)]
-    /// # #![feature(unwrap_infallible)]
+    /// let mut val = 12;
+    /// let x: Result<&mut i32, i32> = Ok(&mut val);
+    /// assert_eq!(x, Ok(&mut 12));
+    /// let copied = x.copied();
+    /// assert_eq!(copied, Ok(12));
+    /// ```
+    #[inline]
+    #[stable(feature = "result_copied", since = "1.59.0")]
+    pub fn copied(self) -> Result<T, E>
+    where
+        T: Copy,
+    {
+        self.map(|&mut t| t)
+    }
+
+    /// Maps a `Result<&mut T, E>` to a `Result<T, E>` by cloning the contents of the
+    /// `Ok` part.
     ///
-    /// fn only_bad_news() -> Result<!, String> {
-    ///     Err("Oops, it failed".into())
-    /// }
+    /// # Examples
     ///
-    /// let error: String = only_bad_news().into_err();
-    /// println!("{}", error);
+    /// ```
+    /// let mut val = 12;
+    /// let x: Result<&mut i32, i32> = Ok(&mut val);
+    /// assert_eq!(x, Ok(&mut 12));
+    /// let cloned = x.cloned();
+    /// assert_eq!(cloned, Ok(12));
     /// ```
     #[inline]
-    pub fn into_err(self) -> E {
-        match self {
-            Ok(x) => x.into(),
-            Err(e) => e,
-        }
+    #[stable(feature = "result_cloned", since = "1.59.0")]
+    pub fn cloned(self) -> Result<T, E>
+    where
+        T: Clone,
+    {
+        self.map(|t| t.clone())
     }
 }