Skip to content

Implement signum() on unsigned integers #71728

@jhpratt

Description

@jhpratt

This can be quite useful when writing macros that are generic over any integer.

For example, I just tried writing this code (bar is any of i8, i16, i32, u8, u16, u32 via a macro)

match (foo.signum(), bar.signum()) { (1, 1) | (-1, -1) => max, (-1, 1) | (1, -1) => min, _ => zero, }

But because u*::signum isn't implemented, I had to resort to something far more verbose:

if foo > 0 { if bar > 0 { max } else if bar < 0 { min } else { zero } } else if foo < 0 { if bar > 0 { min } else if bar < 0 { max } else { zero } } else { zero }

This can be simplified a bit, but at the expense of performing the operations more than once. This might be optimized away, though.

if (foo > 0 && bar > 0) || (foo < 0 && bar < 0) { max } else if (foo > 0 && bar < 0) || (foo < 0 && bar > 0) { min } else { zero }

To allow for the first example to compile (along with the rest of the code, of course), I'd think having u32::signum return i32 would make sense, despite returning -1 being impossible. I definitely think using signum makes things clearer and more readable.

If this is something that is desired, I can submit a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-feature-requestCategory: A feature request, i.e: not implemented / a PR.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions