Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 #![cfg_attr(test, deny(warnings))]
2 #![deny(missing_docs)]
3
4 //! # unreachable
5 //!
6 //! An unreachable code optimization hint in stable rust, and some useful
7 //! extension traits for `Option` and `Result`.
8 //!
9
10 #![no_std]
11
12 extern crate void;
13
14 use core::mem;
15
16 /// Hint to the optimizer that any code path which calls this function is
17 /// statically unreachable and can be removed.
18 ///
19 /// Calling this function in reachable code invokes undefined behavior. Be
20 /// very, very sure this is what you want; often, a simple `panic!` is more
21 /// suitable.
22 #[inline]
23 pub unsafe fn unreachable() -> ! {
24 let x: &void::Void = mem::transmute(1usize);
25 void::unreachable(*x)
26 }
27
28 /// An extension trait for `Option<T>` providing unchecked unwrapping methods.
29 pub trait UncheckedOptionExt<T> {
30 /// Get the value out of this Option without checking for None.
31 unsafe fn unchecked_unwrap(self) -> T;
32
33 /// Assert that this Option is a None to the optimizer.
34 unsafe fn unchecked_unwrap_none(self);
35 }
36
37 /// An extension trait for `Result<T, E>` providing unchecked unwrapping methods.
38 pub trait UncheckedResultExt<T, E> {
39 /// Get the value out of this Result without checking for Err.
40 unsafe fn unchecked_unwrap_ok(self) -> T;
41
42 /// Get the error out of this Result without checking for Ok.
43 unsafe fn unchecked_unwrap_err(self) -> E;
44 }
45
46 impl<T> UncheckedOptionExt<T> for Option<T> {
47 unsafe fn unchecked_unwrap(self) -> T {
48 match self {
49 Some(x) => x,
50 None => unreachable()
51 }
52 }
53
54 unsafe fn unchecked_unwrap_none(self) {
55 match self {
56 Some(_) => unreachable(),
57 None => ()
58 }
59 }
60 }
61
62 impl<T, E> UncheckedResultExt<T, E> for Result<T, E> {
63 unsafe fn unchecked_unwrap_ok(self) -> T {
64 match self {
65 Ok(x) => x,
66 Err(_) => unreachable()
67 }
68 }
69
70 unsafe fn unchecked_unwrap_err(self) -> E {
71 match self {
72 Ok(_) => unreachable(),
73 Err(e) => e
74 }
75 }
76 }
77