From eda61d8d8a9a241f90808e6dc5256766721dc608 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:23:46 -0800 Subject: [PATCH 01/15] Move Result::as_deref --- library/core/src/result.rs | 47 +++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 3cde63493d3..09feb7e0eda 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -901,6 +901,30 @@ impl Result { self } + /// Converts from `Result` (or `&Result`) to `Result<&::Target, &E>`. + /// + /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref) + /// and returns the new [`Result`]. + /// + /// # Examples + /// + /// ``` + /// let x: Result = Ok("hello".to_string()); + /// let y: Result<&str, &u32> = Ok("hello"); + /// assert_eq!(x.as_deref(), y); + /// + /// let x: Result = Err(42); + /// let y: Result<&str, &u32> = Err(&42); + /// assert_eq!(x.as_deref(), y); + /// ``` + #[stable(feature = "inner_deref", since = "1.47.0")] + pub fn as_deref(&self) -> Result<&T::Target, &E> + where + T: Deref, + { + self.as_ref().map(|t| t.deref()) + } + ///////////////////////////////////////////////////////////////////////// // Iterator constructors ///////////////////////////////////////////////////////////////////////// @@ -1508,29 +1532,6 @@ impl, E> Result { } } -impl Result { - /// Converts from `Result` (or `&Result`) to `Result<&::Target, &E>`. - /// - /// Coerces the [`Ok`] variant of the original [`Result`] via [`Deref`](crate::ops::Deref) - /// and returns the new [`Result`]. - /// - /// # Examples - /// - /// ``` - /// let x: Result = Ok("hello".to_string()); - /// let y: Result<&str, &u32> = Ok("hello"); - /// assert_eq!(x.as_deref(), y); - /// - /// let x: Result = Err(42); - /// let y: Result<&str, &u32> = Err(&42); - /// assert_eq!(x.as_deref(), y); - /// ``` - #[stable(feature = "inner_deref", since = "1.47.0")] - pub fn as_deref(&self) -> Result<&T::Target, &E> { - self.as_ref().map(|t| t.deref()) - } -} - impl Result { /// Converts from `Result` (or `&mut Result`) to `Result<&mut ::Target, &mut E>`. /// From 5aa8f91ff0d376eb25ea52a10d7c4cdadf4407ac Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:24:23 -0800 Subject: [PATCH 02/15] Move Result::as_deref_mut --- library/core/src/result.rs | 51 +++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 09feb7e0eda..e74e70125b8 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -925,6 +925,32 @@ impl Result { self.as_ref().map(|t| t.deref()) } + /// Converts from `Result` (or `&mut Result`) to `Result<&mut ::Target, &mut E>`. + /// + /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut) + /// and returns the new [`Result`]. + /// + /// # Examples + /// + /// ``` + /// let mut s = "HELLO".to_string(); + /// let mut x: Result = Ok("hello".to_string()); + /// let y: Result<&mut str, &mut u32> = Ok(&mut s); + /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); + /// + /// let mut i = 42; + /// let mut x: Result = Err(42); + /// let y: Result<&mut str, &mut u32> = Err(&mut i); + /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); + /// ``` + #[stable(feature = "inner_deref", since = "1.47.0")] + pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> + where + T: DerefMut, + { + self.as_mut().map(|t| t.deref_mut()) + } + ///////////////////////////////////////////////////////////////////////// // Iterator constructors ///////////////////////////////////////////////////////////////////////// @@ -1532,31 +1558,6 @@ impl, E> Result { } } -impl Result { - /// Converts from `Result` (or `&mut Result`) to `Result<&mut ::Target, &mut E>`. - /// - /// Coerces the [`Ok`] variant of the original [`Result`] via [`DerefMut`](crate::ops::DerefMut) - /// and returns the new [`Result`]. - /// - /// # Examples - /// - /// ``` - /// let mut s = "HELLO".to_string(); - /// let mut x: Result = Ok("hello".to_string()); - /// let y: Result<&mut str, &mut u32> = Ok(&mut s); - /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); - /// - /// let mut i = 42; - /// let mut x: Result = Err(42); - /// let y: Result<&mut str, &mut u32> = Err(&mut i); - /// assert_eq!(x.as_deref_mut().map(|x| { x.make_ascii_uppercase(); x }), y); - /// ``` - #[stable(feature = "inner_deref", since = "1.47.0")] - pub fn as_deref_mut(&mut self) -> Result<&mut T::Target, &mut E> { - self.as_mut().map(|t| t.deref_mut()) - } -} - impl Result, E> { /// Transposes a `Result` of an `Option` into an `Option` of a `Result`. /// From 15f57a6c59125c9f08efa2688675a998a869f9b9 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:25:42 -0800 Subject: [PATCH 03/15] Move Result::expect and Result::unwrap --- library/core/src/result.rs | 144 +++++++++++++++++++------------------ 1 file changed, 76 insertions(+), 68 deletions(-) diff --git a/library/core/src/result.rs b/library/core/src/result.rs index e74e70125b8..7265f03adba 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1001,6 +1001,82 @@ impl Result { IterMut { inner: self.as_mut().ok() } } + ///////////////////////////////////////////////////////////////////////// + // Extract a value + ///////////////////////////////////////////////////////////////////////// + + /// Returns the contained [`Ok`] value, consuming the `self` value. + /// + /// # Panics + /// + /// Panics if the value is an [`Err`], with a panic message including the + /// passed message, and the content of the [`Err`]. + /// + /// + /// # Examples + /// + /// Basic usage: + /// + /// ```should_panic + /// let x: Result = Err("emergency failure"); + /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure` + /// ``` + #[inline] + #[track_caller] + #[stable(feature = "result_expect", since = "1.4.0")] + pub fn expect(self, msg: &str) -> T + where + E: fmt::Debug, + { + match self { + Ok(t) => t, + Err(e) => unwrap_failed(msg, &e), + } + } + + /// 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. + /// + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// let x: Result = Ok(2); + /// assert_eq!(x.unwrap(), 2); + /// ``` + /// + /// ```should_panic + /// let x: Result = Err("emergency failure"); + /// x.unwrap(); // panics with `emergency failure` + /// ``` + #[inline] + #[track_caller] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn unwrap(self) -> T + where + E: fmt::Debug, + { + match self { + Ok(t) => t, + Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e), + } + } + //////////////////////////////////////////////////////////////////////// // Boolean operations on the values, eager and lazy ///////////////////////////////////////////////////////////////////////// @@ -1326,74 +1402,6 @@ impl Result<&mut T, E> { } } -impl Result { - /// Returns the contained [`Ok`] value, consuming the `self` value. - /// - /// # Panics - /// - /// Panics if the value is an [`Err`], with a panic message including the - /// passed message, and the content of the [`Err`]. - /// - /// - /// # Examples - /// - /// Basic usage: - /// - /// ```should_panic - /// let x: Result = Err("emergency failure"); - /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure` - /// ``` - #[inline] - #[track_caller] - #[stable(feature = "result_expect", since = "1.4.0")] - pub fn expect(self, msg: &str) -> T { - match self { - Ok(t) => t, - Err(e) => unwrap_failed(msg, &e), - } - } - - /// 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. - /// - /// - /// # Examples - /// - /// Basic usage: - /// - /// ``` - /// let x: Result = Ok(2); - /// assert_eq!(x.unwrap(), 2); - /// ``` - /// - /// ```should_panic - /// let x: Result = Err("emergency failure"); - /// x.unwrap(); // panics with `emergency failure` - /// ``` - #[inline] - #[track_caller] - #[stable(feature = "rust1", since = "1.0.0")] - pub fn unwrap(self) -> T { - match self { - Ok(t) => t, - Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e), - } - } -} - impl Result { /// Returns the contained [`Err`] value, consuming the `self` value. /// From aa2aca2c8c9b5f07318350ecebcd535d79d0deeb Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:26:36 -0800 Subject: [PATCH 04/15] Move Result::unwrap_or_default --- library/core/src/result.rs | 73 +++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 7265f03adba..7d0e647bd91 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1077,6 +1077,43 @@ impl Result { } } + /// 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. + /// + /// # 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(); + /// + /// assert_eq!(1909, good_year); + /// assert_eq!(0, bad_year); + /// ``` + /// + /// [`parse`]: str::parse + /// [`FromStr`]: crate::str::FromStr + #[inline] + #[stable(feature = "result_unwrap_or_default", since = "1.16.0")] + pub fn unwrap_or_default(self) -> T + where + T: Default, + { + match self { + Ok(x) => x, + Err(_) => Default::default(), + } + } + //////////////////////////////////////////////////////////////////////// // Boolean operations on the values, eager and lazy ///////////////////////////////////////////////////////////////////////// @@ -1458,42 +1495,6 @@ impl Result { } } -impl Result { - /// 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. - /// - /// # 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(); - /// - /// assert_eq!(1909, good_year); - /// assert_eq!(0, bad_year); - /// ``` - /// - /// [`parse`]: str::parse - /// [`FromStr`]: crate::str::FromStr - #[inline] - #[stable(feature = "result_unwrap_or_default", since = "1.16.0")] - pub fn unwrap_or_default(self) -> T { - match self { - Ok(x) => x, - Err(_) => Default::default(), - } - } -} - #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] impl> Result { /// Returns the contained [`Ok`] value, but never panics. From 06ea5ebe4ef89cdb626930c4e8b235d430d47fee Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:27:43 -0800 Subject: [PATCH 05/15] Move Result::expect_err and Result::unwrap_err --- library/core/src/result.rs | 116 +++++++++++++++++++------------------ 1 file changed, 60 insertions(+), 56 deletions(-) diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 7d0e647bd91..9cd949f7a12 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1114,6 +1114,66 @@ impl Result { } } + /// Returns the contained [`Err`] value, consuming the `self` value. + /// + /// # 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: + /// + /// ```should_panic + /// let x: Result = Ok(10); + /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` + /// ``` + #[inline] + #[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) => unwrap_failed(msg, &t), + Err(e) => e, + } + } + + /// Returns the contained [`Err`] value, consuming the `self` value. + /// + /// # Panics + /// + /// Panics if the value is an [`Ok`], with a custom panic message provided + /// by the [`Ok`]'s value. + /// + /// # Examples + /// + /// ```should_panic + /// let x: Result = Ok(2); + /// x.unwrap_err(); // panics with `2` + /// ``` + /// + /// ``` + /// let x: Result = Err("emergency failure"); + /// assert_eq!(x.unwrap_err(), "emergency failure"); + /// ``` + #[inline] + #[track_caller] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn unwrap_err(self) -> E + where + T: fmt::Debug, + { + match self { + Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t), + Err(e) => e, + } + } + //////////////////////////////////////////////////////////////////////// // Boolean operations on the values, eager and lazy ///////////////////////////////////////////////////////////////////////// @@ -1439,62 +1499,6 @@ impl Result<&mut T, E> { } } -impl Result { - /// Returns the contained [`Err`] value, consuming the `self` value. - /// - /// # 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: - /// - /// ```should_panic - /// let x: Result = Ok(10); - /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` - /// ``` - #[inline] - #[track_caller] - #[stable(feature = "result_expect_err", since = "1.17.0")] - pub fn expect_err(self, msg: &str) -> E { - match self { - Ok(t) => unwrap_failed(msg, &t), - Err(e) => e, - } - } - - /// Returns the contained [`Err`] value, consuming the `self` value. - /// - /// # Panics - /// - /// Panics if the value is an [`Ok`], with a custom panic message provided - /// by the [`Ok`]'s value. - /// - /// # Examples - /// - /// ```should_panic - /// let x: Result = Ok(2); - /// x.unwrap_err(); // panics with `2` - /// ``` - /// - /// ``` - /// let x: Result = Err("emergency failure"); - /// assert_eq!(x.unwrap_err(), "emergency failure"); - /// ``` - #[inline] - #[track_caller] - #[stable(feature = "rust1", since = "1.0.0")] - pub fn unwrap_err(self) -> E { - match self { - Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t), - Err(e) => e, - } - } -} - #[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] impl> Result { /// Returns the contained [`Ok`] value, but never panics. From 778ca204a6187eb9db99b06d1fa4c759e4e67f05 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:28:23 -0800 Subject: [PATCH 06/15] Move Result::into_ok --- library/core/src/result.rs | 73 +++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 9cd949f7a12..6810e44d81e 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1174,6 +1174,43 @@ impl Result { } } + /// 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: + /// + /// ``` + /// # #![feature(never_type)] + /// # #![feature(unwrap_infallible)] + /// + /// fn only_good_news() -> Result { + /// 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(x) => x, + Err(e) => e.into(), + } + } + //////////////////////////////////////////////////////////////////////// // Boolean operations on the values, eager and lazy ///////////////////////////////////////////////////////////////////////// @@ -1499,42 +1536,6 @@ impl Result<&mut T, E> { } } -#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] -impl> Result { - /// 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: - /// - /// ``` - /// # #![feature(never_type)] - /// # #![feature(unwrap_infallible)] - /// - /// fn only_good_news() -> Result { - /// 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 = "unwrap_infallible", reason = "newly added", issue = "61695")] impl, E> Result { /// Returns the contained [`Err`] value, but never panics. From b2df61fa9f69554f3a1cdc5e02d1259396f8ff53 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:28:54 -0800 Subject: [PATCH 07/15] Move Result::into_err --- library/core/src/result.rs | 73 +++++++++++++++++++------------------- 1 file changed, 37 insertions(+), 36 deletions(-) diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 6810e44d81e..382a5711641 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1211,6 +1211,43 @@ impl Result { } } + /// Returns the contained [`Err`] value, but never panics. + /// + /// 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. + /// + /// [`unwrap_err`]: Result::unwrap_err + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// # #![feature(never_type)] + /// # #![feature(unwrap_infallible)] + /// + /// fn only_bad_news() -> Result { + /// 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] + pub fn into_err(self) -> E + where + T: Into, + { + match self { + Ok(x) => x.into(), + Err(e) => e, + } + } + //////////////////////////////////////////////////////////////////////// // Boolean operations on the values, eager and lazy ///////////////////////////////////////////////////////////////////////// @@ -1536,42 +1573,6 @@ impl Result<&mut T, E> { } } -#[unstable(feature = "unwrap_infallible", reason = "newly added", issue = "61695")] -impl, E> Result { - /// Returns the contained [`Err`] value, but never panics. - /// - /// 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. - /// - /// [`unwrap_err`]: Result::unwrap_err - /// - /// # Examples - /// - /// Basic usage: - /// - /// ``` - /// # #![feature(never_type)] - /// # #![feature(unwrap_infallible)] - /// - /// fn only_bad_news() -> Result { - /// Err("Oops, it failed".into()) - /// } - /// - /// let error: String = only_bad_news().into_err(); - /// println!("{}", error); - /// ``` - #[inline] - pub fn into_err(self) -> E { - match self { - Ok(x) => x.into(), - Err(e) => e, - } - } -} - impl Result, E> { /// Transposes a `Result` of an `Option` into an `Option` of a `Result`. /// From e63e2680dadeb87c9fea78c431e628cf7ed461a6 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:30:28 -0800 Subject: [PATCH 08/15] Consolidate impl Result<&T, E> --- library/core/src/result.rs | 48 +++++++++++++++++++++----------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 382a5711641..29a0be68083 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1493,7 +1493,7 @@ impl Result { } } -impl Result<&T, E> { +impl Result<&T, E> { /// Maps a `Result<&T, E>` to a `Result` by copying the contents of the /// `Ok` part. /// @@ -1508,9 +1508,33 @@ impl Result<&T, E> { /// assert_eq!(copied, Ok(12)); /// ``` #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")] - pub fn copied(self) -> Result { + pub fn copied(self) -> Result + where + T: Copy, + { self.map(|&t| t) } + + /// Maps a `Result<&T, E>` to a `Result` by cloning the contents of the + /// `Ok` part. + /// + /// # Examples + /// + /// ``` + /// #![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)); + /// ``` + #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")] + pub fn cloned(self) -> Result + where + T: Clone, + { + self.map(|t| t.clone()) + } } impl Result<&mut T, E> { @@ -1533,26 +1557,6 @@ impl Result<&mut T, E> { } } -impl Result<&T, E> { - /// Maps a `Result<&T, E>` to a `Result` by cloning the contents of the - /// `Ok` part. - /// - /// # Examples - /// - /// ``` - /// #![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)); - /// ``` - #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")] - pub fn cloned(self) -> Result { - self.map(|t| t.clone()) - } -} - impl Result<&mut T, E> { /// Maps a `Result<&mut T, E>` to a `Result` by cloning the contents of the /// `Ok` part. From b7a0ab18f6b506b73cda720553a5710e7170fc7c Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:31:26 -0800 Subject: [PATCH 09/15] Consolidate impl Result<&mut T, E> --- library/core/src/result.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 29a0be68083..f46632e7a8d 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1537,7 +1537,7 @@ impl Result<&T, E> { } } -impl Result<&mut T, E> { +impl Result<&mut T, E> { /// Maps a `Result<&mut T, E>` to a `Result` by copying the contents of the /// `Ok` part. /// @@ -1552,12 +1552,13 @@ impl Result<&mut T, E> { /// assert_eq!(copied, Ok(12)); /// ``` #[unstable(feature = "result_copied", reason = "newly added", issue = "63168")] - pub fn copied(self) -> Result { + pub fn copied(self) -> Result + where + T: Copy, + { self.map(|&mut t| t) } -} -impl Result<&mut T, E> { /// Maps a `Result<&mut T, E>` to a `Result` by cloning the contents of the /// `Ok` part. /// @@ -1572,7 +1573,10 @@ impl Result<&mut T, E> { /// assert_eq!(cloned, Ok(12)); /// ``` #[unstable(feature = "result_cloned", reason = "newly added", issue = "63168")] - pub fn cloned(self) -> Result { + pub fn cloned(self) -> Result + where + T: Clone, + { self.map(|t| t.clone()) } } From bbcf09f2fb50c146a4b79a1cfece94bfbe1b159a Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:34:35 -0800 Subject: [PATCH 10/15] Move Option::unwrap_or_default --- library/core/src/option.rs | 80 +++++++++++++++++++------------------- 1 file changed, 39 insertions(+), 41 deletions(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index e6312b8b2d9..d457d502c25 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -810,6 +810,45 @@ impl Option { } } + /// Returns the contained [`Some`] value or a default. + /// + /// Consumes the `self` argument then, if [`Some`], returns the contained + /// value, otherwise if [`None`], returns the [default value] for that + /// type. + /// + /// # 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 + /// [`None`] on error. + /// + /// ``` + /// let good_year_from_input = "1909"; + /// let bad_year_from_input = "190blarg"; + /// let good_year = good_year_from_input.parse().ok().unwrap_or_default(); + /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default(); + /// + /// assert_eq!(1909, good_year); + /// assert_eq!(0, bad_year); + /// ``` + /// + /// [default value]: Default::default + /// [`parse`]: str::parse + /// [`FromStr`]: crate::str::FromStr + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] + pub const fn unwrap_or_default(self) -> T + where + T: ~const Default, + { + match self { + Some(x) => x, + None => Default::default(), + } + } + /// Returns the contained [`Some`] value, consuming the `self` value, /// without checking that the value is not [`None`]. /// @@ -1685,47 +1724,6 @@ impl Option<&mut T> { } } -impl Option { - /// Returns the contained [`Some`] value or a default. - /// - /// Consumes the `self` argument then, if [`Some`], returns the contained - /// value, otherwise if [`None`], returns the [default value] for that - /// type. - /// - /// # 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 - /// [`None`] on error. - /// - /// ``` - /// let good_year_from_input = "1909"; - /// let bad_year_from_input = "190blarg"; - /// let good_year = good_year_from_input.parse().ok().unwrap_or_default(); - /// let bad_year = bad_year_from_input.parse().ok().unwrap_or_default(); - /// - /// assert_eq!(1909, good_year); - /// assert_eq!(0, bad_year); - /// ``` - /// - /// [default value]: Default::default - /// [`parse`]: str::parse - /// [`FromStr`]: crate::str::FromStr - #[inline] - #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn unwrap_or_default(self) -> T - where - T: ~const Default, - { - match self { - Some(x) => x, - None => Default::default(), - } - } -} - impl Option { /// Converts from `Option` (or `&Option`) to `Option<&T::Target>`. /// From 48a91a08d166d293fcc03fdc9f86fa30ecbcc51c Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:36:37 -0800 Subject: [PATCH 11/15] Move Option::as_deref --- library/core/src/option.rs | 54 ++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index d457d502c25..8feebe11e97 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -1072,6 +1072,32 @@ impl Option { } } + /// Converts from `Option` (or `&Option`) to `Option<&T::Target>`. + /// + /// Leaves the original Option in-place, creating a new one with a reference + /// to the original one, additionally coercing the contents via [`Deref`]. + /// + /// # Examples + /// + /// ``` + /// let x: Option = Some("hey".to_owned()); + /// assert_eq!(x.as_deref(), Some("hey")); + /// + /// let x: Option = None; + /// assert_eq!(x.as_deref(), None); + /// ``` + #[stable(feature = "option_deref", since = "1.40.0")] + #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] + pub const fn as_deref(&self) -> Option<&T::Target> + where + T: ~const Deref, + { + match self.as_ref() { + Some(t) => Some(t.deref()), + None => None, + } + } + ///////////////////////////////////////////////////////////////////////// // Iterator constructors ///////////////////////////////////////////////////////////////////////// @@ -1724,34 +1750,6 @@ impl Option<&mut T> { } } -impl Option { - /// Converts from `Option` (or `&Option`) to `Option<&T::Target>`. - /// - /// Leaves the original Option in-place, creating a new one with a reference - /// to the original one, additionally coercing the contents via [`Deref`]. - /// - /// # Examples - /// - /// ``` - /// let x: Option = Some("hey".to_owned()); - /// assert_eq!(x.as_deref(), Some("hey")); - /// - /// let x: Option = None; - /// assert_eq!(x.as_deref(), None); - /// ``` - #[stable(feature = "option_deref", since = "1.40.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn as_deref(&self) -> Option<&T::Target> - where - T: ~const Deref, - { - match self.as_ref() { - Some(t) => Some(t.deref()), - None => None, - } - } -} - impl Option { /// Converts from `Option` (or `&mut Option`) to `Option<&mut T::Target>`. /// From 9d65bc51c1ea5fc482cc42d79732043201bcf54a Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:36:55 -0800 Subject: [PATCH 12/15] Move Option::as_deref_mut --- library/core/src/option.rs | 54 ++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 8feebe11e97..c3bea55772f 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -1098,6 +1098,32 @@ impl Option { } } + /// Converts from `Option` (or `&mut Option`) to `Option<&mut T::Target>`. + /// + /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to + /// the inner type's [`Deref::Target`] type. + /// + /// # Examples + /// + /// ``` + /// let mut x: Option = Some("hey".to_owned()); + /// assert_eq!(x.as_deref_mut().map(|x| { + /// x.make_ascii_uppercase(); + /// x + /// }), Some("HEY".to_owned().as_mut_str())); + /// ``` + #[stable(feature = "option_deref", since = "1.40.0")] + #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] + pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target> + where + T: ~const DerefMut, + { + match self.as_mut() { + Some(t) => Some(t.deref_mut()), + None => None, + } + } + ///////////////////////////////////////////////////////////////////////// // Iterator constructors ///////////////////////////////////////////////////////////////////////// @@ -1750,34 +1776,6 @@ impl Option<&mut T> { } } -impl Option { - /// Converts from `Option` (or `&mut Option`) to `Option<&mut T::Target>`. - /// - /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to - /// the inner type's [`Deref::Target`] type. - /// - /// # Examples - /// - /// ``` - /// let mut x: Option = Some("hey".to_owned()); - /// assert_eq!(x.as_deref_mut().map(|x| { - /// x.make_ascii_uppercase(); - /// x - /// }), Some("HEY".to_owned().as_mut_str())); - /// ``` - #[stable(feature = "option_deref", since = "1.40.0")] - #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn as_deref_mut(&mut self) -> Option<&mut T::Target> - where - T: ~const DerefMut, - { - match self.as_mut() { - Some(t) => Some(t.deref_mut()), - None => None, - } - } -} - impl Option> { /// Transposes an `Option` of a [`Result`] into a [`Result`] of an `Option`. /// From 538fe4b28d3aca5657a95aadf65800d2237276d1 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:37:27 -0800 Subject: [PATCH 13/15] Consolidate impl Option<&T> --- library/core/src/option.rs | 59 +++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 29 deletions(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index c3bea55772f..9b3b27b68a3 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -1672,7 +1672,7 @@ impl Option<(T, U)> { } } -impl Option<&T> { +impl Option<&T> { /// Maps an `Option<&T>` to an `Option` by copying the contents of the /// option. /// @@ -1688,7 +1688,10 @@ impl Option<&T> { #[must_use = "`self` will be dropped if the result is not used"] #[stable(feature = "copied", since = "1.35.0")] #[rustc_const_unstable(feature = "const_option", issue = "67441")] - pub const fn copied(self) -> Option { + pub const fn copied(self) -> Option + where + T: Copy, + { // FIXME: this implementation, which sidesteps using `Option::map` since it's not const // ready yet, should be reverted when possible to avoid code repetition match self { @@ -1696,6 +1699,31 @@ impl Option<&T> { None => None, } } + + /// Maps an `Option<&T>` to an `Option` by cloning the contents of the + /// option. + /// + /// # Examples + /// + /// ``` + /// let x = 12; + /// let opt_x = Some(&x); + /// assert_eq!(opt_x, Some(&12)); + /// let cloned = opt_x.cloned(); + /// assert_eq!(cloned, Some(12)); + /// ``` + #[must_use = "`self` will be dropped if the result is not used"] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] + pub const fn cloned(self) -> Option + where + T: ~const Clone, + { + match self { + Some(t) => Some(t.clone()), + None => None, + } + } } impl Option<&mut T> { @@ -1722,33 +1750,6 @@ impl Option<&mut T> { } } -impl Option<&T> { - /// Maps an `Option<&T>` to an `Option` by cloning the contents of the - /// option. - /// - /// # Examples - /// - /// ``` - /// let x = 12; - /// let opt_x = Some(&x); - /// assert_eq!(opt_x, Some(&12)); - /// let cloned = opt_x.cloned(); - /// assert_eq!(cloned, Some(12)); - /// ``` - #[must_use = "`self` will be dropped if the result is not used"] - #[stable(feature = "rust1", since = "1.0.0")] - #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] - pub const fn cloned(self) -> Option - where - T: ~const Clone, - { - match self { - Some(t) => Some(t.clone()), - None => None, - } - } -} - impl Option<&mut T> { /// Maps an `Option<&mut T>` to an `Option` by cloning the contents of the /// option. From dc3291614a7e72b833dcae870f8c9b12ede15549 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 10:37:50 -0800 Subject: [PATCH 14/15] Consolidate impl Option<&mut T> --- library/core/src/option.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 9b3b27b68a3..0022df4f65f 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -1726,7 +1726,7 @@ impl Option<&T> { } } -impl Option<&mut T> { +impl Option<&mut T> { /// Maps an `Option<&mut T>` to an `Option` by copying the contents of the /// option. /// @@ -1742,15 +1742,16 @@ impl Option<&mut T> { #[must_use = "`self` will be dropped if the result is not used"] #[stable(feature = "copied", since = "1.35.0")] #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] - pub const fn copied(self) -> Option { + pub const fn copied(self) -> Option + where + T: Copy, + { match self { Some(&mut t) => Some(t), None => None, } } -} -impl Option<&mut T> { /// Maps an `Option<&mut T>` to an `Option` by cloning the contents of the /// option. /// From 5960f7a617647f5204e924304b40592ab4f9f51d Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 30 Dec 2021 11:15:50 -0800 Subject: [PATCH 15/15] UI test updates for Result and Option method moves --- .../option-as_deref_mut.stderr | 1 - .../result-as_deref_mut.stderr | 1 - .../method-help-unsatisfied-bound.rs | 2 +- .../method-help-unsatisfied-bound.stderr | 20 +++++++++---------- 4 files changed, 10 insertions(+), 14 deletions(-) diff --git a/src/test/ui/issues/issue-50264-inner-deref-trait/option-as_deref_mut.stderr b/src/test/ui/issues/issue-50264-inner-deref-trait/option-as_deref_mut.stderr index e4e9705b07d..52ee1db5b15 100644 --- a/src/test/ui/issues/issue-50264-inner-deref-trait/option-as_deref_mut.stderr +++ b/src/test/ui/issues/issue-50264-inner-deref-trait/option-as_deref_mut.stderr @@ -5,7 +5,6 @@ LL | let _result = &mut Some(42).as_deref_mut(); | ^^^^^^^^^^^^ method cannot be called on `Option<{integer}>` due to unsatisfied trait bounds | = note: the following trait bounds were not satisfied: - `{integer}: DerefMut` `{integer}: Deref` error: aborting due to previous error diff --git a/src/test/ui/issues/issue-50264-inner-deref-trait/result-as_deref_mut.stderr b/src/test/ui/issues/issue-50264-inner-deref-trait/result-as_deref_mut.stderr index 98a7091dd05..018557881ef 100644 --- a/src/test/ui/issues/issue-50264-inner-deref-trait/result-as_deref_mut.stderr +++ b/src/test/ui/issues/issue-50264-inner-deref-trait/result-as_deref_mut.stderr @@ -5,7 +5,6 @@ LL | let _result = &mut Ok(42).as_deref_mut(); | ^^^^^^^^^^^^ method cannot be called on `Result<{integer}, _>` due to unsatisfied trait bounds | = note: the following trait bounds were not satisfied: - `{integer}: DerefMut` `{integer}: Deref` error: aborting due to previous error diff --git a/src/test/ui/mismatched_types/method-help-unsatisfied-bound.rs b/src/test/ui/mismatched_types/method-help-unsatisfied-bound.rs index f85c10d78c5..6303c6e6a5d 100644 --- a/src/test/ui/mismatched_types/method-help-unsatisfied-bound.rs +++ b/src/test/ui/mismatched_types/method-help-unsatisfied-bound.rs @@ -3,5 +3,5 @@ struct Foo; fn main() { let a: Result<(), Foo> = Ok(()); a.unwrap(); - //~^ ERROR the method + //~^ ERROR `Foo` doesn't implement `Debug` } diff --git a/src/test/ui/mismatched_types/method-help-unsatisfied-bound.stderr b/src/test/ui/mismatched_types/method-help-unsatisfied-bound.stderr index 596b7bfe79c..dc73bcd6e4d 100644 --- a/src/test/ui/mismatched_types/method-help-unsatisfied-bound.stderr +++ b/src/test/ui/mismatched_types/method-help-unsatisfied-bound.stderr @@ -1,19 +1,17 @@ -error[E0599]: the method `unwrap` exists for enum `Result<(), Foo>`, but its trait bounds were not satisfied +error[E0277]: `Foo` doesn't implement `Debug` --> $DIR/method-help-unsatisfied-bound.rs:5:7 | -LL | struct Foo; - | ----------- doesn't satisfy `Foo: Debug` -... LL | a.unwrap(); - | ^^^^^^ method cannot be called on `Result<(), Foo>` due to unsatisfied trait bounds + | ^^^^^^ `Foo` cannot be formatted using `{:?}` | - = note: the following trait bounds were not satisfied: - `Foo: Debug` -help: consider annotating `Foo` with `#[derive(Debug)]` - | -LL | #[derive(Debug)] + = help: the trait `Debug` is not implemented for `Foo` + = note: add `#[derive(Debug)]` to `Foo` or manually `impl Debug for Foo` +note: required by a bound in `Result::::unwrap` + --> $SRC_DIR/core/src/result.rs:LL:COL | +LL | E: fmt::Debug, + | ^^^^^^^^^^ required by this bound in `Result::::unwrap` error: aborting due to previous error -For more information about this error, try `rustc --explain E0599`. +For more information about this error, try `rustc --explain E0277`.