cmp.gno
1.99 Kb ยท 76 lines
1// cmp (or, comparisons) includes methods for comparing Uint instances.
2// These comparison functions cover a range of operations including equality checks, less than/greater than
3// evaluations, and specialized comparisons such as signed greater than. These are fundamental for logical
4// decision making based on Uint values.
5package uint256
6
7import "math/bits"
8
9// Cmp compares z and x and returns -1 if z < x, 0 if z == x, or +1 if z > x.
10func (z *Uint) Cmp(x *Uint) (r int) {
11 // z < x <=> z - x < 0 i.e. when subtraction overflows.
12 d0, carry := bits.Sub64(z[0], x[0], 0)
13 d1, carry := bits.Sub64(z[1], x[1], carry)
14 d2, carry := bits.Sub64(z[2], x[2], carry)
15 d3, carry := bits.Sub64(z[3], x[3], carry)
16 if carry == 1 {
17 return -1
18 }
19 if d0|d1|d2|d3 == 0 {
20 return 0
21 }
22 return 1
23}
24
25// IsZero returns true if z equals 0.
26func (z *Uint) IsZero() bool {
27 return (z[0] | z[1] | z[2] | z[3]) == 0
28}
29
30// Sign returns the sign of z interpreted as a two's complement signed number.
31// It returns -1 if z < 0, 0 if z == 0, or +1 if z > 0.
32func (z *Uint) Sign() int {
33 if z.IsZero() {
34 return 0
35 }
36 if z[3] < 0x8000000000000000 {
37 return 1
38 }
39 return -1
40}
41
42// Lt returns true if z is less than x.
43func (z *Uint) Lt(x *Uint) bool {
44 // z < x <=> z - x < 0 i.e. when subtraction overflows.
45 _, carry := bits.Sub64(z[0], x[0], 0)
46 _, carry = bits.Sub64(z[1], x[1], carry)
47 _, carry = bits.Sub64(z[2], x[2], carry)
48 _, carry = bits.Sub64(z[3], x[3], carry)
49
50 return carry != 0
51}
52
53// Gt returns true if z is greater than x.
54func (z *Uint) Gt(x *Uint) bool {
55 return x.Lt(z)
56}
57
58// Lte returns true if z is less than or equal to x.
59func (z *Uint) Lte(x *Uint) bool {
60 return !x.Lt(z)
61}
62
63// Gte returns true if z is greater than or equal to x.
64func (z *Uint) Gte(x *Uint) bool {
65 return !z.Lt(x)
66}
67
68// Eq returns true if z equals x.
69func (z *Uint) Eq(x *Uint) bool {
70 return (z[0] == x[0]) && (z[1] == x[1]) && (z[2] == x[2]) && (z[3] == x[3])
71}
72
73// Neq returns true if z does not equal x.
74func (z *Uint) Neq(x *Uint) bool {
75 return !z.Eq(x)
76}