Rfcs: uabs/unsigned_abs

Created on 25 Apr 2020  ·  4Comments  ·  Source: rust-lang/rfcs

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)

Advantages

  • It encodes the guarantee that the result is positive.
  • It is more concise and less error-prone than workarounds

Disadvantages

  • None?

Implementation

impl iX {
    pub fn uabs(self) -> uX {
        self.wrapping_abs() as uX
    }
}

Alternatives

  • x.abs() as uX

    • iX::MIN.abs() panics in debug mode

  • x.wrapping_abs() as uX

    • Very verbose

  • if x == iX::MIN { x as uX } else { x.abs() as uX }

    • Extremely verbose

  • Redefining iX::abs

    • May cause compatibility issues

Related: https://github.com/rust-lang/rfcs/pull/1017, https://github.com/rust-lang/rust/issues/2353

Most helpful comment

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.

All 4 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rust-highfive picture rust-highfive  ·  4Comments

mqudsi picture mqudsi  ·  3Comments

burdges picture burdges  ·  3Comments

Diggsey picture Diggsey  ·  3Comments

3442853561 picture 3442853561  ·  3Comments