Skip to content

math/big: add a method to Int for an absolute value comparison #22473

@ericlagergren

Description

@ericlagergren

When writing a couple libraries I've needed to compare the absolute value of two big.Ints, but have had my hands tied a bit because the API doesn't allow me to modify them.

Right now, the only way to get an absolute comparison without modifying either of the inputs is

new(big.Int).Abs(x).Cmp( ... ) // allocation of big.Int + copy of entire backing nat
new(big.Int).SetBits(x.Bits()).Cmp( ... ) // allocation of big.Int + dangerous aliasing
// write my own method with code copied and pasted from math/big.nat.cmp

The first two allocate a big.Int and the second causes aliasing which can cause subtle bugs. The allocations have appeared when benchmarking.

It would be very nice to essentially have this

// Cmp compares, ignoring signs, x and y and returns:
//
//   -1 if x <  y
//    0 if x == y
//   +1 if x >  y
//
func (x *Int) CmpAbs(y *Int) int {
    return x.abs.cmp(y.abs)
}

PS: is there a proposal template?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions