Where is std::num::Saturating?

Or completely identical, using the add_with_carry_using_overflowing from my previous godbolt: https://rust.godbolt.org/z/jxd4WM

1 Like

Note that this version produces some fairly garbage assembly for the adc() function in -Oz; you should use a bool for the carry like @scottmcm did. (See also why I really think this should be an intrinsic...). https://godbolt.org/z/WoWKK1

(In -Oz rustc fails to inline any of these for whatever reason, though that's not included in the example.)

Alright, so if I didn't miss it, there should be all the methods for all the cases – checked, wrapping and overflow –, but so far only Wrapping exists and the two remaining cases could be possibly added to make this corner of std::num complete. And it seems there are good uses for it.

I think it is worth making an RFC, isn't it?

While for unsigned integers those give access to the carry flag, for signed integers they give access to the overflow flag. So for example to access the carry bit in i64 addition, you'd need to first cast the integers to u64, then use overflowing_add, and then cast the sum back to i64.

2 Likes

there is an RFC for this (widening_mul) https://github.com/rust-lang/rfcs/pull/2417.

Yup, mentioned that in post #11 above :upside_down_face: