-
-
Notifications
You must be signed in to change notification settings - Fork 324
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
bolts: Simplify definition of nonzero!
macro
#2624
Conversation
b0e9420
to
9d007fb
Compare
9d007fb
to
babe921
Compare
Looks like this doesn't work in my tests. |
Can you say more about what not working means, and what kinds of tests you were looking at? It appears to be working ok in CI. |
It compiles in a |
Can you share an example with that behavior? The following example fails at compile-time (playground): use core::num::NonZeroUsize;
#[macro_export]
macro_rules! nonzero {
($val:expr) => {
const {
match NonZeroUsize::new($val) {
Some(x) => x,
None => panic!("Value was zero"),
}
}
};
}
fn main() {
println!("{}", nonzero!(0));
}
|
That's what I tried. How is my code different? :D |
Your example works. I'm a bit confused but oh well.. |
The example you posted seems quite different from the solution proposed here. Namely, you use a use core::num::NonZero;
pub fn main() {
const { nonzero::<0>() }; // panics at compile-time
nonzero::<0>(); // panics at runtime
}
const fn nonzero<const N: usize>() -> NonZero<usize> {
match NonZero::new(N) {
Some(val) => val,
None => panic!("Zero passed to `nonzero`"),
}
} |
I also can't fix it by adding a |
Right. You can think of The nice part about this is that you don't have to make |
Ok neat, so this actually works: pub const fn nonzero<const N: usize>() -> NonZeroUsize {
const {
match NonZero::new(N) {
Some(val) => val,
None => panic!("expected non-zero value"),
}
}
} Anyway I guess the macro is fine as well / looks a bit nicer / the errors may trigger at the right place |
* bolts: Simplify definition of `nonzero!` macro * Non-Usize NonZero --------- Co-authored-by: Dominik Maier <domenukk@gmail.com>
No description provided.