Skip to content

Commit

Permalink
Revert "Replace black_box with std::hint::black_box"
Browse files Browse the repository at this point in the history
This reverts commit 4978f42.
  • Loading branch information
dsprenkels committed Mar 15, 2023
1 parent c1d3561 commit 5254934
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Documentation is available [here][docs].

## Minimum Supported Rust Version

Rust **1.66** or higher.
Rust **1.41** or higher.

Minimum supported Rust version can be changed in the future, but it will be done with a minor version bump.

Expand Down
29 changes: 28 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -206,12 +206,39 @@ impl Not for Choice {
}
}

/// This function is a best-effort attempt to prevent the compiler from knowing
/// anything about the value of the returned `u8`, other than its type.
///
/// Because we want to support stable Rust, we don't have access to inline
/// assembly or test::black_box, so we use the fact that volatile values will
/// never be elided to register values.
///
/// Note: Rust's notion of "volatile" is subject to change over time. While this
/// code may break in a non-destructive way in the future, “constant-time” code
/// is a continually moving target, and this is better than doing nothing.
#[inline(never)]
fn black_box(input: u8) -> u8 {
debug_assert!((input == 0u8) | (input == 1u8));

unsafe {
// Optimization barrier
//
// Unsafe is ok, because:
// - &input is not NULL;
// - size of input is not zero;
// - u8 is neither Sync, nor Send;
// - u8 is Copy, so input is always live;
// - u8 type is always properly aligned.
core::ptr::read_volatile(&input as *const u8)
}
}

impl From<u8> for Choice {
#[inline]
fn from(input: u8) -> Choice {
// Our goal is to prevent the compiler from inferring that the value held inside the
// resulting `Choice` struct is really an `i1` instead of an `i8`.
Choice(core::hint::black_box(input))
Choice(black_box(input))
}
}

Expand Down

0 comments on commit 5254934

Please sign in to comment.