// cmp (or, comparisons) includes methods for comparing Uint instances. // These comparison functions cover a range of operations including equality checks, less than/greater than // evaluations, and specialized comparisons such as signed greater than. These are fundamental for logical // decision making based on Uint values. package uint256 import "math/bits" // Cmp compares z and x and returns -1 if z < x, 0 if z == x, or +1 if z > x. func (z *Uint) Cmp(x *Uint) (r int) { // z < x <=> z - x < 0 i.e. when subtraction overflows. d0, carry := bits.Sub64(z[0], x[0], 0) d1, carry := bits.Sub64(z[1], x[1], carry) d2, carry := bits.Sub64(z[2], x[2], carry) d3, carry := bits.Sub64(z[3], x[3], carry) if carry == 1 { return -1 } if d0|d1|d2|d3 == 0 { return 0 } return 1 } // IsZero returns true if z equals 0. func (z *Uint) IsZero() bool { return (z[0] | z[1] | z[2] | z[3]) == 0 } // Sign returns the sign of z interpreted as a two's complement signed number. // It returns -1 if z < 0, 0 if z == 0, or +1 if z > 0. func (z *Uint) Sign() int { if z.IsZero() { return 0 } if z[3] < 0x8000000000000000 { return 1 } return -1 } // Lt returns true if z is less than x. func (z *Uint) Lt(x *Uint) bool { // z < x <=> z - x < 0 i.e. when subtraction overflows. _, carry := bits.Sub64(z[0], x[0], 0) _, carry = bits.Sub64(z[1], x[1], carry) _, carry = bits.Sub64(z[2], x[2], carry) _, carry = bits.Sub64(z[3], x[3], carry) return carry != 0 } // Gt returns true if z is greater than x. func (z *Uint) Gt(x *Uint) bool { return x.Lt(z) } // Lte returns true if z is less than or equal to x. func (z *Uint) Lte(x *Uint) bool { return !x.Lt(z) } // Gte returns true if z is greater than or equal to x. func (z *Uint) Gte(x *Uint) bool { return !z.Lt(x) } // Eq returns true if z equals x. func (z *Uint) Eq(x *Uint) bool { return (z[0] == x[0]) && (z[1] == x[1]) && (z[2] == x[2]) && (z[3] == x[3]) } // Neq returns true if z does not equal x. func (z *Uint) Neq(x *Uint) bool { return !z.Eq(x) }