Skip to content

Latest commit

 

History

History
87 lines (65 loc) · 2.56 KB

0000-saturating-bit-shifts.md

File metadata and controls

87 lines (65 loc) · 2.56 KB

Summary

This RFC proposes to add saturating_shl and saturating_shr to integer types to accommodate shifting equal to and greater than the total number of bits without requiring a check or panicking.

Motivation

This RFC would bring available shift operations inline with other saturating_* functionality on integer types.

Currently if a developer wishes to shift a total number of times equal or greater than the number of bits in the type, saturating at the value 0, they must add a check manually before shifting otherwise they will be met with a panic.

Guide-level explanation

A shift value less than the number of bits in the type will be functionally equivalent to shifting normally. A shift value equal or greater than the number of bits in the type will always produce the saturated value 0.

Reference-level explanation

// Here we shift left the max number of times we can in a `u8`.
assert_eq!(0b0000_0001_u8 << (u8::BITS - 1), 0b1000_0000_u8);

// Again this is the same in the `saturating_shl` variant.
assert_eq!(0b0000_0001_u8.saturating_shl(u8::BITS - 1), 0b1000_0000_u8);

// When we shift left or right, to and above the max number of bits in a u8 (8) our result is always `0`.
assert_eq!(0b0000_0001_u8.saturating_shl(u8::BITS), 0b0000_0000_u8);
assert_eq!(0b1000_0000_u8.saturating_shr(u8::BITS), 0b0000_0000_u8);

Implementation where $ty is an integer (ie. u8, i8, etc):

impl $ty {
    fn saturating_shl(self, rhs: u32) -> $ty {
        if rhs >= $ty::BITS {
            0
        } else {
            self << rhs
        }
    }

    fn saturating_shr(self, rhs: u32) -> $ty {
        if rhs >= $ty::BITS {
            0
        } else {
            self >> rhs
        }
    }
}

Drawbacks

No drawbacks.

Rationale and alternatives

Not implementing this will require developers to continue to manually implement this trival functionality.

Prior art

This is inline with other saturating functionality on integer types.

Unresolved questions

No unresolved issues.