1 // Copyright 2017 Amanieu d'Antras
2 //
3 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 // http://opensource.org/licenses/MIT>, at your option. This file may not be
6 // copied, modified, or distributed except according to those terms.
7 
8 use std::hint::unreachable_unchecked;
9 
10 /// An extension trait for `Option<T>` providing unchecked unwrapping methods.
11 pub trait UncheckedOptionExt<T> {
12     /// Get the value out of this Option without checking for None.
unchecked_unwrap(self) -> T13     unsafe fn unchecked_unwrap(self) -> T;
14 
15     /// Assert that this Option is a None to the optimizer.
unchecked_unwrap_none(self)16     unsafe fn unchecked_unwrap_none(self);
17 }
18 
19 /// An extension trait for `Result<T, E>` providing unchecked unwrapping methods.
20 pub trait UncheckedResultExt<T, E> {
21     /// Get the value out of this Result without checking for Err.
unchecked_unwrap_ok(self) -> T22     unsafe fn unchecked_unwrap_ok(self) -> T;
23 
24     /// Get the error out of this Result without checking for Ok.
unchecked_unwrap_err(self) -> E25     unsafe fn unchecked_unwrap_err(self) -> E;
26 }
27 
28 impl<T> UncheckedOptionExt<T> for Option<T> {
unchecked_unwrap(self) -> T29     unsafe fn unchecked_unwrap(self) -> T {
30         match self {
31             Some(x) => x,
32             None => unreachable_unchecked(),
33         }
34     }
35 
unchecked_unwrap_none(self)36     unsafe fn unchecked_unwrap_none(self) {
37         if self.is_some() {
38             unreachable_unchecked()
39         }
40     }
41 }
42 
43 impl<T, E> UncheckedResultExt<T, E> for Result<T, E> {
unchecked_unwrap_ok(self) -> T44     unsafe fn unchecked_unwrap_ok(self) -> T {
45         match self {
46             Ok(x) => x,
47             Err(_) => unreachable_unchecked(),
48         }
49     }
50 
unchecked_unwrap_err(self) -> E51     unsafe fn unchecked_unwrap_err(self) -> E {
52         match self {
53             Ok(_) => unreachable_unchecked(),
54             Err(e) => e,
55         }
56     }
57 }
58