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
8use std::hint::unreachable_unchecked;
9
10/// An extension trait for `Option<T>` providing unchecked unwrapping methods.
11pub trait UncheckedOptionExt<T> {
12 /// Get the value out of this Option without checking for None.
13 unsafe fn unchecked_unwrap(self) -> T;
14
15 /// Assert that this Option is a None to the optimizer.
16 unsafe fn unchecked_unwrap_none(self);
17}
18
19/// An extension trait for `Result<T, E>` providing unchecked unwrapping methods.
20pub trait UncheckedResultExt<T, E> {
21 /// Get the value out of this Result without checking for Err.
22 unsafe fn unchecked_unwrap_ok(self) -> T;
23
24 /// Get the error out of this Result without checking for Ok.
25 unsafe fn unchecked_unwrap_err(self) -> E;
26}
27
28impl<T> UncheckedOptionExt<T> for Option<T> {
29 unsafe fn unchecked_unwrap(self) -> T {
30 match self {
31 Some(x: T) => x,
32 None => unreachable_unchecked(),
33 }
34 }
35
36 unsafe fn unchecked_unwrap_none(self) {
37 if self.is_some() {
38 unreachable_unchecked()
39 }
40 }
41}
42
43impl<T, E> UncheckedResultExt<T, E> for Result<T, E> {
44 unsafe fn unchecked_unwrap_ok(self) -> T {
45 match self {
46 Ok(x: T) => x,
47 Err(_) => unreachable_unchecked(),
48 }
49 }
50
51 unsafe fn unchecked_unwrap_err(self) -> E {
52 match self {
53 Ok(_) => unreachable_unchecked(),
54 Err(e: E) => e,
55 }
56 }
57}
58