Skip to content
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

Check if PrimInt is even or not #273

Closed
matthew-hennefarth opened this issue Jun 15, 2023 · 3 comments
Closed

Check if PrimInt is even or not #273

matthew-hennefarth opened this issue Jun 15, 2023 · 3 comments

Comments

@matthew-hennefarth
Copy link

Is there any neat way to check if a primitive integer is even or odd? Currently I would imagine either some casts or some bit-wise manipulations on the generic type PrimInt is needed and it would obfuscate code readibility. For example, if we used the modulo way:

fn some_func<T>(n: T) -> bool
where 
    T: PrimInt + FromPrimitive,
{
    // Do something else...
    n % T::from_usize(2).unwrap() == T::zero()
}

versus something like

fn some_func<T>(n: T) -> bool
where 
    T: PrimInt + FromPrimitive,
{
    // Do something else...
    n.is_even()
}

Thoughts? I could work on a PR if this would be appreciated.

@cuviper
Copy link
Member

cuviper commented Jun 15, 2023

Those methods do exist more generally on Integer, so I'd be wary of adding ambiguity if PrimInt got the same.
https://docs.rs/num-integer/latest/num_integer/trait.Integer.html#tymethod.is_even

To do it yourself, PrimInt includes Shl/Shr<usize>, so you can use ((x >> 1) << 1) == x for even.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=02fcdb7c587a5a6b86c74400e7b476d4

@matthew-hennefarth
Copy link
Author

Thanks! Makes sense to not have it in both Integer and PrimInt since it can cause conflicts.

@cuviper
Copy link
Member

cuviper commented Jun 15, 2023

Another option is n.trailing_zeros() > 0. On x86_64, it's optimized to the same bit test either way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants