Skip to content

Commit 8bf5a45

Browse files
committed
Add unsafe Option::unwrap_unchecked()
This adds a new function to the Option enum which allows for an unchecked unwrap. In some cases, a developer may be able to statically determine that an Option must be Some(V) but the compiler cannot. Being able to forgo a conditional branch is desirable, even if unsafe.
1 parent da2276e commit 8bf5a45

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/libcore/option.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ use self::Option::*;
148148
use clone::Clone;
149149
use cmp::{Eq, Ord};
150150
use default::Default;
151+
use intrinsics::unreachable;
151152
use iter::ExactSizeIterator;
152153
use iter::{Iterator, DoubleEndedIterator, FromIterator, IntoIterator};
153154
use mem;
@@ -398,6 +399,24 @@ impl<T> Option<T> {
398399
}
399400
}
400401

402+
/// Moves the value `v` out of the `Option<T>` without checking for None.
403+
///
404+
/// # Safety note
405+
///
406+
/// Because it is undefined behavior to call this on a None, this function
407+
/// is unsafe.
408+
#[inline]
409+
#[unstable(feature = "core")]
410+
pub unsafe fn unwrap_unchecked(self) -> T {
411+
if self.is_none() {
412+
if cfg!(debug) {
413+
panic!("called `Option::unwrap_unchecked()` on a `None` value");
414+
}
415+
unreachable();
416+
}
417+
unwrap(self)
418+
}
419+
401420
/////////////////////////////////////////////////////////////////////////
402421
// Transforming contained values
403422
/////////////////////////////////////////////////////////////////////////

src/libcoretest/option.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,13 @@ fn test_unwrap_or_else() {
170170
assert_eq!(x.unwrap_or_else(|| 2), 2);
171171
}
172172

173+
#[test]
174+
fn test_unwrap_unchecked() {
175+
assert_eq!(unsafe { Some(1).unwrap_unchecked() }, 1);
176+
let s = unsafe { Some("hello".to_string()).unwrap_unchecked() };
177+
assert_eq!(s, "hello");
178+
}
179+
173180
#[test]
174181
fn test_iter() {
175182
let val = 5;

0 commit comments

Comments
 (0)