rust-num / num-traits

Numeric traits for generic mathematics in Rust
Apache License 2.0
731 stars 135 forks source link

PrimInt: total number of bits #107

Closed dvdhrm closed 5 years ago

dvdhrm commented 5 years ago

Hi!

Is there any way to get the total number of bits in an PrimInt? That is, the compile-time equivalent of:

p.count_zeros() + p.count_ones()

I am implementing floored/ceiled logarithms on PrimInt and these make use of the leading/trailing counters. These need the inverse of the respective functions, so I need to calculate the total bitlength of a number.

I thought about using std::mem::size_of(), but that does not sound right, as it includes possible state-tracking data. Or is PrimInt meant to allow the use of sizeof()?

Thanks! David

cuviper commented 5 years ago

I thought about using std::mem::size_of(), but that does not sound right, as it includes possible state-tracking data.

That would be fine for the actual primitive integers, but I suppose generically you're right that an arbitrary PrimInt could have other data.

For generic T: PrimInt, I think you could use T::zero().count_zeros(). While this isn't exactly a compile-time constant, the optimizer will probably reduce that to a constant anyway.

dvdhrm commented 5 years ago

For generic T: PrimInt, I think you could use T::zero().count_zeros(). While this isn't exactly a compile-time constant, the optimizer will probably reduce that to a constant anyway.

This is what I ended up doing.

If you want, you can close this and I will comment on #11 that zero().count_zeros() is a viable alternative?

Thanks!

cuviper commented 5 years ago

OK, closing. I'm not sure how this is an "alternative" to #11 documentation though...

dvdhrm commented 5 years ago

Nah, I meant I will comment on #11 that zero().count_zeros() is an alternative to std::mem::size_of() ;)

Timmmm commented 4 years ago

I think this should be reopened. Neither zero().count_zeros() nor std::mem::size_of(x) * 8 are particularly obvious, and it's not obvious that they would be optimised to a constant (though I verified that both are).