rust-num / num-traits

Numeric traits for generic mathematics in Rust
Apache License 2.0
719 stars 133 forks source link

Add is_signed #322

Open geeknoid opened 5 months ago

geeknoid commented 5 months ago

When working in a generic context, it would be useful to access whether a PrimInt-based generic type is signed or not signed at build time.

fn foo(v: X)
where X: PrimInt {
    if (K::is_signed()) {
       let num = v.to_i64();
   else {
       let num = v.to_u64();
   }
}
cuviper commented 5 months ago

It's possible to add, and you can emulate this now with T::min_value() < T::zero(), which is probably how we would write a default implementation in the trait.

Since the to_* methods return Option, you could also write it based on the runtime values like this:

if let Some(i) = v.to_i64() {
    // signed operations using `i`
} else {
    let u = v.to_u64().expect("unsigned number");
}