Skip to content

Commit 5a7e730

Browse files
committed
Add Option::expect_none(msg) and unwrap_none()
These are `Option` analogues to `Result::expect_err` and `unwrap_err`.
1 parent 97b1128 commit 5a7e730

File tree

1 file changed

+94
-1
lines changed

1 file changed

+94
-1
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
@@ -972,6 +972,92 @@ impl<T: Clone> Option<&mut T> {
972972
}
973973
}
974974

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

1153+
// This is a separate function to reduce the code size of .expect_none() itself.
1154+
#[inline(never)]
1155+
#[cold]
1156+
fn expect_none_failed<T: fmt::Debug>(msg: &str, value: T) -> ! {
1157+
panic!("{}: {:?}", msg, value)
1158+
}
1159+
10671160
/////////////////////////////////////////////////////////////////////////////
10681161
// Trait implementations
10691162
/////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)