rust-num / num-traits

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

Feature request: OverflowingShl #299

Open tower120 opened 11 months ago

tower120 commented 11 months ago

I have need in overflowing_shl. Is there a reason, why there is no trait for it?

P.S. Well, actually I need something like saturating_shl, but since there is no such thing in Rust, overflowing_shl is the closest one.

cuviper commented 10 months ago

For most such things, it's just because nobody needed it yet.

However, note that shifting is a bit weird compared to other checked/overflowing/wrapping ops, because overflowing_shl and overflowing_shr will overflow the shift value, not the result. Is that what you're actually looking for?

See also https://github.com/rust-lang/libs-team/issues/230

tower120 commented 10 months ago

I am aware of overflowing_shl behavior in Rust. I personally need behavior, where shifting left too far results in zero (like in old x86 shl instructions).

And the thing is, this:

    let (res, ok) = 1usize.overflowing_shl(n);
    res * (!ok as usize)

is faster then this:

     1usize.checked_shl(n).unwrap_or(0)

https://rust.godbolt.org/z/3a6q5Wazf

UPDATE: there were error in example