frozen_core/hints.rs
1//! Implementation of branch preditor hints
2
3/// empty function used as a placeholder to influence branch prediction
4#[cold]
5#[inline]
6const fn cold_fn() {}
7
8/// Branch predictor hint, which marks given condition as *likely* to be
9///
10/// # Example
11///
12/// ```
13/// use frozen_core::hints::likely;
14/// assert!(likely(true));
15/// assert!(!likely(false));
16/// ```
17#[inline]
18pub const fn likely(b: bool) -> bool {
19 if !b {
20 cold_fn();
21 }
22 b
23}
24
25/// Branch predictor hint, which marks given condition as *unlikely* to be
26///
27/// # Example
28///
29/// ```
30/// use frozen_core::hints::unlikely;
31/// assert!(unlikely(true));
32/// assert!(!unlikely(false));
33/// ```
34#[inline]
35pub const fn unlikely(b: bool) -> bool {
36 if b {
37 cold_fn();
38 }
39 b
40}
41
42#[cfg(test)]
43mod hints {
44 use super::*;
45
46 #[test]
47 fn sanity_checks_for_likely() {
48 assert!(likely(true));
49 assert!(!likely(false));
50 }
51
52 #[test]
53 fn sanity_checks_for_unlikely() {
54 assert!(unlikely(true));
55 assert!(!unlikely(false));
56 }
57}