It would be great to have a uabs or unsigned_abs (or something else, the name isn't important) method that returns the absolute value of the given signed integer as an unsigned integer of the same size. (e.g. uabs(self: i8) -> u8)
impl iX {
pub fn uabs(self) -> uX {
self.wrapping_abs() as uX
}
}
x.abs() as uXiX::MIN.abs() panics in debug modex.wrapping_abs() as uXif x == iX::MIN { x as uX } else { x.abs() as uX }iX::absRelated: https://github.com/rust-lang/rfcs/pull/1017, https://github.com/rust-lang/rust/issues/2353
If x == i8::MIN == -128_i8, then x.wrapping_abs() == -128_i8 and then, since in 8-bit 2's complement, -128_i8 is represented as 0b1000_0000, when converted to u8, 0b1000_0000 is interpreted as 128_u8, which is correct.
@sollyucko That works playground
Yes please! wrapping and as set off all the alarm bells when looking for bugs in integer code, so having a method that is just documented as "always returns the correct absolute value, no wrapping ever" would be great.
Looks like this went in: https://doc.rust-lang.org/nightly/std/primitive.i64.html#method.unsigned_abs
Anyone interested should follow the tracking issue now: https://github.com/rust-lang/rust/issues/74913
Most helpful comment
Yes please!
wrappingandasset off all the alarm bells when looking for bugs in integer code, so having a method that is just documented as "always returns the correct absolute value, no wrapping ever" would be great.