|
| 1 | +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution and at |
| 3 | +// http://rust-lang.org/COPYRIGHT. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 8 | +// option. This file may not be copied, modified, or distributed |
| 9 | +// except according to those terms. |
| 10 | + |
| 11 | +#![stable(feature = "core_hint", since = "1.27.0")] |
| 12 | + |
| 13 | +//! Hints to compiler that affects how code should be emitted or optimized. |
| 14 | +
|
| 15 | +use intrinsics; |
| 16 | + |
| 17 | +/// Informs the compiler that this point in the code is not reachable, enabling |
| 18 | +/// further optimizations. |
| 19 | +/// |
| 20 | +/// # Safety |
| 21 | +/// |
| 22 | +/// Reaching this function is completely *undefined behavior* (UB). In |
| 23 | +/// particular, the compiler assumes that all UB must never happen, and |
| 24 | +/// therefore will eliminate all branches that reach to a call to |
| 25 | +/// `unreachable_unchecked()`. |
| 26 | +/// |
| 27 | +/// Like all instances of UB, if this assumption turns out to be wrong, i.e. the |
| 28 | +/// `unreachable_unchecked()` call is actually reachable among all possible |
| 29 | +/// control flow, the compiler will apply the wrong optimization strategy, and |
| 30 | +/// may sometimes even corrupt seemingly unrelated code, causing |
| 31 | +/// difficult-to-debug problems. |
| 32 | +/// |
| 33 | +/// Use this function only when you can prove that the code will never call it. |
| 34 | +/// |
| 35 | +/// The [`unreachable!()`] macro is the safe counterpart of this function, which |
| 36 | +/// will panic instead when executed. |
| 37 | +/// |
| 38 | +/// [`unreachable!()`]: ../macro.unreachable.html |
| 39 | +/// |
| 40 | +/// # Example |
| 41 | +/// |
| 42 | +/// ``` |
| 43 | +/// fn div_1(a: u32, b: u32) -> u32 { |
| 44 | +/// use std::hint::unreachable_unchecked; |
| 45 | +/// |
| 46 | +/// // `b.saturating_add(1)` is always positive (not zero), |
| 47 | +/// // hence `checked_div` will never return None. |
| 48 | +/// // Therefore, the else branch is unreachable. |
| 49 | +/// a.checked_div(b.saturating_add(1)) |
| 50 | +/// .unwrap_or_else(|| unsafe { unreachable_unchecked() }) |
| 51 | +/// } |
| 52 | +/// |
| 53 | +/// assert_eq!(div_1(7, 0), 7); |
| 54 | +/// assert_eq!(div_1(9, 1), 4); |
| 55 | +/// assert_eq!(div_1(11, std::u32::MAX), 0); |
| 56 | +/// ``` |
| 57 | +#[inline] |
| 58 | +#[stable(feature = "unreachable", since = "1.27.0")] |
| 59 | +pub unsafe fn unreachable_unchecked() -> ! { |
| 60 | + intrinsics::unreachable() |
| 61 | +} |
0 commit comments