Skip to content

Commit d56128d

Browse files
committed
Auto merge of #62596 - cuviper:expect_none, r=rkruppe
Add Option::expect_none(msg) and unwrap_none() These are `Option` analogues to `Result::expect_err` and `unwrap_err`.
2 parents bf16480 + 74c8d98 commit d56128d

File tree

2 files changed

+99
-6
lines changed

2 files changed

+99
-6
lines changed

src/libcore/option.rs

+94-1
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@
136136
#![stable(feature = "rust1", since = "1.0.0")]
137137

138138
use crate::iter::{FromIterator, FusedIterator, TrustedLen};
139-
use crate::{convert, hint, mem, ops::{self, Deref}};
139+
use crate::{convert, fmt, hint, mem, ops::{self, Deref}};
140140
use crate::pin::Pin;
141141

142142
// Note that this is not a lang item per se, but it has a hidden dependency on
@@ -977,6 +977,92 @@ impl<T: Clone> Option<&mut T> {
977977
}
978978
}
979979

980+
impl<T: fmt::Debug> Option<T> {
981+
/// Unwraps an option, expecting [`None`] and returning nothing.
982+
///
983+
/// # Panics
984+
///
985+
/// Panics if the value is a [`Some`], with a panic message including the
986+
/// passed message, and the content of the [`Some`].
987+
///
988+
/// [`Some`]: #variant.Some
989+
/// [`None`]: #variant.None
990+
///
991+
/// # Examples
992+
///
993+
/// ```
994+
/// #![feature(option_expect_none)]
995+
///
996+
/// use std::collections::HashMap;
997+
/// let mut squares = HashMap::new();
998+
/// for i in -10..=10 {
999+
/// // This will not panic, since all keys are unique.
1000+
/// squares.insert(i, i * i).expect_none("duplicate key");
1001+
/// }
1002+
/// ```
1003+
///
1004+
/// ```{.should_panic}
1005+
/// #![feature(option_expect_none)]
1006+
///
1007+
/// use std::collections::HashMap;
1008+
/// let mut sqrts = HashMap::new();
1009+
/// for i in -10..=10 {
1010+
/// // This will panic, since both negative and positive `i` will
1011+
/// // insert the same `i * i` key, returning the old `Some(i)`.
1012+
/// sqrts.insert(i * i, i).expect_none("duplicate key");
1013+
/// }
1014+
/// ```
1015+
#[inline]
1016+
#[unstable(feature = "option_expect_none", reason = "newly added", issue = "62633")]
1017+
pub fn expect_none(self, msg: &str) {
1018+
if let Some(val) = self {
1019+
expect_none_failed(msg, &val);
1020+
}
1021+
}
1022+
1023+
/// Unwraps an option, expecting [`None`] and returning nothing.
1024+
///
1025+
/// # Panics
1026+
///
1027+
/// Panics if the value is a [`Some`], with a custom panic message provided
1028+
/// by the [`Some`]'s value.
1029+
///
1030+
/// [`Some(v)`]: #variant.Some
1031+
/// [`None`]: #variant.None
1032+
///
1033+
/// # Examples
1034+
///
1035+
/// ```
1036+
/// #![feature(option_unwrap_none)]
1037+
///
1038+
/// use std::collections::HashMap;
1039+
/// let mut squares = HashMap::new();
1040+
/// for i in -10..=10 {
1041+
/// // This will not panic, since all keys are unique.
1042+
/// squares.insert(i, i * i).unwrap_none();
1043+
/// }
1044+
/// ```
1045+
///
1046+
/// ```{.should_panic}
1047+
/// #![feature(option_unwrap_none)]
1048+
///
1049+
/// use std::collections::HashMap;
1050+
/// let mut sqrts = HashMap::new();
1051+
/// for i in -10..=10 {
1052+
/// // This will panic, since both negative and positive `i` will
1053+
/// // insert the same `i * i` key, returning the old `Some(i)`.
1054+
/// sqrts.insert(i * i, i).unwrap_none();
1055+
/// }
1056+
/// ```
1057+
#[inline]
1058+
#[unstable(feature = "option_unwrap_none", reason = "newly added", issue = "62633")]
1059+
pub fn unwrap_none(self) {
1060+
if let Some(val) = self {
1061+
expect_none_failed("called `Option::unwrap_none()` on a `Some` value", &val);
1062+
}
1063+
}
1064+
}
1065+
9801066
impl<T: Default> Option<T> {
9811067
/// Returns the contained value or a default
9821068
///
@@ -1069,6 +1155,13 @@ fn expect_failed(msg: &str) -> ! {
10691155
panic!("{}", msg)
10701156
}
10711157

1158+
// This is a separate function to reduce the code size of .expect_none() itself.
1159+
#[inline(never)]
1160+
#[cold]
1161+
fn expect_none_failed(msg: &str, value: &dyn fmt::Debug) -> ! {
1162+
panic!("{}: {:?}", msg, value)
1163+
}
1164+
10721165
/////////////////////////////////////////////////////////////////////////////
10731166
// Trait implementations
10741167
/////////////////////////////////////////////////////////////////////////////

src/libcore/result.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -849,7 +849,7 @@ impl<T, E: fmt::Debug> Result<T, E> {
849849
pub fn unwrap(self) -> T {
850850
match self {
851851
Ok(t) => t,
852-
Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
852+
Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", &e),
853853
}
854854
}
855855

@@ -876,7 +876,7 @@ impl<T, E: fmt::Debug> Result<T, E> {
876876
pub fn expect(self, msg: &str) -> T {
877877
match self {
878878
Ok(t) => t,
879-
Err(e) => unwrap_failed(msg, e),
879+
Err(e) => unwrap_failed(msg, &e),
880880
}
881881
}
882882
}
@@ -908,7 +908,7 @@ impl<T: fmt::Debug, E> Result<T, E> {
908908
#[stable(feature = "rust1", since = "1.0.0")]
909909
pub fn unwrap_err(self) -> E {
910910
match self {
911-
Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
911+
Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", &t),
912912
Err(e) => e,
913913
}
914914
}
@@ -935,7 +935,7 @@ impl<T: fmt::Debug, E> Result<T, E> {
935935
#[stable(feature = "result_expect_err", since = "1.17.0")]
936936
pub fn expect_err(self, msg: &str) -> E {
937937
match self {
938-
Ok(t) => unwrap_failed(msg, t),
938+
Ok(t) => unwrap_failed(msg, &t),
939939
Err(e) => e,
940940
}
941941
}
@@ -1047,7 +1047,7 @@ impl<T, E> Result<Option<T>, E> {
10471047
// This is a separate function to reduce the code size of the methods
10481048
#[inline(never)]
10491049
#[cold]
1050-
fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
1050+
fn unwrap_failed(msg: &str, error: &dyn fmt::Debug) -> ! {
10511051
panic!("{}: {:?}", msg, error)
10521052
}
10531053

0 commit comments

Comments
 (0)