Skip to content

uabs/unsigned_abs #2914

Closed
Closed
@sollyucko

Description

@sollyucko

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: #1017, rust-lang/rust#2353

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions