]> git.proxmox.com Git - rustc.git/blob - vendor/thread_local/src/unreachable.rs
New upstream version 1.32.0~beta.2+dfsg1
[rustc.git] / vendor / thread_local / src / unreachable.rs
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 //! # unreachable
9 //! inlined from https://github.com/reem/rust-unreachable/
10 //!
11 //! An unreachable code optimization hint in stable rust, and some useful
12 //! extension traits for `Option` and `Result`.
13 //!
14
15 /// Hint to the optimizer that any code path which calls this function is
16 /// statically unreachable and can be removed.
17 ///
18 /// Calling this function in reachable code invokes undefined behavior. Be
19 /// very, very sure this is what you want; often, a simple `panic!` is more
20 /// suitable.
21 #[inline]
22 pub unsafe fn unreachable() -> ! {
23 /// The empty type for cases which can't occur.
24 enum Void { }
25 let x: &Void = ::std::mem::transmute(1usize);
26 match *x {}
27 }
28
29 /// An extension trait for `Option<T>` providing unchecked unwrapping methods.
30 pub trait UncheckedOptionExt<T> {
31 /// Get the value out of this Option without checking for None.
32 unsafe fn unchecked_unwrap(self) -> T;
33
34 /// Assert that this Option is a None to the optimizer.
35 unsafe fn unchecked_unwrap_none(self);
36 }
37
38 /// An extension trait for `Result<T, E>` providing unchecked unwrapping methods.
39 pub trait UncheckedResultExt<T, E> {
40 /// Get the value out of this Result without checking for Err.
41 unsafe fn unchecked_unwrap_ok(self) -> T;
42
43 /// Get the error out of this Result without checking for Ok.
44 unsafe fn unchecked_unwrap_err(self) -> E;
45 }
46
47 impl<T> UncheckedOptionExt<T> for Option<T> {
48 unsafe fn unchecked_unwrap(self) -> T {
49 match self {
50 Some(x) => x,
51 None => unreachable()
52 }
53 }
54
55 unsafe fn unchecked_unwrap_none(self) {
56 if self.is_some() { unreachable() }
57 }
58 }
59
60 impl<T, E> UncheckedResultExt<T, E> for Result<T, E> {
61 unsafe fn unchecked_unwrap_ok(self) -> T {
62 match self {
63 Ok(x) => x,
64 Err(_) => unreachable()
65 }
66 }
67
68 unsafe fn unchecked_unwrap_err(self) -> E {
69 match self {
70 Ok(_) => unreachable(),
71 Err(e) => e
72 }
73 }
74 }