Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 38 additions & 2 deletions library/core/src/hint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ pub const fn must_use<T>(value: T) -> T {
/// }
/// }
/// ```
#[unstable(feature = "likely_unlikely", issue = "136873")]
#[unstable(feature = "likely_unlikely", issue = "151619")]
#[inline(always)]
pub const fn likely(b: bool) -> bool {
crate::intrinsics::likely(b)
Expand Down Expand Up @@ -699,7 +699,7 @@ pub const fn likely(b: bool) -> bool {
/// }
/// }
/// ```
#[unstable(feature = "likely_unlikely", issue = "136873")]
#[unstable(feature = "likely_unlikely", issue = "151619")]
#[inline(always)]
pub const fn unlikely(b: bool) -> bool {
crate::intrinsics::unlikely(b)
Expand All @@ -708,6 +708,10 @@ pub const fn unlikely(b: bool) -> bool {
/// Hints to the compiler that given path is cold, i.e., unlikely to be taken. The compiler may
/// choose to optimize paths that are not cold at the expense of paths that are cold.
///
/// Note that like all hints, the exact effect to codegen is not guaranteed. Using `cold_path`
/// can actually *decrease* performance if the branch is called more than expected. It is advisable
/// to perform benchmarks to tell if this function is useful.
///
/// # Examples
///
/// ```
Expand All @@ -732,6 +736,38 @@ pub const fn unlikely(b: bool) -> bool {
/// }
/// }
/// ```
///
/// This can also be used to implement `likely` and `unlikely` helpers to hint the condition rather
/// than the branch:
///
/// ```
/// #![feature(cold_path)]
/// use core::hint::cold_path;
///
/// #[inline(always)]
/// pub const fn likely(b: bool) -> bool {
/// if !b {
/// cold_path();
/// }
/// b
/// }
///
/// #[inline(always)]
/// pub const fn unlikely(b: bool) -> bool {
/// if b {
/// cold_path();
/// }
/// b
/// }
///
/// fn foo(x: i32) {
/// if likely(x > 0) {
/// println!("this branch is likely to be taken");
/// } else {
/// println!("this branch is unlikely to be taken");
/// }
/// }
/// ```
#[unstable(feature = "cold_path", issue = "136873")]
#[inline(always)]
pub const fn cold_path() {
Expand Down
Loading