rust-num / num-integer

Integer trait and functions for Rust
Apache License 2.0
180 stars 48 forks source link

Contribute is_power_of_ten? #14

Open mohrezaei opened 6 years ago

mohrezaei commented 6 years ago

I'd like to contribute a high performance implementation of is_power_of_ten. Is that an appropriate function for this crate?

cuviper commented 6 years ago

I'm open to it, if we can present it in a generic trait befitting the rest of the crate. That doesn't mean that you have to have a generic implementation, just that it's designed such that things like BigUint can implement it too. Take the Roots trait, for example.

The unsigned primitive integers already have is_power_of_two, and a related next_power_of_two. It would be good to also abstract this in a trait, while we're doing it for 10. Something like:

pub trait Power2: Integer {
    fn is_power_of_two(&self) -> bool;
    fn next_power_of_two(&self) -> Self;
}
pub trait Power10: Integer {
    fn is_power_of_ten(&self) -> bool;
    fn next_power_of_ten(&self) -> Self;
}

Or maybe just combine those into a single trait Powers. And feel free to suggest a better name.

Could we reasonably implement checks for arbitrary powers of n? It wouldn't have to be as fast, but I'm wondering if that's feasible and useful to have too.

cuviper commented 6 years ago

Floored log2 and log10 might also fit into the scope of this design.

mohrezaei commented 6 years ago

A separate trait is consistent with the way I was thinking about it.

Curious, why don't signed primitive integers implement is_power_of_two? (obviously, all negative numbers would return false).

How would we abstract over arbitrary powers on n? Extra parameter to the method? I think 2 and 10 are sufficiently interesting to have their own trait.

cuviper commented 6 years ago

Curious, why don't signed primitive integers implement is_power_of_two? (obviously, all negative numbers would return false).

I'm not sure, but probably just because negative inputs are useless if they're all false.

Similarly, what would next_power_of_two do with a negative -- jump all the way to 1?

How would we abstract over arbitrary powers on n? Extra parameter to the method?

Yeah, fn is_power_of_n(&self, n: u32) -> bool, or maybe n: usize or n: &Self. I'm not sure if this is really useful anywhere, just musing.

mohrezaei commented 6 years ago

Alright, that gives me enough to move this over to a PR. Expect something in the next few days. :smile: