about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorJosh Stone <jistone@redhat.com>2019-07-11 12:05:14 -0700
committerJosh Stone <jistone@redhat.com>2019-07-11 12:05:14 -0700
commit5a7e7309356c70d04ac62765c395978ffd49cf5e (patch)
treeae350c5f791f3b4a46aeed303bd82cb41f00a25e /src/libcore
parent97b1128589fdaa786a7cf65c5a6ff7ed37a1d2f3 (diff)
downloadrust-5a7e7309356c70d04ac62765c395978ffd49cf5e.tar.gz
rust-5a7e7309356c70d04ac62765c395978ffd49cf5e.zip
Add Option::expect_none(msg) and unwrap_none()
These are `Option` analogues to `Result::expect_err` and `unwrap_err`.
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/option.rs95
1 files changed, 94 insertions, 1 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs
index 29169951e46..6156b4cd393 100644
--- a/src/libcore/option.rs
+++ b/src/libcore/option.rs
@@ -136,7 +136,7 @@
 #![stable(feature = "rust1", since = "1.0.0")]
 
 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
-use crate::{convert, hint, mem, ops::{self, Deref}};
+use crate::{convert, fmt, hint, mem, ops::{self, Deref}};
 use crate::pin::Pin;
 
 // 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> {
     }
 }
 
+impl<T: fmt::Debug> Option<T> {
+    /// Unwraps an option, expecting [`None`] and returning nothing.
+    ///
+    /// # Panics
+    ///
+    /// Panics if the value is a [`Some`], with a panic message including the
+    /// passed message, and the content of the [`Some`].
+    ///
+    /// [`Some`]: #variant.Some
+    /// [`None`]: #variant.None
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(option_expect_none)]
+    ///
+    /// use std::collections::HashMap;
+    /// let mut squares = HashMap::new();
+    /// for i in -10..=10 {
+    ///     // This will not panic, since all keys are unique.
+    ///     squares.insert(i, i * i).expect_none("duplicate key");
+    /// }
+    /// ```
+    ///
+    /// ```{.should_panic}
+    /// #![feature(option_expect_none)]
+    ///
+    /// use std::collections::HashMap;
+    /// let mut sqrts = HashMap::new();
+    /// for i in -10..=10 {
+    ///     // This will panic, since both negative and positive `i` will
+    ///     // insert the same `i * i` key, returning the old `Some(i)`.
+    ///     sqrts.insert(i * i, i).expect_none("duplicate key");
+    /// }
+    /// ```
+    #[inline]
+    #[unstable(feature = "option_expect_none", reason = "newly added", issue = "0")]
+    pub fn expect_none(self, msg: &str) {
+        if let Some(val) = self {
+            expect_none_failed(msg, val);
+        }
+    }
+
+    /// Unwraps an option, expecting [`None`] and returning nothing.
+    ///
+    /// # Panics
+    ///
+    /// Panics if the value is a [`Some`], with a custom panic message provided
+    /// by the [`Some`]'s value.
+    ///
+    /// [`Some(v)`]: #variant.Some
+    /// [`None`]: #variant.None
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// #![feature(option_unwrap_none)]
+    ///
+    /// use std::collections::HashMap;
+    /// let mut squares = HashMap::new();
+    /// for i in -10..=10 {
+    ///     // This will not panic, since all keys are unique.
+    ///     squares.insert(i, i * i).unwrap_none();
+    /// }
+    /// ```
+    ///
+    /// ```{.should_panic}
+    /// #![feature(option_unwrap_none)]
+    ///
+    /// use std::collections::HashMap;
+    /// let mut sqrts = HashMap::new();
+    /// for i in -10..=10 {
+    ///     // This will panic, since both negative and positive `i` will
+    ///     // insert the same `i * i` key, returning the old `Some(i)`.
+    ///     sqrts.insert(i * i, i).unwrap_none();
+    /// }
+    /// ```
+    #[inline]
+    #[unstable(feature = "option_unwrap_none", reason = "newly added", issue = "0")]
+    pub fn unwrap_none(self) {
+        if let Some(val) = self {
+            expect_none_failed("called `Option::unwrap_none()` on a `Some` value", val);
+        }
+    }
+}
+
 impl<T: Default> Option<T> {
     /// Returns the contained value or a default
     ///
@@ -1064,6 +1150,13 @@ fn expect_failed(msg: &str) -> ! {
     panic!("{}", msg)
 }
 
+// This is a separate function to reduce the code size of .expect_none() itself.
+#[inline(never)]
+#[cold]
+fn expect_none_failed<T: fmt::Debug>(msg: &str, value: T) -> ! {
+    panic!("{}: {:?}", msg, value)
+}
+
 /////////////////////////////////////////////////////////////////////////////
 // Trait implementations
 /////////////////////////////////////////////////////////////////////////////