llogiq
llogiq

Reputation: 14541

Why does `128u8.checked_shl(1)` return `Some(0)`?

I was under the impression that the .checked_*(_) methods of the integral types were there to help avoid overflow. However, the .checked_shl(u32) method happily shifts out the last bit of the example above.

Is my impression wrong? What is that method for?

(Also wanted to add that to avoid overflow on shifts, one can check if ((~0) >> rhs) >= self at least for unsigned types)

Upvotes: 1

Views: 170

Answers (1)

user555045
user555045

Reputation: 64913

Because it checks only the shift amount. From the docs,

None if rhs is larger than or equal to the number of bits in self.

So by design it lets you shift out bits, it just doesn't let you use invalid shift amounts (or, it lets you, but you get None).

Upvotes: 5

Related Questions