From b0e9420b3200e87fd0f53197cb8e5efdd36d5a56 Mon Sep 17 00:00:00 2001 From: Langston Barrett Date: Sat, 19 Oct 2024 13:02:07 -0400 Subject: [PATCH] bolts: Simplify definition of `nonzero!` macro --- libafl_bolts/src/lib.rs | 45 +++++++++-------------------------------- 1 file changed, 10 insertions(+), 35 deletions(-) diff --git a/libafl_bolts/src/lib.rs b/libafl_bolts/src/lib.rs index ffa5f99130..795e36932e 100644 --- a/libafl_bolts/src/lib.rs +++ b/libafl_bolts/src/lib.rs @@ -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")]