Skip to content

Commit a2143c8

Browse files
committed
Replace black_box with std::hint::black_box
Rust version 1.66 now comes with a stabilized version of a black_box function that emits an "empty" assembly directive. This patch replaces the older optimization barrier, which was based on a volatile read with the newly standardized function. Announcement from Mara: <https://hachyderm.io/@Mara/109518823276877083> Current implementation of black_box in rustc: https://github.com/rust-lang/rust/blob/a803f313fdf8f6eb2d674d7dfb3694a2b437ee1e/compiler/rustc_codegen_llvm/src/intrinsic.rs#L341-L375
1 parent 1213ae8 commit a2143c8

File tree

1 file changed

+1
-28
lines changed

1 file changed

+1
-28
lines changed

src/lib.rs

Lines changed: 1 addition & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -200,39 +200,12 @@ impl Not for Choice {
200200
}
201201
}
202202

203-
/// This function is a best-effort attempt to prevent the compiler from knowing
204-
/// anything about the value of the returned `u8`, other than its type.
205-
///
206-
/// Because we want to support stable Rust, we don't have access to inline
207-
/// assembly or test::black_box, so we use the fact that volatile values will
208-
/// never be elided to register values.
209-
///
210-
/// Note: Rust's notion of "volatile" is subject to change over time. While this
211-
/// code may break in a non-destructive way in the future, “constant-time” code
212-
/// is a continually moving target, and this is better than doing nothing.
213-
#[inline(never)]
214-
fn black_box(input: u8) -> u8 {
215-
debug_assert!((input == 0u8) | (input == 1u8));
216-
217-
unsafe {
218-
// Optimization barrier
219-
//
220-
// Unsafe is ok, because:
221-
// - &input is not NULL;
222-
// - size of input is not zero;
223-
// - u8 is neither Sync, nor Send;
224-
// - u8 is Copy, so input is always live;
225-
// - u8 type is always properly aligned.
226-
core::ptr::read_volatile(&input as *const u8)
227-
}
228-
}
229-
230203
impl From<u8> for Choice {
231204
#[inline]
232205
fn from(input: u8) -> Choice {
233206
// Our goal is to prevent the compiler from inferring that the value held inside the
234207
// resulting `Choice` struct is really an `i1` instead of an `i8`.
235-
Choice(black_box(input))
208+
Choice(core::hint::black_box(input))
236209
}
237210
}
238211

0 commit comments

Comments
 (0)