Skip to content

Commit

Permalink
bolts: Simplify definition of nonzero! macro
Browse files Browse the repository at this point in the history
  • Loading branch information
langston-barrett committed Oct 19, 2024
1 parent fda1596 commit b0e9420
Showing 1 changed file with 10 additions and 35 deletions.
45 changes: 10 additions & 35 deletions libafl_bolts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1050,44 +1050,19 @@ pub unsafe fn set_error_print_panic_hook(new_stderr: RawFd) {
}));
}

// Credit goes to https://github.com/thomcc/nonzero_lit
// We don't want add another dependency and just want to use usize macro of it.
#[doc(hidden)]
pub mod _private {
pub use core::num::NonZeroUsize;

macro_rules! define_nz_ctor {
($(pub fn $nz_func:ident($n:ident : $int:ident) -> $NonZeroInt:ident;)+) => {$(
#[inline]
#[must_use]
pub const fn $nz_func($n : $int) -> $NonZeroInt {
// Note: Hacky const fn assert.
let _ = ["N must not be zero"][($n == 0) as usize];

match $NonZeroInt::new($n) {
Some(x) => x,
// The assert above makes this branch unreachable
None => unreachable!(),
}
}
)+};
}

define_nz_ctor! {
pub fn nz_usize(n: usize) -> NonZeroUsize;
}
}

/// 0 cost way to create check nonzero on compilation.
/// Zero-cost way to construct [`NonZeroUsize`] at compile-time.
#[macro_export]
macro_rules! nonzero {
($val:expr $(,)?) => {{
const __E: usize = $val;
{
const NZ: $crate::_private::NonZeroUsize = $crate::_private::nz_usize(__E);
NZ
// TODO: Further simplify with `unwrap`/`expect` once MSRV includes
// https://github.com/rust-lang/rust/issues/67441
($val:expr) => {
const {
match NonZeroUsize::new($val) {
Some(x) => x,
None => panic!("Value passed to `nonzero!` was zero"),
}
}
}};
};
}

#[cfg(feature = "python")]
Expand Down

0 comments on commit b0e9420

Please sign in to comment.