All the standard integer type have a pub const BITS.
Unfortunately the only way to get at them is by spelling their name, i.e. u32::BITS.
Would it be stupid to therefore resort to something like:
I'm trying to round up to next power of two (for fun).
Which is 1 << (u32::BITS - x.leading_zeros() - 1); for a u32 x.
But I'd rather not write down the type.
This is why I suggest just not using leading_zeros. You can do 1 << x.ilog2() instead and not need to know the width. (Well, not exactly that, but that with some fixups, if you want to implement next_power_of_two yourself.)
Is libcore a different library? The one I checked used
intrinsics::ctlz_nonzero(p) in the absolutely hilariously named one_less_than_next_power_of_two function.
Addressing the original question, I expected the num-traits crate to have this, but:
All PrimInt types are expected to be fixed-width binary integers. The width can be queried via T::zero().count_zeros(). The trait currently lacks a way to query the width at compile-time.
A similar issue came up with the funty trait and trying to get the byte length for a number, which would give the number of bits also. There was an explanation given:
libcore is the old name for just the core library you're looking at.
The !0 >> ctlz_nonzero(x) approach it's using is just a faster way of doing the shifts from the bithacks link. So it's the same conceptual approach, albeit different instructions.
I wish I could think of a better name than one_less_than_next_power_of_two so we could stabilize it
But more seriously, they're called Mersenne numbers in maths, you're not likely to get a snappier name than that. Main problem is the semantics: it's not the next Mersenne number if it already is one, right?
That's also true for next_power_of_two so I wouldn't mind a next_mersenne_number function.
However given the mathematical importance of Mersenne Primes and their enormous sizes I would also want a BigInt with next_mersenne_prime. So you might want to fight over who gets a shorter name.
Perhaps a function to get the p part of (2^p -1) and the exponent of the next power of two could be useful too idk.
huh, i wouldn't expect something called "next" to return the current power of two, but its more likely to be what you want, and consistency trumps everything.