Created
October 12, 2019 16:37
-
-
Save DutchGhost/ebe9377bd455e84a0f508a45cc7cbf93 to your computer and use it in GitHub Desktop.
Compiler hints
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #![no_std] | |
| /// Fakes a value of type `T`. | |
| #[inline] | |
| pub const unsafe fn fake_type<T>() -> T { | |
| cold(); | |
| unreachable() | |
| } | |
| /// Tells the compiler this code is unreachable. | |
| #[inline] | |
| pub const unsafe fn unreachable() -> ! { | |
| cold(); | |
| fake_type() | |
| } | |
| /// Suggests the compiler this code is unlikely to be called. | |
| /// See [cold](https://doc.rust-lang.org/nightly/reference/attributes/codegen.html#the-cold-attribute) for more. | |
| #[inline] | |
| #[cold] | |
| pub const fn cold() {} | |
| /// Unsafely assumes the value of an expression to be `true`. | |
| #[inline(always)] | |
| pub unsafe fn assume(b: bool) { | |
| if !b { | |
| unreachable() | |
| } | |
| } | |
| /// Tells the compiler this `bool` is probably false. | |
| #[inline(always)] | |
| pub fn unlikely(b: bool) -> bool { | |
| if b { | |
| cold() | |
| } | |
| b | |
| } | |
| /// Tells the compiler this `bool` is probably true. | |
| #[inline(always)] | |
| pub fn likely(b: bool) -> bool { | |
| if !b { | |
| cold() | |
| } | |
| b | |
| } | |
| #[macro_export] | |
| macro_rules! assume { | |
| ($x:expr) => { | |
| if !$x { | |
| unreachable!("Assumption was wrong"); | |
| } | |
| } | |
| } | |
| #[macro_export] | |
| macro_rules! debug_assume { | |
| ($x:expr) => { | |
| if cfg!(debug_assertions) { | |
| assume!($x) | |
| } else { | |
| if !$x { | |
| unsafe { | |
| $crate::unreachable() | |
| } | |
| } | |
| } | |
| } | |
| } | |
| #[cfg(test)] | |
| mod tests { | |
| use super::{assume, debug_assume}; | |
| #[test] | |
| fn assume_success() { | |
| assume!(true); | |
| } | |
| #[test] | |
| #[should_panic] | |
| fn assume_fail() { | |
| assume!(false); | |
| } | |
| #[test] | |
| fn debug_assume_success() { | |
| debug_assume!(true); | |
| } | |
| #[test] | |
| #[should_panic] | |
| fn debug_assume_fail() { | |
| debug_assume!(false); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment