1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//! This crate provides [`likely`] and [`unlikely`] functions that work as compiler hints for branching in stable rust.
//! They are taken directly from the [`hashbrown`](https://crates.io/crates/hashbrown) crate, all credit belongs to them.
//! These functions enable constructions like
//! ```
//! # use branch_hints::likely;
//! # let condition = true;
//! if likely(condition) {
//! // main code
//! } else {
//! // error handling code
//! }
//! ```
//! and they should be optimized away by the compiler.
//!
//! ## Notes
//!
//! This is a very minimal crate. If you want more comprehensive functionality, take a look at the [`likely_stable`](https://docs.rs/likely_stable/latest/likely_stable/) crate.
//!
//! Verify for yourself with benchmarks if these functions do anything for you,
//! as even the unstable intrinsics sometimes don't do anything: <https://github.com/rust-lang/rust/issues/88767>.
//! This implementation of them was removed from `hashbrown` for this reason: <https://github.com/rust-lang/hashbrown/issues/482>.
// The branch hint functions `core::intrinsics::likely` and `core::intrinsics::unlikely` are only available on nightly.
// On stable we can use #[cold] to get an equivalent effect: this attribute
// suggests that the function is unlikely to be called. This function should
// be optimized away by the compiler.
/// Returns the boolean passed to it while hinting to the compiler that it is likely to be true.
/// This function brings [`likely`](core::intrinsics::likely) to stable Rust.
/// # Example
/// ```
/// # use branch_hints::likely;
/// use rand::prelude::*;
/// if likely(rand::random::<u64>() > 0) {
/// println!("It's nonzero!");
/// }
/// ```
/// Returns the boolean passed to it while hinting to the compiler that it is unlikely to be true.
/// This function brings [`unlikely`](core::intrinsics::unlikely) to stable Rust.
/// # Example
/// ```
/// # use branch_hints::unlikely;
/// use rand::prelude::*;
/// if unlikely(rand::random::<u64>() == 42) {
/// println!("We found the meaning of life, the universe, and everything");
/// }
/// ```