Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Playground

arithmetic.gno

// arithmetic provides arithmetic operations for Uint objects.
// This includes basic binary operations such as addition, subtraction, multiplication, division, and modulo operations
// as well as overflow checks, and negation. These functions are essential for numeric
// calculations using 256-bit unsigned integers.
package uint256

import (
	"math/bits"
)

// Add sets z to the sum x+y
func (z *Uint) Add(x, y *Uint) *Uint {
	var carry uint64
	z.arr[0], carry = bits.Add64(x.arr[0], y.arr[0], 0)
	z.arr[1], carry = bits.Add64(x.arr[1], y.arr[1], carry)
	z.arr[2], carry = bits.Add64(x.arr[2], y.arr[2], carry)
	z.arr[3], _ = bits.Add64(x.arr[3], y.arr[3], carry)
	return z
}

// AddOverflow sets z to the sum x+y, and returns z and whether overflow occurred
func (z *Uint) AddOverflow(x, y *Uint) (*Uint, bool) {
	var carry uint64
	z.arr[0], carry = bits.Add64(x.arr[0], y.arr[0], 0)
	z.arr[1], carry = bits.Add64(x.arr[1], y.arr[1], carry)
	z.arr[2], carry = bits.Add64(x.arr[2], y.arr[2], carry)
	z.arr[3], carry = bits.Add64(x.arr[3], y.arr[3], carry)
	return z, carry != 0
}

// Sub sets z to the difference x-y
func (z *Uint) Sub(x, y *Uint) *Uint {
	var carry uint64
	z.arr[0], carry = bits.Sub64(x.arr[0], y.arr[0], 0)
	z.arr[1], carry = bits.Sub64(x.arr[1], y.arr[1], carry)
	z.arr[2], carry = bits.Sub64(x.arr[2], y.arr[2], carry)
	z.arr[3], _ = bits.Sub64(x.arr[3], y.arr[3], carry)
	return z
}

// SubOverflow sets z to the difference x-y and returns z and true if the operation underflowed
func (z *Uint) SubOverflow(x, y *Uint) (*Uint, bool) {
	var carry uint64
	z.arr[0], carry = bits.Sub64(x.arr[0], y.arr[0], 0)
	z.arr[1], carry = bits.Sub64(x.arr[1], y.arr[1], carry)
	z.arr[2], carry = bits.Sub64(x.arr[2], y.arr[2], carry)
	z.arr[3], carry = bits.Sub64(x.arr[3], y.arr[3], carry)
	return z, carry != 0
}

// Neg returns -x mod 2^256.
func (z *Uint) Neg(x *Uint) *Uint {
	return z.Sub(new(Uint), x)
}

// commented out for possible overflow
// Mul sets z to the product x*y
func (z *Uint) Mul(x, y *Uint) *Uint {
	var (
		res              Uint
		carry            uint64
		res1, res2, res3 uint64
	)

	carry, res.arr[0] = bits.Mul64(x.arr[0], y.arr[0])
	carry, res1 = umulHop(carry, x.arr[1], y.arr[0])
	carry, res2 = umulHop(carry, x.arr[2], y.arr[0])
	res3 = x.arr[3]*y.arr[0] + carry

	carry, res.arr[1] = umulHop(res1, x.arr[0], y.arr[1])
	carry, res2 = umulStep(res2, x.arr[1], y.arr[1], carry)
	res3 = res3 + x.arr[2]*y.arr[1] + carry

	carry, res.arr[2] = umulHop(res2, x.arr[0], y.arr[2])
	res3 = res3 + x.arr[1]*y.arr[2] + carry

	res.arr[3] = res3 + x.arr[0]*y.arr[3]

	return z.Set(&res)
}

// MulOverflow sets z to the product x*y, and returns z and  whether overflow occurred
func (z *Uint) MulOverflow(x, y *Uint) (*Uint, bool) {
	p := umul(x, y)
	copy(z.arr[:], p[:4])
	return z, (p[4] | p[5] | p[6] | p[7]) != 0
}

// commented out for possible overflow
// Div sets z to the quotient x/y for returns z.
// If y == 0, z is set to 0
func (z *Uint) Div(x, y *Uint) *Uint {
	if y.IsZero() || y.Gt(x) {
		return z.Clear()
	}
	if x.Eq(y) {
		return z.SetOne()
	}
	// Shortcut some cases
	if x.IsUint64() {
		return z.SetUint64(x.Uint64() / y.Uint64())
	}

	// At this point, we know
	// x/y ; x > y > 0

	var quot Uint
	udivrem(quot.arr[:], x.arr[:], y)
	return z.Set(&quot)
}

// MulMod calculates the modulo-m multiplication of x and y and
// returns z.
// If m == 0, z is set to 0 (OBS: differs from the big.Int)
func (z *Uint) MulMod(x, y, m *Uint) *Uint {
	if x.IsZero() || y.IsZero() || m.IsZero() {
		return z.Clear()
	}
	p := umul(x, y)

	if m.arr[3] != 0 {
		mu := Reciprocal(m)
		r := reduce4(p, m, mu)
		return z.Set(&r)
	}

	var (
		pl Uint
		ph Uint
	)

	pl = Uint{arr: [4]uint64{p[0], p[1], p[2], p[3]}}
	ph = Uint{arr: [4]uint64{p[4], p[5], p[6], p[7]}}

	// If the multiplication is within 256 bits use Mod().
	if ph.IsZero() {
		return z.Mod(&pl, m)
	}

	var quot [8]uint64
	rem := udivrem(quot[:], p[:], m)
	return z.Set(&rem)
}

// Mod sets z to the modulus x%y for y != 0 and returns z.
// If y == 0, z is set to 0 (OBS: differs from the big.Uint)
func (z *Uint) Mod(x, y *Uint) *Uint {
	if x.IsZero() || y.IsZero() {
		return z.Clear()
	}
	switch x.Cmp(y) {
	case -1:
		// x < y
		copy(z.arr[:], x.arr[:])
		return z
	case 0:
		// x == y
		return z.Clear() // They are equal
	}

	// At this point:
	// x != 0
	// y != 0
	// x > y

	// Shortcut trivial case
	if x.IsUint64() {
		return z.SetUint64(x.Uint64() % y.Uint64())
	}

	var quot Uint
	*z = udivrem(quot.arr[:], x.arr[:], y)
	return z
}

// DivMod sets z to the quotient x div y and m to the modulus x mod y and returns the pair (z, m) for y != 0.
// If y == 0, both z and m are set to 0 (OBS: differs from the big.Int)
func (z *Uint) DivMod(x, y, m *Uint) (*Uint, *Uint) {
	if y.IsZero() {
		return z.Clear(), m.Clear()
	}
	var quot Uint
	*m = udivrem(quot.arr[:], x.arr[:], y)
	*z = quot
	return z, m
}

// Exp sets z = base**exponent mod 2**256, and returns z.
func (z *Uint) Exp(base, exponent *Uint) *Uint {
	res := Uint{arr: [4]uint64{1, 0, 0, 0}}
	multiplier := *base
	expBitLen := exponent.BitLen()

	curBit := 0
	word := exponent.arr[0]
	for ; curBit < expBitLen && curBit < 64; curBit++ {
		if word&1 == 1 {
			res.Mul(&res, &multiplier)
		}
		multiplier.squared()
		word >>= 1
	}

	word = exponent.arr[1]
	for ; curBit < expBitLen && curBit < 128; curBit++ {
		if word&1 == 1 {
			res.Mul(&res, &multiplier)
		}
		multiplier.squared()
		word >>= 1
	}

	word = exponent.arr[2]
	for ; curBit < expBitLen && curBit < 192; curBit++ {
		if word&1 == 1 {
			res.Mul(&res, &multiplier)
		}
		multiplier.squared()
		word >>= 1
	}

	word = exponent.arr[3]
	for ; curBit < expBitLen && curBit < 256; curBit++ {
		if word&1 == 1 {
			res.Mul(&res, &multiplier)
		}
		multiplier.squared()
		word >>= 1
	}
	return z.Set(&res)
}

func (z *Uint) squared() {
	var (
		res                    Uint
		carry0, carry1, carry2 uint64
		res1, res2             uint64
	)

	carry0, res.arr[0] = bits.Mul64(z.arr[0], z.arr[0])
	carry0, res1 = umulHop(carry0, z.arr[0], z.arr[1])
	carry0, res2 = umulHop(carry0, z.arr[0], z.arr[2])

	carry1, res.arr[1] = umulHop(res1, z.arr[0], z.arr[1])
	carry1, res2 = umulStep(res2, z.arr[1], z.arr[1], carry1)

	carry2, res.arr[2] = umulHop(res2, z.arr[0], z.arr[2])

	res.arr[3] = 2*(z.arr[0]*z.arr[3]+z.arr[1]*z.arr[2]) + carry0 + carry1 + carry2

	z.Set(&res)
}

// udivrem divides u by d and produces both quotient and remainder.
// The quotient is stored in provided quot - len(u)-len(d)+1 words.
// It loosely follows the Knuth's division algorithm (sometimes referenced as "schoolbook" division) using 64-bit words.
// See Knuth, Volume 2, section 4.3.1, Algorithm D.
func udivrem(quot, u []uint64, d *Uint) (rem Uint) {
	var dLen int
	for i := len(d.arr) - 1; i >= 0; i-- {
		if d.arr[i] != 0 {
			dLen = i + 1
			break
		}
	}

	shift := uint(bits.LeadingZeros64(d.arr[dLen-1]))

	var dnStorage Uint
	dn := dnStorage.arr[:dLen]
	for i := dLen - 1; i > 0; i-- {
		dn[i] = (d.arr[i] << shift) | (d.arr[i-1] >> (64 - shift))
	}
	dn[0] = d.arr[0] << shift

	var uLen int
	for i := len(u) - 1; i >= 0; i-- {
		if u[i] != 0 {
			uLen = i + 1
			break
		}
	}

	if uLen < dLen {
		copy(rem.arr[:], u)
		return rem
	}

	var unStorage [9]uint64
	un := unStorage[:uLen+1]
	un[uLen] = u[uLen-1] >> (64 - shift)
	for i := uLen - 1; i > 0; i-- {
		un[i] = (u[i] << shift) | (u[i-1] >> (64 - shift))
	}
	un[0] = u[0] << shift

	// TODO: Skip the highest word of numerator if not significant.

	if dLen == 1 {
		r := udivremBy1(quot, un, dn[0])
		rem.SetUint64(r >> shift)
		return rem
	}

	udivremKnuth(quot, un, dn)

	for i := 0; i < dLen-1; i++ {
		rem.arr[i] = (un[i] >> shift) | (un[i+1] << (64 - shift))
	}
	rem.arr[dLen-1] = un[dLen-1] >> shift

	return rem
}

// umul computes full 256 x 256 -> 512 multiplication.
func umul(x, y *Uint) [8]uint64 {
	var (
		res                           [8]uint64
		carry, carry4, carry5, carry6 uint64
		res1, res2, res3, res4, res5  uint64
	)

	carry, res[0] = bits.Mul64(x.arr[0], y.arr[0])
	carry, res1 = umulHop(carry, x.arr[1], y.arr[0])
	carry, res2 = umulHop(carry, x.arr[2], y.arr[0])
	carry4, res3 = umulHop(carry, x.arr[3], y.arr[0])

	carry, res[1] = umulHop(res1, x.arr[0], y.arr[1])
	carry, res2 = umulStep(res2, x.arr[1], y.arr[1], carry)
	carry, res3 = umulStep(res3, x.arr[2], y.arr[1], carry)
	carry5, res4 = umulStep(carry4, x.arr[3], y.arr[1], carry)

	carry, res[2] = umulHop(res2, x.arr[0], y.arr[2])
	carry, res3 = umulStep(res3, x.arr[1], y.arr[2], carry)
	carry, res4 = umulStep(res4, x.arr[2], y.arr[2], carry)
	carry6, res5 = umulStep(carry5, x.arr[3], y.arr[2], carry)

	carry, res[3] = umulHop(res3, x.arr[0], y.arr[3])
	carry, res[4] = umulStep(res4, x.arr[1], y.arr[3], carry)
	carry, res[5] = umulStep(res5, x.arr[2], y.arr[3], carry)
	res[7], res[6] = umulStep(carry6, x.arr[3], y.arr[3], carry)

	return res
}

// umulStep computes (hi * 2^64 + lo) = z + (x * y) + carry.
func umulStep(z, x, y, carry uint64) (hi, lo uint64) {
	hi, lo = bits.Mul64(x, y)
	lo, carry = bits.Add64(lo, carry, 0)
	hi, _ = bits.Add64(hi, 0, carry)
	lo, carry = bits.Add64(lo, z, 0)
	hi, _ = bits.Add64(hi, 0, carry)
	return hi, lo
}

// umulHop computes (hi * 2^64 + lo) = z + (x * y)
func umulHop(z, x, y uint64) (hi, lo uint64) {
	hi, lo = bits.Mul64(x, y)
	lo, carry := bits.Add64(lo, z, 0)
	hi, _ = bits.Add64(hi, 0, carry)
	return hi, lo
}

// udivremBy1 divides u by single normalized word d and produces both quotient and remainder.
// The quotient is stored in provided quot.
func udivremBy1(quot, u []uint64, d uint64) (rem uint64) {
	reciprocal := reciprocal2by1(d)
	rem = u[len(u)-1] // Set the top word as remainder.
	for j := len(u) - 2; j >= 0; j-- {
		quot[j], rem = udivrem2by1(rem, u[j], d, reciprocal)
	}
	return rem
}

// udivremKnuth implements the division of u by normalized multiple word d from the Knuth's division algorithm.
// The quotient is stored in provided quot - len(u)-len(d) words.
// Updates u to contain the remainder - len(d) words.
func udivremKnuth(quot, u, d []uint64) {
	dh := d[len(d)-1]
	dl := d[len(d)-2]
	reciprocal := reciprocal2by1(dh)

	for j := len(u) - len(d) - 1; j >= 0; j-- {
		u2 := u[j+len(d)]
		u1 := u[j+len(d)-1]
		u0 := u[j+len(d)-2]

		var qhat, rhat uint64
		if u2 >= dh { // Division overflows.
			qhat = ^uint64(0)
			// TODO: Add "qhat one to big" adjustment (not needed for correctness, but helps avoiding "add back" case).
		} else {
			qhat, rhat = udivrem2by1(u2, u1, dh, reciprocal)
			ph, pl := bits.Mul64(qhat, dl)
			if ph > rhat || (ph == rhat && pl > u0) {
				qhat--
				// TODO: Add "qhat one to big" adjustment (not needed for correctness, but helps avoiding "add back" case).
			}
		}

		// Multiply and subtract.
		borrow := subMulTo(u[j:], d, qhat)
		u[j+len(d)] = u2 - borrow
		if u2 < borrow { // Too much subtracted, add back.
			qhat--
			u[j+len(d)] += addTo(u[j:], d)
		}

		quot[j] = qhat // Store quotient digit.
	}
}

// isBitSet returns true if bit n-th is set, where n = 0 is LSB.
// The n must be <= 255.
func (z *Uint) isBitSet(n uint) bool {
	return (z.arr[n/64] & (1 << (n % 64))) != 0
}

// addTo computes x += y.
// Requires len(x) >= len(y).
func addTo(x, y []uint64) uint64 {
	var carry uint64
	for i := 0; i < len(y); i++ {
		x[i], carry = bits.Add64(x[i], y[i], carry)
	}
	return carry
}

// subMulTo computes x -= y * multiplier.
// Requires len(x) >= len(y).
func subMulTo(x, y []uint64, multiplier uint64) uint64 {
	var borrow uint64
	for i := 0; i < len(y); i++ {
		s, carry1 := bits.Sub64(x[i], borrow, 0)
		ph, pl := bits.Mul64(y[i], multiplier)
		t, carry2 := bits.Sub64(s, pl, 0)
		x[i] = t
		borrow = ph + carry1 + carry2
	}
	return borrow
}

// reciprocal2by1 computes <^d, ^0> / d.
func reciprocal2by1(d uint64) uint64 {
	reciprocal, _ := bits.Div64(^d, ^uint64(0), d)
	return reciprocal
}

// udivrem2by1 divides <uh, ul> / d and produces both quotient and remainder.
// It uses the provided d's reciprocal.
// Implementation ported from https://github.com/chfast/intx and is based on
// "Improved division by invariant integers", Algorithm 4.
func udivrem2by1(uh, ul, d, reciprocal uint64) (quot, rem uint64) {
	qh, ql := bits.Mul64(reciprocal, uh)
	ql, carry := bits.Add64(ql, ul, 0)
	qh, _ = bits.Add64(qh, uh, carry)
	qh++

	r := ul - qh*d

	if r > ql {
		qh--
		r += d
	}

	if r >= d {
		qh++
		r -= d
	}

	return qh, r
}

arithmetic_test.gno

package uint256

import (
	"testing"
)

type binOp2Test struct {
	x, y, want string
}

func TestAdd(t *testing.T) {
	tests := []binOp2Test{
		{"0", "1", "1"},
		{"1", "0", "1"},
		{"1", "1", "2"},
		{"1", "3", "4"},
		{"10", "10", "20"},
		{"18446744073709551615", "18446744073709551615", "36893488147419103230"}, // uint64 overflow
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)
		y := MustFromDecimal(tt.y)

		want := MustFromDecimal(tt.want)
		got := new(Uint).Add(x, y)

		if got.Neq(want) {
			t.Errorf("Add(%s, %s) = %v, want %v", tt.x, tt.y, got.String(), want.String())
		}
	}
}

func TestAddOverflow(t *testing.T) {
	tests := []struct {
		x, y     string
		want     string
		overflow bool
	}{
		{"0", "1", "1", false},
		{"1", "0", "1", false},
		{"1", "1", "2", false},
		{"10", "10", "20", false},
		{"18446744073709551615", "18446744073709551615", "36893488147419103230", false},                    // uint64 overflow, but not Uint256 overflow
		{"115792089237316195423570985008687907853269984665640564039457584007913129639935", "1", "0", true}, // 2^256 - 1 + 1, should overflow
		{"57896044618658097711785492504343953926634992332820282019728792003956564819967", "57896044618658097711785492504343953926634992332820282019728792003956564819968", "115792089237316195423570985008687907853269984665640564039457584007913129639935", false}, // (2^255 - 1) + 2^255, no overflow
		{"57896044618658097711785492504343953926634992332820282019728792003956564819967", "57896044618658097711785492504343953926634992332820282019728792003956564819969", "0", true},                                                                               // (2^255 - 1) + (2^255 + 1), should overflow
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)
		y := MustFromDecimal(tt.y)
		want, _ := FromDecimal(tt.want)

		got, overflow := new(Uint).AddOverflow(x, y)

		if got.Cmp(want) != 0 || overflow != tt.overflow {
			t.Errorf("AddOverflow(%s, %s) = (%s, %v), want (%s, %v)",
				tt.x, tt.y, got.String(), overflow, tt.want, tt.overflow)
		}
	}
}

func TestSub(t *testing.T) {
	tests := []binOp2Test{
		{"1", "0", "1"},
		{"1", "1", "0"},
		{"10", "10", "0"},
		{"31337", "1337", "30000"},
		{"2", "3", twoPow256Sub1}, // underflow
	}

	for _, tc := range tests {
		x := MustFromDecimal(tc.x)
		y := MustFromDecimal(tc.y)

		want := MustFromDecimal(tc.want)

		got := new(Uint).Sub(x, y)

		if got.Neq(want) {
			t.Errorf(
				"Sub(%s, %s) = %v, want %v",
				tc.x, tc.y, got.String(), want.String(),
			)
		}
	}
}

func TestSubOverflow(t *testing.T) {
	tests := []struct {
		x, y     string
		want     string
		overflow bool
	}{
		{"1", "0", "1", false},
		{"1", "1", "0", false},
		{"10", "10", "0", false},
		{"31337", "1337", "30000", false},
		{"0", "1", "115792089237316195423570985008687907853269984665640564039457584007913129639935", true},                                                                                                                                                         // 0 - 1, should underflow
		{"57896044618658097711785492504343953926634992332820282019728792003956564819968", "1", "57896044618658097711785492504343953926634992332820282019728792003956564819967", false},                                                                             // 2^255 - 1, no underflow
		{"57896044618658097711785492504343953926634992332820282019728792003956564819968", "57896044618658097711785492504343953926634992332820282019728792003956564819969", "115792089237316195423570985008687907853269984665640564039457584007913129639935", true}, // 2^255 - (2^255 + 1), should underflow
	}

	for _, tc := range tests {
		x := MustFromDecimal(tc.x)
		y := MustFromDecimal(tc.y)
		want := MustFromDecimal(tc.want)

		got, overflow := new(Uint).SubOverflow(x, y)

		if got.Cmp(want) != 0 || overflow != tc.overflow {
			t.Errorf(
				"SubOverflow(%s, %s) = (%s, %v), want (%s, %v)",
				tc.x, tc.y, got.String(), overflow, tc.want, tc.overflow,
			)
		}
	}
}

func TestMul(t *testing.T) {
	tests := []binOp2Test{
		{"1", "0", "0"},
		{"1", "1", "1"},
		{"10", "10", "100"},
		{"18446744073709551615", "2", "36893488147419103230"}, // uint64 overflow
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)
		y := MustFromDecimal(tt.y)
		want := MustFromDecimal(tt.want)
		got := new(Uint).Mul(x, y)

		if got.Neq(want) {
			t.Errorf("Mul(%s, %s) = %v, want %v", tt.x, tt.y, got.String(), want.String())
		}
	}
}

func TestMulOverflow(t *testing.T) {
	tests := []struct {
		x        string
		y        string
		wantZ    string
		wantOver bool
	}{
		{"0x1", "0x1", "0x1", false},
		{"0x0", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0x0", false},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0x2", "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe", true},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0x1", true},
		{"0x8000000000000000000000000000000000000000000000000000000000000000", "0x2", "0x0", true},
		{"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0x2", "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe", false},
		{"0x100000000000000000", "0x100000000000000000", "0x10000000000000000000000000000000000", false},
		{"0x10000000000000000000000000000000", "0x10000000000000000000000000000000", "0x100000000000000000000000000000000000000000000000000000000000000", false},
	}

	for _, tt := range tests {
		x := MustFromHex(tt.x)
		y := MustFromHex(tt.y)
		wantZ := MustFromHex(tt.wantZ)

		gotZ, gotOver := new(Uint).MulOverflow(x, y)

		if gotZ.Neq(wantZ) {
			t.Errorf(
				"MulOverflow(%s, %s) = %s, want %s",
				tt.x, tt.y, gotZ.String(), wantZ.String(),
			)
		}
		if gotOver != tt.wantOver {
			t.Errorf("MulOverflow(%s, %s) = %v, want %v", tt.x, tt.y, gotOver, tt.wantOver)
		}
	}
}

func TestDiv(t *testing.T) {
	tests := []binOp2Test{
		{"31337", "3", "10445"},
		{"31337", "0", "0"},
		{"0", "31337", "0"},
		{"1", "1", "1"},
		{"1000000000000000000", "3", "333333333333333333"},
		{twoPow256Sub1, "2", "57896044618658097711785492504343953926634992332820282019728792003956564819967"},
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)
		y := MustFromDecimal(tt.y)
		want := MustFromDecimal(tt.want)

		got := new(Uint).Div(x, y)

		if got.Neq(want) {
			t.Errorf("Div(%s, %s) = %v, want %v", tt.x, tt.y, got.String(), want.String())
		}
	}
}

func TestMod(t *testing.T) {
	tests := []binOp2Test{
		{"31337", "3", "2"},
		{"31337", "0", "0"},
		{"0", "31337", "0"},
		{"2", "31337", "2"},
		{"1", "1", "0"},
		{"115792089237316195423570985008687907853269984665640564039457584007913129639935", "2", "1"}, // 2^256 - 1 mod 2
		{"115792089237316195423570985008687907853269984665640564039457584007913129639935", "3", "0"}, // 2^256 - 1 mod 3
		{"115792089237316195423570985008687907853269984665640564039457584007913129639935", "57896044618658097711785492504343953926634992332820282019728792003956564819968", "57896044618658097711785492504343953926634992332820282019728792003956564819967"}, // 2^256 - 1 mod 2^255
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)
		y := MustFromDecimal(tt.y)
		want := MustFromDecimal(tt.want)

		got := new(Uint).Mod(x, y)

		if got.Neq(want) {
			t.Errorf("Mod(%s, %s) = %v, want %v", tt.x, tt.y, got.String(), want.String())
		}
	}
}

func TestMulMod(t *testing.T) {
	tests := []struct {
		x    string
		y    string
		m    string
		want string
	}{
		{"0x1", "0x1", "0x2", "0x1"},
		{"0x10", "0x10", "0x7", "0x4"},
		{"0x100", "0x100", "0x17", "0x9"},
		{"0x31337", "0x31337", "0x31338", "0x1"},
		{"0x0", "0x31337", "0x31338", "0x0"},
		{"0x31337", "0x0", "0x31338", "0x0"},
		{"0x2", "0x3", "0x5", "0x1"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0x0"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe", "0x1"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "0xffffffffffffffffffffffffffffffff", "0x0"},
	}

	for _, tt := range tests {
		x := MustFromHex(tt.x)
		y := MustFromHex(tt.y)
		m := MustFromHex(tt.m)
		want := MustFromHex(tt.want)

		got := new(Uint).MulMod(x, y, m)

		if got.Neq(want) {
			t.Errorf(
				"MulMod(%s, %s, %s) = %s, want %s",
				tt.x, tt.y, tt.m, got.String(), want.String(),
			)
		}
	}
}

func TestDivMod(t *testing.T) {
	tests := []struct {
		x       string
		y       string
		wantDiv string
		wantMod string
	}{
		{"1", "1", "1", "0"},
		{"10", "10", "1", "0"},
		{"100", "10", "10", "0"},
		{"31337", "3", "10445", "2"},
		{"31337", "0", "0", "0"},
		{"0", "31337", "0", "0"},
		{"2", "31337", "0", "2"},
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)
		y := MustFromDecimal(tt.y)
		wantDiv := MustFromDecimal(tt.wantDiv)
		wantMod := MustFromDecimal(tt.wantMod)

		gotDiv := new(Uint)
		gotMod := new(Uint)
		gotDiv.DivMod(x, y, gotMod)

		for i := range gotDiv.arr {
			if gotDiv.arr[i] != wantDiv.arr[i] {
				t.Errorf("DivMod(%s, %s) got Div %v, want Div %v", tt.x, tt.y, gotDiv, wantDiv)
				break
			}
		}
		for i := range gotMod.arr {
			if gotMod.arr[i] != wantMod.arr[i] {
				t.Errorf("DivMod(%s, %s) got Mod %v, want Mod %v", tt.x, tt.y, gotMod, wantMod)
				break
			}
		}
	}
}

func TestNeg(t *testing.T) {
	tests := []struct {
		x    string
		want string
	}{
		{"31337", "115792089237316195423570985008687907853269984665640564039457584007913129608599"},
		{"115792089237316195423570985008687907853269984665640564039457584007913129608599", "31337"},
		{"0", "0"},
		{"2", "115792089237316195423570985008687907853269984665640564039457584007913129639934"},
		{"1", twoPow256Sub1},
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)
		want := MustFromDecimal(tt.want)

		got := new(Uint).Neg(x)

		if got.Neq(want) {
			t.Errorf("Neg(%s) = %v, want %v", tt.x, got.String(), want.String())
		}
	}
}

func TestExp(t *testing.T) {
	tests := []binOp2Test{
		{"31337", "3", "30773171189753"},
		{"31337", "0", "1"},
		{"0", "31337", "0"},
		{"1", "1", "1"},
		{"2", "3", "8"},
		{"2", "64", "18446744073709551616"},
		{"2", "128", "340282366920938463463374607431768211456"},
		{"2", "255", "57896044618658097711785492504343953926634992332820282019728792003956564819968"},
		{"2", "256", "0"}, // overflow
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)
		y := MustFromDecimal(tt.y)
		want := MustFromDecimal(tt.want)

		got := new(Uint).Exp(x, y)

		if got.Neq(want) {
			t.Errorf(
				"Exp(%s, %s) = %v, want %v",
				tt.x, tt.y, got.String(), want.String(),
			)
		}
	}
}

func TestExp_LargeExponent(t *testing.T) {
	tests := []struct {
		name     string
		base     string
		exponent string
		expected string
	}{
		{
			name:     "2^129",
			base:     "2",
			exponent: "680564733841876926926749214863536422912",
			expected: "0",
		},
		{
			name:     "2^193",
			base:     "2",
			exponent: "12379400392853802746563808384000000000000000000",
			expected: "0",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			base := MustFromDecimal(tt.base)
			exponent := MustFromDecimal(tt.exponent)
			expected := MustFromDecimal(tt.expected)

			result := new(Uint).Exp(base, exponent)

			if result.Neq(expected) {
				t.Errorf(
					"Test %s failed. Expected %s, got %s",
					tt.name, expected.String(), result.String(),
				)
			}
		})
	}
}

bits_table.gno

// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Code generated by go run make_tables.go. DO NOT EDIT.

package uint256

const ntz8tab = "" +
	"\x08\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x05\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x06\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x05\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x07\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x05\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x06\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x05\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00" +
	"\x04\x00\x01\x00\x02\x00\x01\x00\x03\x00\x01\x00\x02\x00\x01\x00"

const pop8tab = "" +
	"\x00\x01\x01\x02\x01\x02\x02\x03\x01\x02\x02\x03\x02\x03\x03\x04" +
	"\x01\x02\x02\x03\x02\x03\x03\x04\x02\x03\x03\x04\x03\x04\x04\x05" +
	"\x01\x02\x02\x03\x02\x03\x03\x04\x02\x03\x03\x04\x03\x04\x04\x05" +
	"\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
	"\x01\x02\x02\x03\x02\x03\x03\x04\x02\x03\x03\x04\x03\x04\x04\x05" +
	"\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
	"\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
	"\x03\x04\x04\x05\x04\x05\x05\x06\x04\x05\x05\x06\x05\x06\x06\x07" +
	"\x01\x02\x02\x03\x02\x03\x03\x04\x02\x03\x03\x04\x03\x04\x04\x05" +
	"\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
	"\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
	"\x03\x04\x04\x05\x04\x05\x05\x06\x04\x05\x05\x06\x05\x06\x06\x07" +
	"\x02\x03\x03\x04\x03\x04\x04\x05\x03\x04\x04\x05\x04\x05\x05\x06" +
	"\x03\x04\x04\x05\x04\x05\x05\x06\x04\x05\x05\x06\x05\x06\x06\x07" +
	"\x03\x04\x04\x05\x04\x05\x05\x06\x04\x05\x05\x06\x05\x06\x06\x07" +
	"\x04\x05\x05\x06\x05\x06\x06\x07\x05\x06\x06\x07\x06\x07\x07\x08"

const rev8tab = "" +
	"\x00\x80\x40\xc0\x20\xa0\x60\xe0\x10\x90\x50\xd0\x30\xb0\x70\xf0" +
	"\x08\x88\x48\xc8\x28\xa8\x68\xe8\x18\x98\x58\xd8\x38\xb8\x78\xf8" +
	"\x04\x84\x44\xc4\x24\xa4\x64\xe4\x14\x94\x54\xd4\x34\xb4\x74\xf4" +
	"\x0c\x8c\x4c\xcc\x2c\xac\x6c\xec\x1c\x9c\x5c\xdc\x3c\xbc\x7c\xfc" +
	"\x02\x82\x42\xc2\x22\xa2\x62\xe2\x12\x92\x52\xd2\x32\xb2\x72\xf2" +
	"\x0a\x8a\x4a\xca\x2a\xaa\x6a\xea\x1a\x9a\x5a\xda\x3a\xba\x7a\xfa" +
	"\x06\x86\x46\xc6\x26\xa6\x66\xe6\x16\x96\x56\xd6\x36\xb6\x76\xf6" +
	"\x0e\x8e\x4e\xce\x2e\xae\x6e\xee\x1e\x9e\x5e\xde\x3e\xbe\x7e\xfe" +
	"\x01\x81\x41\xc1\x21\xa1\x61\xe1\x11\x91\x51\xd1\x31\xb1\x71\xf1" +
	"\x09\x89\x49\xc9\x29\xa9\x69\xe9\x19\x99\x59\xd9\x39\xb9\x79\xf9" +
	"\x05\x85\x45\xc5\x25\xa5\x65\xe5\x15\x95\x55\xd5\x35\xb5\x75\xf5" +
	"\x0d\x8d\x4d\xcd\x2d\xad\x6d\xed\x1d\x9d\x5d\xdd\x3d\xbd\x7d\xfd" +
	"\x03\x83\x43\xc3\x23\xa3\x63\xe3\x13\x93\x53\xd3\x33\xb3\x73\xf3" +
	"\x0b\x8b\x4b\xcb\x2b\xab\x6b\xeb\x1b\x9b\x5b\xdb\x3b\xbb\x7b\xfb" +
	"\x07\x87\x47\xc7\x27\xa7\x67\xe7\x17\x97\x57\xd7\x37\xb7\x77\xf7" +
	"\x0f\x8f\x4f\xcf\x2f\xaf\x6f\xef\x1f\x9f\x5f\xdf\x3f\xbf\x7f\xff"

const len8tab = "" +
	"\x00\x01\x02\x02\x03\x03\x03\x03\x04\x04\x04\x04\x04\x04\x04\x04" +
	"\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05\x05" +
	"\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06" +
	"\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06\x06" +
	"\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" +
	"\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" +
	"\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" +
	"\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07\x07" +
	"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
	"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
	"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
	"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
	"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
	"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
	"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08" +
	"\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08\x08"

bitwise.gno

// bitwise contains bitwise operations for Uint instances.
// This file includes functions to perform bitwise AND, OR, XOR, and NOT operations, as well as bit shifting.
// These operations are crucial for manipulating individual bits within a 256-bit unsigned integer.
package uint256

// Or sets z = x | y and returns z.
func (z *Uint) Or(x, y *Uint) *Uint {
	z.arr[0] = x.arr[0] | y.arr[0]
	z.arr[1] = x.arr[1] | y.arr[1]
	z.arr[2] = x.arr[2] | y.arr[2]
	z.arr[3] = x.arr[3] | y.arr[3]
	return z
}

// And sets z = x & y and returns z.
func (z *Uint) And(x, y *Uint) *Uint {
	z.arr[0] = x.arr[0] & y.arr[0]
	z.arr[1] = x.arr[1] & y.arr[1]
	z.arr[2] = x.arr[2] & y.arr[2]
	z.arr[3] = x.arr[3] & y.arr[3]
	return z
}

// Not sets z = ^x and returns z.
func (z *Uint) Not(x *Uint) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = ^x.arr[3], ^x.arr[2], ^x.arr[1], ^x.arr[0]
	return z
}

// AndNot sets z = x &^ y and returns z.
func (z *Uint) AndNot(x, y *Uint) *Uint {
	z.arr[0] = x.arr[0] &^ y.arr[0]
	z.arr[1] = x.arr[1] &^ y.arr[1]
	z.arr[2] = x.arr[2] &^ y.arr[2]
	z.arr[3] = x.arr[3] &^ y.arr[3]
	return z
}

// Xor sets z = x ^ y and returns z.
func (z *Uint) Xor(x, y *Uint) *Uint {
	z.arr[0] = x.arr[0] ^ y.arr[0]
	z.arr[1] = x.arr[1] ^ y.arr[1]
	z.arr[2] = x.arr[2] ^ y.arr[2]
	z.arr[3] = x.arr[3] ^ y.arr[3]
	return z
}

// Lsh sets z = x << n and returns z.
func (z *Uint) Lsh(x *Uint, n uint) *Uint {
	// n % 64 == 0
	if n&0x3f == 0 {
		switch n {
		case 0:
			return z.Set(x)
		case 64:
			return z.lsh64(x)
		case 128:
			return z.lsh128(x)
		case 192:
			return z.lsh192(x)
		default:
			return z.Clear()
		}
	}
	var a, b uint64
	// Big swaps first
	switch {
	case n > 192:
		if n > 256 {
			return z.Clear()
		}
		z.lsh192(x)
		n -= 192
		goto sh192
	case n > 128:
		z.lsh128(x)
		n -= 128
		goto sh128
	case n > 64:
		z.lsh64(x)
		n -= 64
		goto sh64
	default:
		z.Set(x)
	}

	// remaining shifts
	a = z.arr[0] >> (64 - n)
	z.arr[0] = z.arr[0] << n

sh64:
	b = z.arr[1] >> (64 - n)
	z.arr[1] = (z.arr[1] << n) | a

sh128:
	a = z.arr[2] >> (64 - n)
	z.arr[2] = (z.arr[2] << n) | b

sh192:
	z.arr[3] = (z.arr[3] << n) | a

	return z
}

// Rsh sets z = x >> n and returns z.
func (z *Uint) Rsh(x *Uint, n uint) *Uint {
	// n % 64 == 0
	if n&0x3f == 0 {
		switch n {
		case 0:
			return z.Set(x)
		case 64:
			return z.rsh64(x)
		case 128:
			return z.rsh128(x)
		case 192:
			return z.rsh192(x)
		default:
			return z.Clear()
		}
	}
	var a, b uint64
	// Big swaps first
	switch {
	case n > 192:
		if n > 256 {
			return z.Clear()
		}
		z.rsh192(x)
		n -= 192
		goto sh192
	case n > 128:
		z.rsh128(x)
		n -= 128
		goto sh128
	case n > 64:
		z.rsh64(x)
		n -= 64
		goto sh64
	default:
		z.Set(x)
	}

	// remaining shifts
	a = z.arr[3] << (64 - n)
	z.arr[3] = z.arr[3] >> n

sh64:
	b = z.arr[2] << (64 - n)
	z.arr[2] = (z.arr[2] >> n) | a

sh128:
	a = z.arr[1] << (64 - n)
	z.arr[1] = (z.arr[1] >> n) | b

sh192:
	z.arr[0] = (z.arr[0] >> n) | a

	return z
}

// SRsh (Signed/Arithmetic right shift)
// considers z to be a signed integer, during right-shift
// and sets z = x >> n and returns z.
func (z *Uint) SRsh(x *Uint, n uint) *Uint {
	// If the MSB is 0, SRsh is same as Rsh.
	if !x.isBitSet(255) {
		return z.Rsh(x, n)
	}
	if n%64 == 0 {
		switch n {
		case 0:
			return z.Set(x)
		case 64:
			return z.srsh64(x)
		case 128:
			return z.srsh128(x)
		case 192:
			return z.srsh192(x)
		default:
			return z.SetAllOne()
		}
	}
	var a uint64 = MaxUint64 << (64 - n%64)
	// Big swaps first
	switch {
	case n > 192:
		if n > 256 {
			return z.SetAllOne()
		}
		z.srsh192(x)
		n -= 192
		goto sh192
	case n > 128:
		z.srsh128(x)
		n -= 128
		goto sh128
	case n > 64:
		z.srsh64(x)
		n -= 64
		goto sh64
	default:
		z.Set(x)
	}

	// remaining shifts
	z.arr[3], a = (z.arr[3]>>n)|a, z.arr[3]<<(64-n)

sh64:
	z.arr[2], a = (z.arr[2]>>n)|a, z.arr[2]<<(64-n)

sh128:
	z.arr[1], a = (z.arr[1]>>n)|a, z.arr[1]<<(64-n)

sh192:
	z.arr[0] = (z.arr[0] >> n) | a

	return z
}

func (z *Uint) lsh64(x *Uint) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[2], x.arr[1], x.arr[0], 0
	return z
}

func (z *Uint) lsh128(x *Uint) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[1], x.arr[0], 0, 0
	return z
}

func (z *Uint) lsh192(x *Uint) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = x.arr[0], 0, 0, 0
	return z
}

func (z *Uint) rsh64(x *Uint) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, x.arr[3], x.arr[2], x.arr[1]
	return z
}

func (z *Uint) rsh128(x *Uint) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, x.arr[3], x.arr[2]
	return z
}

func (z *Uint) rsh192(x *Uint) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, x.arr[3]
	return z
}

func (z *Uint) srsh64(x *Uint) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, x.arr[3], x.arr[2], x.arr[1]
	return z
}

func (z *Uint) srsh128(x *Uint) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, x.arr[3], x.arr[2]
	return z
}

func (z *Uint) srsh192(x *Uint) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, MaxUint64, x.arr[3]
	return z
}

bitwise_test.gno

package uint256

import "testing"

type logicOpTest struct {
	name string
	x    Uint
	y    Uint
	want Uint
}

func TestOr(t *testing.T) {
	tests := []logicOpTest{
		{
			name: "all zeros",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			y:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "all ones",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
		},
		{
			name: "mixed",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},
			y:    Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
		},
		{
			name: "one operand all ones",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}},
			want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			res := new(Uint).Or(&tt.x, &tt.y)
			if *res != tt.want {
				t.Errorf(
					"Or(%s, %s) = %s, want %s",
					tt.x.String(), tt.y.String(), res.String(), (tt.want).String(),
				)
			}
		})
	}
}

func TestAnd(t *testing.T) {
	tests := []logicOpTest{
		{
			name: "all zeros",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			y:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "all ones",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
		},
		{
			name: "mixed",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			y:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "mixed 2",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "mixed 3",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},
			y:    Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "one operand zero",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			y:    Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "one operand all ones",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}},
			want: Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			res := new(Uint).And(&tt.x, &tt.y)
			if *res != tt.want {
				t.Errorf(
					"And(%s, %s) = %s, want %s",
					tt.x.String(), tt.y.String(), res.String(), (tt.want).String(),
				)
			}
		})
	}
}

func TestNot(t *testing.T) {
	tests := []struct {
		name string
		x    Uint
		want Uint
	}{
		{
			name: "all zeros",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
		},
		{
			name: "all ones",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "mixed",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},
			want: Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			res := new(Uint).Not(&tt.x)
			if *res != tt.want {
				t.Errorf(
					"Not(%s) = %s, want %s",
					tt.x.String(), res.String(), (tt.want).String(),
				)
			}
		})
	}
}

func TestAndNot(t *testing.T) {
	tests := []logicOpTest{
		{
			name: "all zeros",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			y:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "all ones",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "mixed",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			y:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "mixed 2",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
		},
		{
			name: "mixed 3",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},
			y:    Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},
		},
		{
			name: "one operand zero",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			y:    Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "one operand all ones",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}},
			want: Uint{arr: [4]uint64{0xAAAAAAAAAAAAAAAA, 0x5555555555555555, 0x0000000000000000, ^uint64(0)}},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			res := new(Uint).AndNot(&tt.x, &tt.y)
			if *res != tt.want {
				t.Errorf(
					"AndNot(%s, %s) = %s, want %s",
					tt.x.String(), tt.y.String(), res.String(), (tt.want).String(),
				)
			}
		})
	}
}

func TestXor(t *testing.T) {
	tests := []logicOpTest{
		{
			name: "all zeros",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			y:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "all ones",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{0, 0, 0, 0}},
		},
		{
			name: "mixed",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			y:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
		},
		{
			name: "mixed 2",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
		},
		{
			name: "mixed 3",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), 0, 0}},
			y:    Uint{arr: [4]uint64{0, 0, ^uint64(0), ^uint64(0)}},
			want: Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
		},
		{
			name: "one operand zero",
			x:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			y:    Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}},
			want: Uint{arr: [4]uint64{0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF}},
		},
		{
			name: "one operand all ones",
			x:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			y:    Uint{arr: [4]uint64{0x5555555555555555, 0xAAAAAAAAAAAAAAAA, 0xFFFFFFFFFFFFFFFF, 0x0000000000000000}},
			want: Uint{arr: [4]uint64{0xAAAAAAAAAAAAAAAA, 0x5555555555555555, 0x0000000000000000, ^uint64(0)}},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			res := new(Uint).Xor(&tt.x, &tt.y)
			if *res != tt.want {
				t.Errorf(
					"Xor(%s, %s) = %s, want %s",
					tt.x.String(), tt.y.String(), res.String(), (tt.want).String(),
				)
			}
		})
	}
}

func TestLsh(t *testing.T) {
	tests := []struct {
		x    string
		y    uint
		want string
	}{
		{"0", 0, "0"},
		{"0", 1, "0"},
		{"0", 64, "0"},
		{"1", 0, "1"},
		{"1", 1, "2"},
		{"1", 64, "18446744073709551616"},
		{"1", 128, "340282366920938463463374607431768211456"},
		{"1", 192, "6277101735386680763835789423207666416102355444464034512896"},
		{"1", 255, "57896044618658097711785492504343953926634992332820282019728792003956564819968"},
		{"1", 256, "0"},
		{"31337", 0, "31337"},
		{"31337", 1, "62674"},
		{"31337", 64, "578065619037836218990592"},
		{"31337", 128, "10663428532201448629551770073089320442396672"},
		{"31337", 192, "196705537081812415096322133155058642481399512563169449530621952"},
		{"31337", 193, "393411074163624830192644266310117284962799025126338899061243904"},
		{"31337", 255, "57896044618658097711785492504343953926634992332820282019728792003956564819968"},
		{"31337", 256, "0"},
		// 64 < n < 128
		{"1", 65, "36893488147419103232"},
		{"31337", 100, "39724366859352024754702188346867712"},

		// 128 < n < 192
		{"1", 129, "680564733841876926926749214863536422912"},
		{"31337", 150, "44725660946326664792723507424638829088826130956288"},

		// 192 < n < 256
		{"1", 193, "12554203470773361527671578846415332832204710888928069025792"},
		{"31337", 200, "50356617492943978264658466087695012475238275216171379079839219712"},

		// n > 256
		{"1", 257, "0"},
		{"31337", 300, "0"},
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)
		want := MustFromDecimal(tt.want)

		got := new(Uint).Lsh(x, tt.y)

		if got.Neq(want) {
			t.Errorf("Lsh(%s, %d) = %s, want %s", tt.x, tt.y, got.String(), want.String())
		}
	}
}

func TestRsh(t *testing.T) {
	tests := []struct {
		x    string
		y    uint
		want string
	}{
		{"0", 0, "0"},
		{"0", 1, "0"},
		{"0", 64, "0"},
		{"1", 0, "1"},
		{"1", 1, "0"},
		{"1", 64, "0"},
		{"1", 128, "0"},
		{"1", 192, "0"},
		{"1", 255, "0"},
		{"57896044618658097711785492504343953926634992332820282019728792003956564819968", 255, "1"},
		{"6277101735386680763835789423207666416102355444464034512896", 192, "1"},
		{"340282366920938463463374607431768211456", 128, "1"},
		{"18446744073709551616", 64, "1"},
		{"393411074163624830192644266310117284962799025126338899061243904", 193, "31337"},
		{"196705537081812415096322133155058642481399512563169449530621952", 192, "31337"},
		{"10663428532201448629551770073089320442396672", 128, "31337"},
		{"578065619037836218990592", 64, "31337"},
		{twoPow256Sub1, 256, "0"},
		// outliers
		{"340282366920938463463374607431768211455", 129, "0"},
		{"18446744073709551615", 65, "0"},
		{twoPow256Sub1, 1, "57896044618658097711785492504343953926634992332820282019728792003956564819967"},

		// n > 256
		{"1", 257, "0"},
		{"31337", 300, "0"},
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)

		want := MustFromDecimal(tt.want)
		got := new(Uint).Rsh(x, tt.y)

		if got.Neq(want) {
			t.Errorf("Rsh(%s, %d) = %s, want %s", tt.x, tt.y, got.String(), want.String())
		}
	}
}

func TestSRsh(t *testing.T) {
	tests := []struct {
		x    string
		y    uint
		want string
	}{
		// Positive numbers (behaves like Rsh)
		{"0x0", 0, "0x0"},
		{"0x0", 1, "0x0"},
		{"0x1", 0, "0x1"},
		{"0x1", 1, "0x0"},
		{"0x31337", 0, "0x31337"},
		{"0x31337", 4, "0x3133"},
		{"0x31337", 8, "0x313"},
		{"0x31337", 16, "0x3"},
		{"0x10000000000000000", 64, "0x1"}, // 2^64 >> 64

		// // Numbers with MSB set (negative numbers in two's complement)
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 0, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 1, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 4, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 64, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 128, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 192, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 255, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},

		// Large positive number close to max value
		{"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 1, "0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 2, "0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 64, "0x7fffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 128, "0x7fffffffffffffffffffffffffffffff"},
		{"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 192, "0x7fffffffffffffff"},
		{"0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 255, "0x0"},

		// Specific cases
		{"0x8000000000000000000000000000000000000000000000000000000000000000", 1, "0xc000000000000000000000000000000000000000000000000000000000000000"},
		{"0x8000000000000000000000000000000000000000000000000000000000000001", 1, "0xc000000000000000000000000000000000000000000000000000000000000000"},

		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 65, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 127, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 129, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 193, "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"},

		// n > 256
		{"0x1", 257, "0x0"},
		{"0x31337", 300, "0x0"},
	}

	for _, tt := range tests {
		x := MustFromHex(tt.x)
		want := MustFromHex(tt.want)

		got := new(Uint).SRsh(x, tt.y)

		if !got.Eq(want) {
			t.Errorf("SRsh(%s, %d) = %s, want %s", tt.x, tt.y, got.String(), want.String())
		}
	}
}

cmp.gno

// 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
//	+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.arr[0], x.arr[0], 0)
	d1, carry := bits.Sub64(z.arr[1], x.arr[1], carry)
	d2, carry := bits.Sub64(z.arr[2], x.arr[2], carry)
	d3, carry := bits.Sub64(z.arr[3], x.arr[3], carry)
	if carry == 1 {
		return -1
	}
	if d0|d1|d2|d3 == 0 {
		return 0
	}
	return 1
}

// IsZero returns true if z == 0
func (z *Uint) IsZero() bool {
	return (z.arr[0] | z.arr[1] | z.arr[2] | z.arr[3]) == 0
}

// Sign returns:
//
//	-1 if z <  0
//	 0 if z == 0
//	+1 if z >  0
//
// Where z is interpreted as a two's complement signed number
func (z *Uint) Sign() int {
	if z.IsZero() {
		return 0
	}
	if z.arr[3] < 0x8000000000000000 {
		return 1
	}
	return -1
}

// LtUint64 returns true if z is smaller than n
func (z *Uint) LtUint64(n uint64) bool {
	return z.arr[0] < n && (z.arr[1]|z.arr[2]|z.arr[3]) == 0
}

// GtUint64 returns true if z is larger than n
func (z *Uint) GtUint64(n uint64) bool {
	return z.arr[0] > n || (z.arr[1]|z.arr[2]|z.arr[3]) != 0
}

// Lt returns true if z < x
func (z *Uint) Lt(x *Uint) bool {
	// z < x <=> z - x < 0 i.e. when subtraction overflows.
	_, carry := bits.Sub64(z.arr[0], x.arr[0], 0)
	_, carry = bits.Sub64(z.arr[1], x.arr[1], carry)
	_, carry = bits.Sub64(z.arr[2], x.arr[2], carry)
	_, carry = bits.Sub64(z.arr[3], x.arr[3], carry)

	return carry != 0
}

// Gt returns true if z > x
func (z *Uint) Gt(x *Uint) bool {
	return x.Lt(z)
}

// Lte returns true if z <= x
func (z *Uint) Lte(x *Uint) bool {
	cond1 := z.Lt(x)
	cond2 := z.Eq(x)

	if cond1 || cond2 {
		return true
	}
	return false
}

// Gte returns true if z >= x
func (z *Uint) Gte(x *Uint) bool {
	cond1 := z.Gt(x)
	cond2 := z.Eq(x)

	if cond1 || cond2 {
		return true
	}
	return false
}

// Eq returns true if z == x
func (z *Uint) Eq(x *Uint) bool {
	return (z.arr[0] == x.arr[0]) && (z.arr[1] == x.arr[1]) && (z.arr[2] == x.arr[2]) && (z.arr[3] == x.arr[3])
}

// Neq returns true if z != x
func (z *Uint) Neq(x *Uint) bool {
	return !z.Eq(x)
}

// Sgt interprets z and x as signed integers, and returns
// true if z > x
func (z *Uint) Sgt(x *Uint) bool {
	zSign := z.Sign()
	xSign := x.Sign()

	switch {
	case zSign >= 0 && xSign < 0:
		return true
	case zSign < 0 && xSign >= 0:
		return false
	default:
		return z.Gt(x)
	}
}

cmp_test.gno

package uint256

import (
	"strings"
	"testing"
)

func TestSign(t *testing.T) {
	tests := []struct {
		input    *Uint
		expected int
	}{
		{
			input:    NewUint(0),
			expected: 0,
		},
		{
			input:    NewUint(1),
			expected: 1,
		},
		{
			input:    NewUint(0x7fffffffffffffff),
			expected: 1,
		},
		{
			input:    NewUint(0x8000000000000000),
			expected: 1,
		},
	}

	for _, tt := range tests {
		t.Run(tt.input.String(), func(t *testing.T) {
			result := tt.input.Sign()
			if result != tt.expected {
				t.Errorf("Sign() = %d; want %d", result, tt.expected)
			}
		})
	}
}

func TestCmp(t *testing.T) {
	tests := []struct {
		x, y string
		want int
	}{
		{"0", "0", 0},
		{"0", "1", -1},
		{"1", "0", 1},
		{"1", "1", 0},
		{"10", "10", 0},
		{"10", "11", -1},
		{"11", "10", 1},
	}

	for _, tc := range tests {
		x := MustFromDecimal(tc.x)
		y := MustFromDecimal(tc.y)

		got := x.Cmp(y)
		if got != tc.want {
			t.Errorf("Cmp(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want)
		}
	}
}

func TestIsZero(t *testing.T) {
	tests := []struct {
		x    string
		want bool
	}{
		{"0", true},
		{"1", false},
		{"10", false},
	}

	for _, tt := range tests {
		x := MustFromDecimal(tt.x)

		got := x.IsZero()
		if got != tt.want {
			t.Errorf("IsZero(%s) = %v, want %v", tt.x, got, tt.want)
		}
	}
}

func TestLtUint64(t *testing.T) {
	tests := []struct {
		x    string
		y    uint64
		want bool
	}{
		{"0", 1, true},
		{"1", 0, false},
		{"10", 10, false},
		{"0xffffffffffffffff", 0, false},
		{"0x10000000000000000", 10000000000000000, false},
	}

	for _, tc := range tests {
		x := parseTestString(t, tc.x)

		got := x.LtUint64(tc.y)
		if got != tc.want {
			t.Errorf("LtUint64(%s, %d) = %v, want %v", tc.x, tc.y, got, tc.want)
		}
	}
}

func TestUint_GtUint64(t *testing.T) {
	tests := []struct {
		name string
		z    string
		n    uint64
		want bool
	}{
		{
			name: "z > n",
			z:    "1",
			n:    0,
			want: true,
		},
		{
			name: "z < n",
			z:    "18446744073709551615",
			n:    0xFFFFFFFFFFFFFFFF,
			want: false,
		},
		{
			name: "z == n",
			z:    "18446744073709551615",
			n:    0xFFFFFFFFFFFFFFFF,
			want: false,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			z := MustFromDecimal(tt.z)

			if got := z.GtUint64(tt.n); got != tt.want {
				t.Errorf("Uint.GtUint64() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestSGT(t *testing.T) {
	x := MustFromHex("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")
	y := MustFromHex("0x0")
	actual := x.Sgt(y)
	if actual {
		t.Fatalf("Expected %v false", actual)
	}

	x = MustFromHex("0x0")
	y = MustFromHex("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")
	actual = x.Sgt(y)
	if !actual {
		t.Fatalf("Expected %v true", actual)
	}
}

func TestEq(t *testing.T) {
	tests := []struct {
		x    string
		y    string
		want bool
	}{
		{"0xffffffffffffffff", "18446744073709551615", true},
		{"0x10000000000000000", "18446744073709551616", true},
		{"0", "0", true},
		{twoPow256Sub1, twoPow256Sub1, true},
	}

	for _, tt := range tests {
		x := parseTestString(t, tt.x)

		y, err := FromDecimal(tt.y)
		if err != nil {
			t.Error(err)
			continue
		}

		got := x.Eq(y)

		if got != tt.want {
			t.Errorf("Eq(%s, %s) = %v, want %v", tt.x, tt.y, got, tt.want)
		}
	}
}

func TestUint_Lte(t *testing.T) {
	tests := []struct {
		z, x string
		want bool
	}{
		{"10", "20", true},
		{"20", "10", false},
		{"10", "10", true},
		{"0", "0", true},
	}

	for _, tt := range tests {
		z, err := FromDecimal(tt.z)
		if err != nil {
			t.Error(err)
			continue
		}
		x, err := FromDecimal(tt.x)
		if err != nil {
			t.Error(err)
			continue
		}
		if got := z.Lte(x); got != tt.want {
			t.Errorf("Uint.Lte(%v, %v) = %v, want %v", tt.z, tt.x, got, tt.want)
		}
	}
}

func TestUint_Gte(t *testing.T) {
	tests := []struct {
		z, x string
		want bool
	}{
		{"20", "10", true},
		{"10", "20", false},
		{"10", "10", true},
		{"0", "0", true},
	}

	for _, tt := range tests {
		z := parseTestString(t, tt.z)
		x := parseTestString(t, tt.x)

		if got := z.Gte(x); got != tt.want {
			t.Errorf("Uint.Gte(%v, %v) = %v, want %v", tt.z, tt.x, got, tt.want)
		}
	}
}

func parseTestString(_ *testing.T, s string) *Uint {
	var x *Uint

	if strings.HasPrefix(s, "0x") {
		x = MustFromHex(s)
	} else {
		x = MustFromDecimal(s)
	}

	return x
}

conversion.gno

// conversions contains methods for converting Uint instances to other types and vice versa.
// This includes conversions to and from basic types such as uint64 and int32, as well as string representations
// and byte slices. Additionally, it covers marshaling and unmarshaling for JSON and other text formats.
package uint256

import (
	"encoding/binary"
	"errors"
	"strconv"
	"strings"
)

// Uint64 returns the lower 64-bits of z
func (z *Uint) Uint64() uint64 {
	return z.arr[0]
}

// Uint64WithOverflow returns the lower 64-bits of z and bool whether overflow occurred
func (z *Uint) Uint64WithOverflow() (uint64, bool) {
	return z.arr[0], (z.arr[1] | z.arr[2] | z.arr[3]) != 0
}

// SetUint64 sets z to the value x
func (z *Uint) SetUint64(x uint64) *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, x
	return z
}

// IsUint64 reports whether z can be represented as a uint64.
func (z *Uint) IsUint64() bool {
	return (z.arr[1] | z.arr[2] | z.arr[3]) == 0
}

// Dec returns the decimal representation of z.
func (z *Uint) Dec() string {
	if z.IsZero() {
		return "0"
	}
	if z.IsUint64() {
		return strconv.FormatUint(z.Uint64(), 10)
	}

	// The max uint64 value being 18446744073709551615, the largest
	// power-of-ten below that is 10000000000000000000.
	// When we do a DivMod using that number, the remainder that we
	// get back is the lower part of the output.
	//
	// The ascii-output of remainder will never exceed 19 bytes (since it will be
	// below 10000000000000000000).
	//
	// Algorithm example using 100 as divisor
	//
	// 12345 % 100 = 45   (rem)
	// 12345 / 100 = 123  (quo)
	// -> output '45', continue iterate on 123
	var (
		// out is 98 bytes long: 78 (max size of a string without leading zeroes,
		// plus slack so we can copy 19 bytes every iteration).
		// We init it with zeroes, because when strconv appends the ascii representations,
		// it will omit leading zeroes.
		out     = []byte("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
		divisor = NewUint(10000000000000000000) // 20 digits
		y       = new(Uint).Set(z)              // copy to avoid modifying z
		pos     = len(out)                      // position to write to
		buf     = make([]byte, 0, 19)           // buffer to write uint64:s to
	)
	for {
		// Obtain Q and R for divisor
		var quot Uint
		rem := udivrem(quot.arr[:], y.arr[:], divisor)
		y.Set(&quot) // Set Q for next loop
		// Convert the R to ascii representation
		buf = strconv.AppendUint(buf[:0], rem.Uint64(), 10)
		// Copy in the ascii digits
		copy(out[pos-len(buf):], buf)
		if y.IsZero() {
			break
		}
		// Move 19 digits left
		pos -= 19
	}
	// skip leading zeroes by only using the 'used size' of buf
	return string(out[pos-len(buf):])
}

func (z *Uint) Scan(src any) error {
	if src == nil {
		z.Clear()
		return nil
	}

	switch src := src.(type) {
	case string:
		return z.scanScientificFromString(src)
	case []byte:
		return z.scanScientificFromString(string(src))
	}
	return errors.New("default // unsupported type: can't convert to uint256.Uint")
}

func (z *Uint) scanScientificFromString(src string) error {
	if len(src) == 0 {
		z.Clear()
		return nil
	}

	idx := strings.IndexByte(src, 'e')
	if idx == -1 {
		return z.SetFromDecimal(src)
	}
	if err := z.SetFromDecimal(src[:idx]); err != nil {
		return err
	}
	if src[(idx+1):] == "0" {
		return nil
	}
	exp := new(Uint)
	if err := exp.SetFromDecimal(src[(idx + 1):]); err != nil {
		return err
	}
	if exp.GtUint64(77) { // 10**78 is larger than 2**256
		return ErrBig256Range
	}
	exp.Exp(NewUint(10), exp)
	if _, overflow := z.MulOverflow(z, exp); overflow {
		return ErrBig256Range
	}
	return nil
}

// ToString returns the decimal string representation of z. It returns an empty string if z is nil.
// OBS: doesn't exist from holiman's uint256
func (z *Uint) String() string {
	if z == nil {
		return ""
	}

	return z.Dec()
}

// MarshalJSON implements json.Marshaler.
// MarshalJSON marshals using the 'decimal string' representation. This is _not_ compatible
// with big.Uint: big.Uint marshals into JSON 'native' numeric format.
//
// The JSON  native format is, on some platforms, (e.g. javascript), limited to 53-bit large
// integer space. Thus, U256 uses string-format, which is not compatible with
// big.int (big.Uint refuses to unmarshal a string representation).
func (z *Uint) MarshalJSON() ([]byte, error) {
	return []byte(`"` + z.Dec() + `"`), nil
}

// UnmarshalJSON implements json.Unmarshaler. UnmarshalJSON accepts either
// - Quoted string: either hexadecimal OR decimal
// - Not quoted string: only decimal
func (z *Uint) UnmarshalJSON(input []byte) error {
	if len(input) < 2 || input[0] != '"' || input[len(input)-1] != '"' {
		// if not quoted, it must be decimal
		return z.fromDecimal(string(input))
	}
	return z.UnmarshalText(input[1 : len(input)-1])
}

// MarshalText implements encoding.TextMarshaler
// MarshalText marshals using the decimal representation (compatible with big.Uint)
func (z *Uint) MarshalText() ([]byte, error) {
	return []byte(z.Dec()), nil
}

// UnmarshalText implements encoding.TextUnmarshaler. This method
// can unmarshal either hexadecimal or decimal.
// - For hexadecimal, the input _must_ be prefixed with 0x or 0X
func (z *Uint) UnmarshalText(input []byte) error {
	if len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') {
		return z.fromHex(string(input))
	}
	return z.fromDecimal(string(input))
}

// SetBytes interprets buf as the bytes of a big-endian unsigned
// integer, sets z to that value, and returns z.
// If buf is larger than 32 bytes, the last 32 bytes is used.
func (z *Uint) SetBytes(buf []byte) *Uint {
	switch l := len(buf); l {
	case 0:
		z.Clear()
	case 1:
		z.SetBytes1(buf)
	case 2:
		z.SetBytes2(buf)
	case 3:
		z.SetBytes3(buf)
	case 4:
		z.SetBytes4(buf)
	case 5:
		z.SetBytes5(buf)
	case 6:
		z.SetBytes6(buf)
	case 7:
		z.SetBytes7(buf)
	case 8:
		z.SetBytes8(buf)
	case 9:
		z.SetBytes9(buf)
	case 10:
		z.SetBytes10(buf)
	case 11:
		z.SetBytes11(buf)
	case 12:
		z.SetBytes12(buf)
	case 13:
		z.SetBytes13(buf)
	case 14:
		z.SetBytes14(buf)
	case 15:
		z.SetBytes15(buf)
	case 16:
		z.SetBytes16(buf)
	case 17:
		z.SetBytes17(buf)
	case 18:
		z.SetBytes18(buf)
	case 19:
		z.SetBytes19(buf)
	case 20:
		z.SetBytes20(buf)
	case 21:
		z.SetBytes21(buf)
	case 22:
		z.SetBytes22(buf)
	case 23:
		z.SetBytes23(buf)
	case 24:
		z.SetBytes24(buf)
	case 25:
		z.SetBytes25(buf)
	case 26:
		z.SetBytes26(buf)
	case 27:
		z.SetBytes27(buf)
	case 28:
		z.SetBytes28(buf)
	case 29:
		z.SetBytes29(buf)
	case 30:
		z.SetBytes30(buf)
	case 31:
		z.SetBytes31(buf)
	default:
		z.SetBytes32(buf[l-32:])
	}
	return z
}

// SetBytes1 is identical to SetBytes(in[:1]), but panics is input is too short
func (z *Uint) SetBytes1(in []byte) *Uint {
	z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0
	z.arr[0] = uint64(in[0])
	return z
}

// SetBytes2 is identical to SetBytes(in[:2]), but panics is input is too short
func (z *Uint) SetBytes2(in []byte) *Uint {
	_ = in[1] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0
	z.arr[0] = uint64(binary.BigEndian.Uint16(in[0:2]))
	return z
}

// SetBytes3 is identical to SetBytes(in[:3]), but panics is input is too short
func (z *Uint) SetBytes3(in []byte) *Uint {
	_ = in[2] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0
	z.arr[0] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])<<16
	return z
}

// SetBytes4 is identical to SetBytes(in[:4]), but panics is input is too short
func (z *Uint) SetBytes4(in []byte) *Uint {
	_ = in[3] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0
	z.arr[0] = uint64(binary.BigEndian.Uint32(in[0:4]))
	return z
}

// SetBytes5 is identical to SetBytes(in[:5]), but panics is input is too short
func (z *Uint) SetBytes5(in []byte) *Uint {
	_ = in[4] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0
	z.arr[0] = bigEndianUint40(in[0:5])
	return z
}

// SetBytes6 is identical to SetBytes(in[:6]), but panics is input is too short
func (z *Uint) SetBytes6(in []byte) *Uint {
	_ = in[5] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0
	z.arr[0] = bigEndianUint48(in[0:6])
	return z
}

// SetBytes7 is identical to SetBytes(in[:7]), but panics is input is too short
func (z *Uint) SetBytes7(in []byte) *Uint {
	_ = in[6] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0
	z.arr[0] = bigEndianUint56(in[0:7])
	return z
}

// SetBytes8 is identical to SetBytes(in[:8]), but panics is input is too short
func (z *Uint) SetBytes8(in []byte) *Uint {
	_ = in[7] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0
	z.arr[0] = binary.BigEndian.Uint64(in[0:8])
	return z
}

// SetBytes9 is identical to SetBytes(in[:9]), but panics is input is too short
func (z *Uint) SetBytes9(in []byte) *Uint {
	_ = in[8] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2] = 0, 0
	z.arr[1] = uint64(in[0])
	z.arr[0] = binary.BigEndian.Uint64(in[1:9])
	return z
}

// SetBytes10 is identical to SetBytes(in[:10]), but panics is input is too short
func (z *Uint) SetBytes10(in []byte) *Uint {
	_ = in[9] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2] = 0, 0
	z.arr[1] = uint64(binary.BigEndian.Uint16(in[0:2]))
	z.arr[0] = binary.BigEndian.Uint64(in[2:10])
	return z
}

// SetBytes11 is identical to SetBytes(in[:11]), but panics is input is too short
func (z *Uint) SetBytes11(in []byte) *Uint {
	_ = in[10] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2] = 0, 0
	z.arr[1] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])<<16
	z.arr[0] = binary.BigEndian.Uint64(in[3:11])
	return z
}

// SetBytes12 is identical to SetBytes(in[:12]), but panics is input is too short
func (z *Uint) SetBytes12(in []byte) *Uint {
	_ = in[11] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2] = 0, 0
	z.arr[1] = uint64(binary.BigEndian.Uint32(in[0:4]))
	z.arr[0] = binary.BigEndian.Uint64(in[4:12])
	return z
}

// SetBytes13 is identical to SetBytes(in[:13]), but panics is input is too short
func (z *Uint) SetBytes13(in []byte) *Uint {
	_ = in[12] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2] = 0, 0
	z.arr[1] = bigEndianUint40(in[0:5])
	z.arr[0] = binary.BigEndian.Uint64(in[5:13])
	return z
}

// SetBytes14 is identical to SetBytes(in[:14]), but panics is input is too short
func (z *Uint) SetBytes14(in []byte) *Uint {
	_ = in[13] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2] = 0, 0
	z.arr[1] = bigEndianUint48(in[0:6])
	z.arr[0] = binary.BigEndian.Uint64(in[6:14])
	return z
}

// SetBytes15 is identical to SetBytes(in[:15]), but panics is input is too short
func (z *Uint) SetBytes15(in []byte) *Uint {
	_ = in[14] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2] = 0, 0
	z.arr[1] = bigEndianUint56(in[0:7])
	z.arr[0] = binary.BigEndian.Uint64(in[7:15])
	return z
}

// SetBytes16 is identical to SetBytes(in[:16]), but panics is input is too short
func (z *Uint) SetBytes16(in []byte) *Uint {
	_ = in[15] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3], z.arr[2] = 0, 0
	z.arr[1] = binary.BigEndian.Uint64(in[0:8])
	z.arr[0] = binary.BigEndian.Uint64(in[8:16])
	return z
}

// SetBytes17 is identical to SetBytes(in[:17]), but panics is input is too short
func (z *Uint) SetBytes17(in []byte) *Uint {
	_ = in[16] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = 0
	z.arr[2] = uint64(in[0])
	z.arr[1] = binary.BigEndian.Uint64(in[1:9])
	z.arr[0] = binary.BigEndian.Uint64(in[9:17])
	return z
}

// SetBytes18 is identical to SetBytes(in[:18]), but panics is input is too short
func (z *Uint) SetBytes18(in []byte) *Uint {
	_ = in[17] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = 0
	z.arr[2] = uint64(binary.BigEndian.Uint16(in[0:2]))
	z.arr[1] = binary.BigEndian.Uint64(in[2:10])
	z.arr[0] = binary.BigEndian.Uint64(in[10:18])
	return z
}

// SetBytes19 is identical to SetBytes(in[:19]), but panics is input is too short
func (z *Uint) SetBytes19(in []byte) *Uint {
	_ = in[18] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = 0
	z.arr[2] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])<<16
	z.arr[1] = binary.BigEndian.Uint64(in[3:11])
	z.arr[0] = binary.BigEndian.Uint64(in[11:19])
	return z
}

// SetBytes20 is identical to SetBytes(in[:20]), but panics is input is too short
func (z *Uint) SetBytes20(in []byte) *Uint {
	_ = in[19] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = 0
	z.arr[2] = uint64(binary.BigEndian.Uint32(in[0:4]))
	z.arr[1] = binary.BigEndian.Uint64(in[4:12])
	z.arr[0] = binary.BigEndian.Uint64(in[12:20])
	return z
}

// SetBytes21 is identical to SetBytes(in[:21]), but panics is input is too short
func (z *Uint) SetBytes21(in []byte) *Uint {
	_ = in[20] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = 0
	z.arr[2] = bigEndianUint40(in[0:5])
	z.arr[1] = binary.BigEndian.Uint64(in[5:13])
	z.arr[0] = binary.BigEndian.Uint64(in[13:21])
	return z
}

// SetBytes22 is identical to SetBytes(in[:22]), but panics is input is too short
func (z *Uint) SetBytes22(in []byte) *Uint {
	_ = in[21] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = 0
	z.arr[2] = bigEndianUint48(in[0:6])
	z.arr[1] = binary.BigEndian.Uint64(in[6:14])
	z.arr[0] = binary.BigEndian.Uint64(in[14:22])
	return z
}

// SetBytes23 is identical to SetBytes(in[:23]), but panics is input is too short
func (z *Uint) SetBytes23(in []byte) *Uint {
	_ = in[22] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = 0
	z.arr[2] = bigEndianUint56(in[0:7])
	z.arr[1] = binary.BigEndian.Uint64(in[7:15])
	z.arr[0] = binary.BigEndian.Uint64(in[15:23])
	return z
}

// SetBytes24 is identical to SetBytes(in[:24]), but panics is input is too short
func (z *Uint) SetBytes24(in []byte) *Uint {
	_ = in[23] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = 0
	z.arr[2] = binary.BigEndian.Uint64(in[0:8])
	z.arr[1] = binary.BigEndian.Uint64(in[8:16])
	z.arr[0] = binary.BigEndian.Uint64(in[16:24])
	return z
}

// SetBytes25 is identical to SetBytes(in[:25]), but panics is input is too short
func (z *Uint) SetBytes25(in []byte) *Uint {
	_ = in[24] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = uint64(in[0])
	z.arr[2] = binary.BigEndian.Uint64(in[1:9])
	z.arr[1] = binary.BigEndian.Uint64(in[9:17])
	z.arr[0] = binary.BigEndian.Uint64(in[17:25])
	return z
}

// SetBytes26 is identical to SetBytes(in[:26]), but panics is input is too short
func (z *Uint) SetBytes26(in []byte) *Uint {
	_ = in[25] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = uint64(binary.BigEndian.Uint16(in[0:2]))
	z.arr[2] = binary.BigEndian.Uint64(in[2:10])
	z.arr[1] = binary.BigEndian.Uint64(in[10:18])
	z.arr[0] = binary.BigEndian.Uint64(in[18:26])
	return z
}

// SetBytes27 is identical to SetBytes(in[:27]), but panics is input is too short
func (z *Uint) SetBytes27(in []byte) *Uint {
	_ = in[26] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = uint64(binary.BigEndian.Uint16(in[1:3])) | uint64(in[0])<<16
	z.arr[2] = binary.BigEndian.Uint64(in[3:11])
	z.arr[1] = binary.BigEndian.Uint64(in[11:19])
	z.arr[0] = binary.BigEndian.Uint64(in[19:27])
	return z
}

// SetBytes28 is identical to SetBytes(in[:28]), but panics is input is too short
func (z *Uint) SetBytes28(in []byte) *Uint {
	_ = in[27] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = uint64(binary.BigEndian.Uint32(in[0:4]))
	z.arr[2] = binary.BigEndian.Uint64(in[4:12])
	z.arr[1] = binary.BigEndian.Uint64(in[12:20])
	z.arr[0] = binary.BigEndian.Uint64(in[20:28])
	return z
}

// SetBytes29 is identical to SetBytes(in[:29]), but panics is input is too short
func (z *Uint) SetBytes29(in []byte) *Uint {
	_ = in[23] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = bigEndianUint40(in[0:5])
	z.arr[2] = binary.BigEndian.Uint64(in[5:13])
	z.arr[1] = binary.BigEndian.Uint64(in[13:21])
	z.arr[0] = binary.BigEndian.Uint64(in[21:29])
	return z
}

// SetBytes30 is identical to SetBytes(in[:30]), but panics is input is too short
func (z *Uint) SetBytes30(in []byte) *Uint {
	_ = in[29] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = bigEndianUint48(in[0:6])
	z.arr[2] = binary.BigEndian.Uint64(in[6:14])
	z.arr[1] = binary.BigEndian.Uint64(in[14:22])
	z.arr[0] = binary.BigEndian.Uint64(in[22:30])
	return z
}

// SetBytes31 is identical to SetBytes(in[:31]), but panics is input is too short
func (z *Uint) SetBytes31(in []byte) *Uint {
	_ = in[30] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = bigEndianUint56(in[0:7])
	z.arr[2] = binary.BigEndian.Uint64(in[7:15])
	z.arr[1] = binary.BigEndian.Uint64(in[15:23])
	z.arr[0] = binary.BigEndian.Uint64(in[23:31])
	return z
}

// SetBytes32 sets z to the value of the big-endian 256-bit unsigned integer in.
func (z *Uint) SetBytes32(in []byte) *Uint {
	_ = in[31] // bounds check hint to compiler; see golang.org/issue/14808
	z.arr[3] = binary.BigEndian.Uint64(in[0:8])
	z.arr[2] = binary.BigEndian.Uint64(in[8:16])
	z.arr[1] = binary.BigEndian.Uint64(in[16:24])
	z.arr[0] = binary.BigEndian.Uint64(in[24:32])
	return z
}

// Utility methods that are "missing" among the bigEndian.UintXX methods.

// bigEndianUint40 returns the uint64 value represented by the 5 bytes in big-endian order.
func bigEndianUint40(b []byte) uint64 {
	_ = b[4] // bounds check hint to compiler; see golang.org/issue/14808
	return uint64(b[4]) | uint64(b[3])<<8 | uint64(b[2])<<16 | uint64(b[1])<<24 |
		uint64(b[0])<<32
}

// bigEndianUint56 returns the uint64 value represented by the 7 bytes in big-endian order.
func bigEndianUint56(b []byte) uint64 {
	_ = b[6] // bounds check hint to compiler; see golang.org/issue/14808
	return uint64(b[6]) | uint64(b[5])<<8 | uint64(b[4])<<16 | uint64(b[3])<<24 |
		uint64(b[2])<<32 | uint64(b[1])<<40 | uint64(b[0])<<48
}

// bigEndianUint48 returns the uint64 value represented by the 6 bytes in big-endian order.
func bigEndianUint48(b []byte) uint64 {
	_ = b[5] // bounds check hint to compiler; see golang.org/issue/14808
	return uint64(b[5]) | uint64(b[4])<<8 | uint64(b[3])<<16 | uint64(b[2])<<24 |
		uint64(b[1])<<32 | uint64(b[0])<<40
}

conversion_test.gno

package uint256

import "testing"

func TestIsUint64(t *testing.T) {
	tests := []struct {
		x    string
		want bool
	}{
		{"0x0", true},
		{"0x1", true},
		{"0x10", true},
		{"0xffffffffffffffff", true},
		{"0x10000000000000000", false},
	}

	for _, tt := range tests {
		x := MustFromHex(tt.x)
		got := x.IsUint64()

		if got != tt.want {
			t.Errorf("IsUint64(%s) = %v, want %v", tt.x, got, tt.want)
		}
	}
}

func TestDec(t *testing.T) {
	tests := []struct {
		name string
		z    Uint
		want string
	}{
		{
			name: "zero",
			z:    Uint{arr: [4]uint64{0, 0, 0, 0}},
			want: "0",
		},
		{
			name: "less than 20 digits",
			z:    Uint{arr: [4]uint64{1234567890, 0, 0, 0}},
			want: "1234567890",
		},
		{
			name: "max possible value",
			z:    Uint{arr: [4]uint64{^uint64(0), ^uint64(0), ^uint64(0), ^uint64(0)}},
			want: twoPow256Sub1,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			result := tt.z.Dec()
			if result != tt.want {
				t.Errorf("Dec(%v) = %s, want %s", tt.z, result, tt.want)
			}
		})
	}
}

func TestUint_Scan(t *testing.T) {
	tests := []struct {
		name    string
		input   any
		want    *Uint
		wantErr bool
	}{
		{
			name:  "nil",
			input: nil,
			want:  NewUint(0),
		},
		{
			name:  "valid scientific notation",
			input: "1e4",
			want:  NewUint(10000),
		},
		{
			name:  "valid decimal string",
			input: "12345",
			want:  NewUint(12345),
		},
		{
			name:  "valid byte slice",
			input: []byte("12345"),
			want:  NewUint(12345),
		},
		{
			name:    "invalid string",
			input:   "invalid",
			wantErr: true,
		},
		{
			name:    "out of range",
			input:   "115792089237316195423570985008687907853269984665640564039457584007913129639936", // 2^256
			wantErr: true,
		},
		{
			name:    "unsupported type",
			input:   123,
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			z := new(Uint)
			err := z.Scan(tt.input)

			if tt.wantErr {
				if err == nil {
					t.Errorf("Scan() error = %v, wantErr %v", err, tt.wantErr)
				}
			} else {
				if err != nil {
					t.Errorf("Scan() error = %v, wantErr %v", err, tt.wantErr)
				}
				if !z.Eq(tt.want) {
					t.Errorf("Scan() = %v, want %v", z, tt.want)
				}
			}
		})
	}
}

func TestSetBytes(t *testing.T) {
	tests := []struct {
		input    []byte
		expected string
	}{
		{[]byte{}, "0"},
		{[]byte{0x01}, "1"},
		{[]byte{0x12, 0x34}, "4660"},
		{[]byte{0x12, 0x34, 0x56}, "1193046"},
		{[]byte{0x12, 0x34, 0x56, 0x78}, "305419896"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a}, "78187493530"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}, "20015998343868"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde}, "5124095576030430"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, "1311768467463790320"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12}, "335812727670730321938"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34}, "85968058283706962416180"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56}, "22007822920628982378542166"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78}, "5634002667681019488906794616"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a}, "1442304682926340989160139421850"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}, "369229998829143293224995691993788"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde}, "94522879700260683065598897150409950"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, "24197857203266734864793317670504947440"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12}, "6194651444036284125387089323649266544658"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34}, "1585830769673288736099094866854212235432500"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56}, "405972677036361916441368285914678332270720086"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78}, "103929005321308650608990281194157653061304342136"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a}, "26605825362255014555901511985704359183693911586970"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}, "6811091292737283726310787068340315951025641366264508"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde}, "1743639370940744633935561489495120883462564189763714270"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, "446371678960830626287503741310750946166416432579510853360"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12}, "114271149813972640329600957775552242218602606740354778460178"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34}, "29253414352376995924377845190541374007962267325530823285805620"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56}, "7488874074208510956640728368778591746038340435335890761166238806"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78}, "1917151762997378804900026462407319486985815151445988034858557134456"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a}, "490790851327328974054406774376273788668368678770172936923790626420890"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}, "125642457939796217357928134240326089899102381765164271852490400363748028"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde}, "32164469232587831643629602365523479014170209731882053594237542493119495390"},
		{[]byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, "8234104123542484900769178205574010627627573691361805720124810878238590820080"},
		// over 32 bytes (last 32 bytes are used)
		{append([]byte{0xff}, []byte{0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}...), "8234104123542484900769178205574010627627573691361805720124810878238590820080"},
	}

	for _, test := range tests {
		z := new(Uint)
		z.SetBytes(test.input)
		expected := MustFromDecimal(test.expected)
		if z.Cmp(expected) != 0 {
			t.Errorf("SetBytes(%x) = %s, expected %s", test.input, z.String(), test.expected)
		}
	}
}

error.gno

package uint256

import (
	"errors"
)

var (
	ErrEmptyString      = errors.New("empty hex string")
	ErrSyntax           = errors.New("invalid hex string")
	ErrRange            = errors.New("number out of range")
	ErrMissingPrefix    = errors.New("hex string without 0x prefix")
	ErrEmptyNumber      = errors.New("hex string \"0x\"")
	ErrLeadingZero      = errors.New("hex number with leading zero digits")
	ErrBig256Range      = errors.New("hex number > 256 bits")
	ErrBadBufferLength  = errors.New("bad ssz buffer length")
	ErrBadEncodedLength = errors.New("bad ssz encoded length")
	ErrInvalidBase      = errors.New("invalid base")
	ErrInvalidBitSize   = errors.New("invalid bit size")
)

type u256Error struct {
	fn    string // function name
	input string
	err   error
}

func (e *u256Error) Error() string {
	return e.fn + ": " + e.input + ": " + e.err.Error()
}

func (e *u256Error) Unwrap() error {
	return e.err
}

func errEmptyString(fn, input string) error {
	return &u256Error{fn: fn, input: input, err: ErrEmptyString}
}

func errSyntax(fn, input string) error {
	return &u256Error{fn: fn, input: input, err: ErrSyntax}
}

func errMissingPrefix(fn, input string) error {
	return &u256Error{fn: fn, input: input, err: ErrMissingPrefix}
}

func errEmptyNumber(fn, input string) error {
	return &u256Error{fn: fn, input: input, err: ErrEmptyNumber}
}

func errLeadingZero(fn, input string) error {
	return &u256Error{fn: fn, input: input, err: ErrLeadingZero}
}

func errRange(fn, input string) error {
	return &u256Error{fn: fn, input: input, err: ErrRange}
}

func errBig256Range(fn, input string) error {
	return &u256Error{fn: fn, input: input, err: ErrBig256Range}
}

func errBadBufferLength(fn, input string) error {
	return &u256Error{fn: fn, input: input, err: ErrBadBufferLength}
}

func errInvalidBase(fn string, base int) error {
	return &u256Error{fn: fn, input: string(base), err: ErrInvalidBase}
}

func errInvalidBitSize(fn string, bitSize int) error {
	return &u256Error{fn: fn, input: string(bitSize), err: ErrInvalidBitSize}
}

gnomod.toml

module = "gno.land/p/onbloc/uint256/v0"
gno = "0.9"

[addpkg]
  creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"

mod.gno

package uint256

import (
	"math/bits"
)

// Some utility functions

// Reciprocal computes a 320-bit value representing 1/m
//
// Notes:
// - specialized for m.arr[3] != 0, hence limited to 2^192 <= m < 2^256
// - returns zero if m.arr[3] == 0
// - starts with a 32-bit division, refines with newton-raphson iterations
func Reciprocal(m *Uint) (mu [5]uint64) {
	if m.arr[3] == 0 {
		return mu
	}

	s := bits.LeadingZeros64(m.arr[3]) // Replace with leadingZeros(m) for general case
	p := 255 - s                       // floor(log_2(m)), m>0

	// 0 or a power of 2?

	// Check if at least one bit is set in m.arr[2], m.arr[1] or m.arr[0],
	// or at least two bits in m.arr[3]

	if m.arr[0]|m.arr[1]|m.arr[2]|(m.arr[3]&(m.arr[3]-1)) == 0 {

		mu[4] = ^uint64(0) >> uint(p&63)
		mu[3] = ^uint64(0)
		mu[2] = ^uint64(0)
		mu[1] = ^uint64(0)
		mu[0] = ^uint64(0)

		return mu
	}

	// Maximise division precision by left-aligning divisor

	var (
		y  Uint   // left-aligned copy of m
		r0 uint32 // estimate of 2^31/y
	)

	y.Lsh(m, uint(s)) // 1/2 < y < 1

	// Extract most significant 32 bits

	yh := uint32(y.arr[3] >> 32)

	if yh == 0x80000000 { // Avoid overflow in division
		r0 = 0xffffffff
	} else {
		r0, _ = bits.Div32(0x80000000, 0, yh)
	}

	// First iteration: 32 -> 64

	t1 := uint64(r0)                 // 2^31/y
	t1 *= t1                         // 2^62/y^2
	t1, _ = bits.Mul64(t1, y.arr[3]) // 2^62/y^2 * 2^64/y / 2^64 = 2^62/y

	r1 := uint64(r0) << 32 // 2^63/y
	r1 -= t1               // 2^63/y - 2^62/y = 2^62/y
	r1 *= 2                // 2^63/y

	if (r1 | (y.arr[3] << 1)) == 0 {
		r1 = ^uint64(0)
	}

	// Second iteration: 64 -> 128

	// square: 2^126/y^2
	a2h, a2l := bits.Mul64(r1, r1)

	// multiply by y: e2h:e2l:b2h = 2^126/y^2 * 2^128/y / 2^128 = 2^126/y
	b2h, _ := bits.Mul64(a2l, y.arr[2])
	c2h, c2l := bits.Mul64(a2l, y.arr[3])
	d2h, d2l := bits.Mul64(a2h, y.arr[2])
	e2h, e2l := bits.Mul64(a2h, y.arr[3])

	b2h, c := bits.Add64(b2h, c2l, 0)
	e2l, c = bits.Add64(e2l, c2h, c)
	e2h, _ = bits.Add64(e2h, 0, c)

	_, c = bits.Add64(b2h, d2l, 0)
	e2l, c = bits.Add64(e2l, d2h, c)
	e2h, _ = bits.Add64(e2h, 0, c)

	// subtract: t2h:t2l = 2^127/y - 2^126/y = 2^126/y
	t2l, b := bits.Sub64(0, e2l, 0)
	t2h, _ := bits.Sub64(r1, e2h, b)

	// double: r2h:r2l = 2^127/y
	r2l, c := bits.Add64(t2l, t2l, 0)
	r2h, _ := bits.Add64(t2h, t2h, c)

	if (r2h | r2l | (y.arr[3] << 1)) == 0 {
		r2h = ^uint64(0)
		r2l = ^uint64(0)
	}

	// Third iteration: 128 -> 192

	// square r2 (keep 256 bits): 2^190/y^2
	a3h, a3l := bits.Mul64(r2l, r2l)
	b3h, b3l := bits.Mul64(r2l, r2h)
	c3h, c3l := bits.Mul64(r2h, r2h)

	a3h, c = bits.Add64(a3h, b3l, 0)
	c3l, c = bits.Add64(c3l, b3h, c)
	c3h, _ = bits.Add64(c3h, 0, c)

	a3h, c = bits.Add64(a3h, b3l, 0)
	c3l, c = bits.Add64(c3l, b3h, c)
	c3h, _ = bits.Add64(c3h, 0, c)

	// multiply by y: q = 2^190/y^2 * 2^192/y / 2^192 = 2^190/y

	x0 := a3l
	x1 := a3h
	x2 := c3l
	x3 := c3h

	var q0, q1, q2, q3, q4, t0 uint64

	q0, _ = bits.Mul64(x2, y.arr[0])
	q1, t0 = bits.Mul64(x3, y.arr[0])
	q0, c = bits.Add64(q0, t0, 0)
	q1, _ = bits.Add64(q1, 0, c)

	t1, _ = bits.Mul64(x1, y.arr[1])
	q0, c = bits.Add64(q0, t1, 0)
	q2, t0 = bits.Mul64(x3, y.arr[1])
	q1, c = bits.Add64(q1, t0, c)
	q2, _ = bits.Add64(q2, 0, c)

	t1, t0 = bits.Mul64(x2, y.arr[1])
	q0, c = bits.Add64(q0, t0, 0)
	q1, c = bits.Add64(q1, t1, c)
	q2, _ = bits.Add64(q2, 0, c)

	t1, t0 = bits.Mul64(x1, y.arr[2])
	q0, c = bits.Add64(q0, t0, 0)
	q1, c = bits.Add64(q1, t1, c)
	q3, t0 = bits.Mul64(x3, y.arr[2])
	q2, c = bits.Add64(q2, t0, c)
	q3, _ = bits.Add64(q3, 0, c)

	t1, _ = bits.Mul64(x0, y.arr[2])
	q0, c = bits.Add64(q0, t1, 0)
	t1, t0 = bits.Mul64(x2, y.arr[2])
	q1, c = bits.Add64(q1, t0, c)
	q2, c = bits.Add64(q2, t1, c)
	q3, _ = bits.Add64(q3, 0, c)

	t1, t0 = bits.Mul64(x1, y.arr[3])
	q1, c = bits.Add64(q1, t0, 0)
	q2, c = bits.Add64(q2, t1, c)
	q4, t0 = bits.Mul64(x3, y.arr[3])
	q3, c = bits.Add64(q3, t0, c)
	q4, _ = bits.Add64(q4, 0, c)

	t1, t0 = bits.Mul64(x0, y.arr[3])
	q0, c = bits.Add64(q0, t0, 0)
	q1, c = bits.Add64(q1, t1, c)
	t1, t0 = bits.Mul64(x2, y.arr[3])
	q2, c = bits.Add64(q2, t0, c)
	q3, c = bits.Add64(q3, t1, c)
	q4, _ = bits.Add64(q4, 0, c)

	// subtract: t3 = 2^191/y - 2^190/y = 2^190/y
	_, b = bits.Sub64(0, q0, 0)
	_, b = bits.Sub64(0, q1, b)
	t3l, b := bits.Sub64(0, q2, b)
	t3m, b := bits.Sub64(r2l, q3, b)
	t3h, _ := bits.Sub64(r2h, q4, b)

	// double: r3 = 2^191/y
	r3l, c := bits.Add64(t3l, t3l, 0)
	r3m, c := bits.Add64(t3m, t3m, c)
	r3h, _ := bits.Add64(t3h, t3h, c)

	// Fourth iteration: 192 -> 320

	// square r3

	a4h, a4l := bits.Mul64(r3l, r3l)
	b4h, b4l := bits.Mul64(r3l, r3m)
	c4h, c4l := bits.Mul64(r3l, r3h)
	d4h, d4l := bits.Mul64(r3m, r3m)
	e4h, e4l := bits.Mul64(r3m, r3h)
	f4h, f4l := bits.Mul64(r3h, r3h)

	b4h, c = bits.Add64(b4h, c4l, 0)
	e4l, c = bits.Add64(e4l, c4h, c)
	e4h, _ = bits.Add64(e4h, 0, c)

	a4h, c = bits.Add64(a4h, b4l, 0)
	d4l, c = bits.Add64(d4l, b4h, c)
	d4h, c = bits.Add64(d4h, e4l, c)
	f4l, c = bits.Add64(f4l, e4h, c)
	f4h, _ = bits.Add64(f4h, 0, c)

	a4h, c = bits.Add64(a4h, b4l, 0)
	d4l, c = bits.Add64(d4l, b4h, c)
	d4h, c = bits.Add64(d4h, e4l, c)
	f4l, c = bits.Add64(f4l, e4h, c)
	f4h, _ = bits.Add64(f4h, 0, c)

	// multiply by y

	x1, x0 = bits.Mul64(d4h, y.arr[0])
	x3, x2 = bits.Mul64(f4h, y.arr[0])
	t1, t0 = bits.Mul64(f4l, y.arr[0])
	x1, c = bits.Add64(x1, t0, 0)
	x2, c = bits.Add64(x2, t1, c)
	x3, _ = bits.Add64(x3, 0, c)

	t1, t0 = bits.Mul64(d4h, y.arr[1])
	x1, c = bits.Add64(x1, t0, 0)
	x2, c = bits.Add64(x2, t1, c)
	x4, t0 := bits.Mul64(f4h, y.arr[1])
	x3, c = bits.Add64(x3, t0, c)
	x4, _ = bits.Add64(x4, 0, c)
	t1, t0 = bits.Mul64(d4l, y.arr[1])
	x0, c = bits.Add64(x0, t0, 0)
	x1, c = bits.Add64(x1, t1, c)
	t1, t0 = bits.Mul64(f4l, y.arr[1])
	x2, c = bits.Add64(x2, t0, c)
	x3, c = bits.Add64(x3, t1, c)
	x4, _ = bits.Add64(x4, 0, c)

	t1, t0 = bits.Mul64(a4h, y.arr[2])
	x0, c = bits.Add64(x0, t0, 0)
	x1, c = bits.Add64(x1, t1, c)
	t1, t0 = bits.Mul64(d4h, y.arr[2])
	x2, c = bits.Add64(x2, t0, c)
	x3, c = bits.Add64(x3, t1, c)
	x5, t0 := bits.Mul64(f4h, y.arr[2])
	x4, c = bits.Add64(x4, t0, c)
	x5, _ = bits.Add64(x5, 0, c)
	t1, t0 = bits.Mul64(d4l, y.arr[2])
	x1, c = bits.Add64(x1, t0, 0)
	x2, c = bits.Add64(x2, t1, c)
	t1, t0 = bits.Mul64(f4l, y.arr[2])
	x3, c = bits.Add64(x3, t0, c)
	x4, c = bits.Add64(x4, t1, c)
	x5, _ = bits.Add64(x5, 0, c)

	t1, t0 = bits.Mul64(a4h, y.arr[3])
	x1, c = bits.Add64(x1, t0, 0)
	x2, c = bits.Add64(x2, t1, c)
	t1, t0 = bits.Mul64(d4h, y.arr[3])
	x3, c = bits.Add64(x3, t0, c)
	x4, c = bits.Add64(x4, t1, c)
	x6, t0 := bits.Mul64(f4h, y.arr[3])
	x5, c = bits.Add64(x5, t0, c)
	x6, _ = bits.Add64(x6, 0, c)
	t1, t0 = bits.Mul64(a4l, y.arr[3])
	x0, c = bits.Add64(x0, t0, 0)
	x1, c = bits.Add64(x1, t1, c)
	t1, t0 = bits.Mul64(d4l, y.arr[3])
	x2, c = bits.Add64(x2, t0, c)
	x3, c = bits.Add64(x3, t1, c)
	t1, t0 = bits.Mul64(f4l, y.arr[3])
	x4, c = bits.Add64(x4, t0, c)
	x5, c = bits.Add64(x5, t1, c)
	x6, _ = bits.Add64(x6, 0, c)

	// subtract
	_, b = bits.Sub64(0, x0, 0)
	_, b = bits.Sub64(0, x1, b)
	r4l, b := bits.Sub64(0, x2, b)
	r4k, b := bits.Sub64(0, x3, b)
	r4j, b := bits.Sub64(r3l, x4, b)
	r4i, b := bits.Sub64(r3m, x5, b)
	r4h, _ := bits.Sub64(r3h, x6, b)

	// Multiply candidate for 1/4y by y, with full precision

	x0 = r4l
	x1 = r4k
	x2 = r4j
	x3 = r4i
	x4 = r4h

	q1, q0 = bits.Mul64(x0, y.arr[0])
	q3, q2 = bits.Mul64(x2, y.arr[0])
	q5, q4 := bits.Mul64(x4, y.arr[0])

	t1, t0 = bits.Mul64(x1, y.arr[0])
	q1, c = bits.Add64(q1, t0, 0)
	q2, c = bits.Add64(q2, t1, c)
	t1, t0 = bits.Mul64(x3, y.arr[0])
	q3, c = bits.Add64(q3, t0, c)
	q4, c = bits.Add64(q4, t1, c)
	q5, _ = bits.Add64(q5, 0, c)

	t1, t0 = bits.Mul64(x0, y.arr[1])
	q1, c = bits.Add64(q1, t0, 0)
	q2, c = bits.Add64(q2, t1, c)
	t1, t0 = bits.Mul64(x2, y.arr[1])
	q3, c = bits.Add64(q3, t0, c)
	q4, c = bits.Add64(q4, t1, c)
	q6, t0 := bits.Mul64(x4, y.arr[1])
	q5, c = bits.Add64(q5, t0, c)
	q6, _ = bits.Add64(q6, 0, c)

	t1, t0 = bits.Mul64(x1, y.arr[1])
	q2, c = bits.Add64(q2, t0, 0)
	q3, c = bits.Add64(q3, t1, c)
	t1, t0 = bits.Mul64(x3, y.arr[1])
	q4, c = bits.Add64(q4, t0, c)
	q5, c = bits.Add64(q5, t1, c)
	q6, _ = bits.Add64(q6, 0, c)

	t1, t0 = bits.Mul64(x0, y.arr[2])
	q2, c = bits.Add64(q2, t0, 0)
	q3, c = bits.Add64(q3, t1, c)
	t1, t0 = bits.Mul64(x2, y.arr[2])
	q4, c = bits.Add64(q4, t0, c)
	q5, c = bits.Add64(q5, t1, c)
	q7, t0 := bits.Mul64(x4, y.arr[2])
	q6, c = bits.Add64(q6, t0, c)
	q7, _ = bits.Add64(q7, 0, c)

	t1, t0 = bits.Mul64(x1, y.arr[2])
	q3, c = bits.Add64(q3, t0, 0)
	q4, c = bits.Add64(q4, t1, c)
	t1, t0 = bits.Mul64(x3, y.arr[2])
	q5, c = bits.Add64(q5, t0, c)
	q6, c = bits.Add64(q6, t1, c)
	q7, _ = bits.Add64(q7, 0, c)

	t1, t0 = bits.Mul64(x0, y.arr[3])
	q3, c = bits.Add64(q3, t0, 0)
	q4, c = bits.Add64(q4, t1, c)
	t1, t0 = bits.Mul64(x2, y.arr[3])
	q5, c = bits.Add64(q5, t0, c)
	q6, c = bits.Add64(q6, t1, c)
	q8, t0 := bits.Mul64(x4, y.arr[3])
	q7, c = bits.Add64(q7, t0, c)
	q8, _ = bits.Add64(q8, 0, c)

	t1, t0 = bits.Mul64(x1, y.arr[3])
	q4, c = bits.Add64(q4, t0, 0)
	q5, c = bits.Add64(q5, t1, c)
	t1, t0 = bits.Mul64(x3, y.arr[3])
	q6, c = bits.Add64(q6, t0, c)
	q7, c = bits.Add64(q7, t1, c)
	q8, _ = bits.Add64(q8, 0, c)

	// Final adjustment

	// subtract q from 1/4
	_, b = bits.Sub64(0, q0, 0)
	_, b = bits.Sub64(0, q1, b)
	_, b = bits.Sub64(0, q2, b)
	_, b = bits.Sub64(0, q3, b)
	_, b = bits.Sub64(0, q4, b)
	_, b = bits.Sub64(0, q5, b)
	_, b = bits.Sub64(0, q6, b)
	_, b = bits.Sub64(0, q7, b)
	_, b = bits.Sub64(uint64(1)<<62, q8, b)

	// decrement the result
	x0, t := bits.Sub64(r4l, 1, 0)
	x1, t = bits.Sub64(r4k, 0, t)
	x2, t = bits.Sub64(r4j, 0, t)
	x3, t = bits.Sub64(r4i, 0, t)
	x4, _ = bits.Sub64(r4h, 0, t)

	// commit the decrement if the subtraction underflowed (reciprocal was too large)
	if b != 0 {
		r4h, r4i, r4j, r4k, r4l = x4, x3, x2, x1, x0
	}

	// Shift to correct bit alignment, truncating excess bits

	p = (p & 63) - 1

	x0, c = bits.Add64(r4l, r4l, 0)
	x1, c = bits.Add64(r4k, r4k, c)
	x2, c = bits.Add64(r4j, r4j, c)
	x3, c = bits.Add64(r4i, r4i, c)
	x4, _ = bits.Add64(r4h, r4h, c)

	if p < 0 {
		r4h, r4i, r4j, r4k, r4l = x4, x3, x2, x1, x0
		p = 0 // avoid negative shift below
	}

	{
		r := uint(p)      // right shift
		l := uint(64 - r) // left shift

		x0 = (r4l >> r) | (r4k << l)
		x1 = (r4k >> r) | (r4j << l)
		x2 = (r4j >> r) | (r4i << l)
		x3 = (r4i >> r) | (r4h << l)
		x4 = (r4h >> r)
	}

	if p > 0 {
		r4h, r4i, r4j, r4k, r4l = x4, x3, x2, x1, x0
	}

	mu[0] = r4l
	mu[1] = r4k
	mu[2] = r4j
	mu[3] = r4i
	mu[4] = r4h

	return mu
}

// reduce4 computes the least non-negative residue of x modulo m
//
// requires a four-word modulus (m.arr[3] > 1) and its inverse (mu)
func reduce4(x [8]uint64, m *Uint, mu [5]uint64) (z Uint) {
	// NB: Most variable names in the comments match the pseudocode for
	// 	Barrett reduction in the Handbook of Applied Cryptography.

	// q1 = x/2^192

	x0 := x[3]
	x1 := x[4]
	x2 := x[5]
	x3 := x[6]
	x4 := x[7]

	// q2 = q1 * mu; q3 = q2 / 2^320

	var q0, q1, q2, q3, q4, q5, t0, t1, c uint64

	q0, _ = bits.Mul64(x3, mu[0])
	q1, t0 = bits.Mul64(x4, mu[0])
	q0, c = bits.Add64(q0, t0, 0)
	q1, _ = bits.Add64(q1, 0, c)

	t1, _ = bits.Mul64(x2, mu[1])
	q0, c = bits.Add64(q0, t1, 0)
	q2, t0 = bits.Mul64(x4, mu[1])
	q1, c = bits.Add64(q1, t0, c)
	q2, _ = bits.Add64(q2, 0, c)

	t1, t0 = bits.Mul64(x3, mu[1])
	q0, c = bits.Add64(q0, t0, 0)
	q1, c = bits.Add64(q1, t1, c)
	q2, _ = bits.Add64(q2, 0, c)

	t1, t0 = bits.Mul64(x2, mu[2])
	q0, c = bits.Add64(q0, t0, 0)
	q1, c = bits.Add64(q1, t1, c)
	q3, t0 = bits.Mul64(x4, mu[2])
	q2, c = bits.Add64(q2, t0, c)
	q3, _ = bits.Add64(q3, 0, c)

	t1, _ = bits.Mul64(x1, mu[2])
	q0, c = bits.Add64(q0, t1, 0)
	t1, t0 = bits.Mul64(x3, mu[2])
	q1, c = bits.Add64(q1, t0, c)
	q2, c = bits.Add64(q2, t1, c)
	q3, _ = bits.Add64(q3, 0, c)

	t1, _ = bits.Mul64(x0, mu[3])
	q0, c = bits.Add64(q0, t1, 0)
	t1, t0 = bits.Mul64(x2, mu[3])
	q1, c = bits.Add64(q1, t0, c)
	q2, c = bits.Add64(q2, t1, c)
	q4, t0 = bits.Mul64(x4, mu[3])
	q3, c = bits.Add64(q3, t0, c)
	q4, _ = bits.Add64(q4, 0, c)

	t1, t0 = bits.Mul64(x1, mu[3])
	q0, c = bits.Add64(q0, t0, 0)
	q1, c = bits.Add64(q1, t1, c)
	t1, t0 = bits.Mul64(x3, mu[3])
	q2, c = bits.Add64(q2, t0, c)
	q3, c = bits.Add64(q3, t1, c)
	q4, _ = bits.Add64(q4, 0, c)

	t1, t0 = bits.Mul64(x0, mu[4])
	_, c = bits.Add64(q0, t0, 0)
	q1, c = bits.Add64(q1, t1, c)
	t1, t0 = bits.Mul64(x2, mu[4])
	q2, c = bits.Add64(q2, t0, c)
	q3, c = bits.Add64(q3, t1, c)
	q5, t0 = bits.Mul64(x4, mu[4])
	q4, c = bits.Add64(q4, t0, c)
	q5, _ = bits.Add64(q5, 0, c)

	t1, t0 = bits.Mul64(x1, mu[4])
	q1, c = bits.Add64(q1, t0, 0)
	q2, c = bits.Add64(q2, t1, c)
	t1, t0 = bits.Mul64(x3, mu[4])
	q3, c = bits.Add64(q3, t0, c)
	q4, c = bits.Add64(q4, t1, c)
	q5, _ = bits.Add64(q5, 0, c)

	// Drop the fractional part of q3

	q0 = q1
	q1 = q2
	q2 = q3
	q3 = q4
	q4 = q5

	// r1 = x mod 2^320

	x0 = x[0]
	x1 = x[1]
	x2 = x[2]
	x3 = x[3]
	x4 = x[4]

	// r2 = q3 * m mod 2^320

	var r0, r1, r2, r3, r4 uint64

	r4, r3 = bits.Mul64(q0, m.arr[3])
	_, t0 = bits.Mul64(q1, m.arr[3])
	r4, _ = bits.Add64(r4, t0, 0)

	t1, r2 = bits.Mul64(q0, m.arr[2])
	r3, c = bits.Add64(r3, t1, 0)
	_, t0 = bits.Mul64(q2, m.arr[2])
	r4, _ = bits.Add64(r4, t0, c)

	t1, t0 = bits.Mul64(q1, m.arr[2])
	r3, c = bits.Add64(r3, t0, 0)
	r4, _ = bits.Add64(r4, t1, c)

	t1, r1 = bits.Mul64(q0, m.arr[1])
	r2, c = bits.Add64(r2, t1, 0)
	t1, t0 = bits.Mul64(q2, m.arr[1])
	r3, c = bits.Add64(r3, t0, c)
	r4, _ = bits.Add64(r4, t1, c)

	t1, t0 = bits.Mul64(q1, m.arr[1])
	r2, c = bits.Add64(r2, t0, 0)
	r3, c = bits.Add64(r3, t1, c)
	_, t0 = bits.Mul64(q3, m.arr[1])
	r4, _ = bits.Add64(r4, t0, c)

	t1, r0 = bits.Mul64(q0, m.arr[0])
	r1, c = bits.Add64(r1, t1, 0)
	t1, t0 = bits.Mul64(q2, m.arr[0])
	r2, c = bits.Add64(r2, t0, c)
	r3, c = bits.Add64(r3, t1, c)
	_, t0 = bits.Mul64(q4, m.arr[0])
	r4, _ = bits.Add64(r4, t0, c)

	t1, t0 = bits.Mul64(q1, m.arr[0])
	r1, c = bits.Add64(r1, t0, 0)
	r2, c = bits.Add64(r2, t1, c)
	t1, t0 = bits.Mul64(q3, m.arr[0])
	r3, c = bits.Add64(r3, t0, c)
	r4, _ = bits.Add64(r4, t1, c)

	// r = r1 - r2

	var b uint64

	r0, b = bits.Sub64(x0, r0, 0)
	r1, b = bits.Sub64(x1, r1, b)
	r2, b = bits.Sub64(x2, r2, b)
	r3, b = bits.Sub64(x3, r3, b)
	r4, b = bits.Sub64(x4, r4, b)

	// if r<0 then r+=m

	if b != 0 {
		r0, c = bits.Add64(r0, m.arr[0], 0)
		r1, c = bits.Add64(r1, m.arr[1], c)
		r2, c = bits.Add64(r2, m.arr[2], c)
		r3, c = bits.Add64(r3, m.arr[3], c)
		r4, _ = bits.Add64(r4, 0, c)
	}

	// while (r>=m) r-=m

	for {
		// q = r - m
		q0, b = bits.Sub64(r0, m.arr[0], 0)
		q1, b = bits.Sub64(r1, m.arr[1], b)
		q2, b = bits.Sub64(r2, m.arr[2], b)
		q3, b = bits.Sub64(r3, m.arr[3], b)
		q4, b = bits.Sub64(r4, 0, b)

		// if borrow break
		if b != 0 {
			break
		}

		// r = q
		r4, r3, r2, r1, r0 = q4, q3, q2, q1, q0
	}

	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = r3, r2, r1, r0

	return z
}

uint256.gno

// Ported from https://github.com/holiman/uint256
// This package provides a 256-bit unsigned integer type, Uint256, and associated functions.
package uint256

import (
	"errors"
	"math/bits"
	"strconv"
)

const (
	MaxUint64 = 1<<64 - 1
	uintSize  = 32 << (^uint(0) >> 63)
)

// Uint is represented as an array of 4 uint64, in little-endian order,
// so that Uint[3] is the most significant, and Uint[0] is the least significant
type Uint struct {
	arr [4]uint64
}

// NewUint returns a new initialized Uint.
func NewUint(val uint64) *Uint {
	z := &Uint{arr: [4]uint64{val, 0, 0, 0}}
	return z
}

// Zero returns a new Uint initialized to zero.
func Zero() *Uint {
	return NewUint(0)
}

// One returns a new Uint initialized to one.
func One() *Uint {
	return NewUint(1)
}

// SetAllOne sets all the bits of z to 1
func (z *Uint) SetAllOne() *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = MaxUint64, MaxUint64, MaxUint64, MaxUint64
	return z
}

// Set sets z to x and returns z.
func (z *Uint) Set(x *Uint) *Uint {
	*z = *x

	return z
}

// SetOne sets z to 1
func (z *Uint) SetOne() *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, 1
	return z
}

const twoPow256Sub1 = "115792089237316195423570985008687907853269984665640564039457584007913129639935"

// SetFromDecimal sets z from the given string, interpreted as a decimal number.
// OBS! This method is _not_ strictly identical to the (*big.Uint).SetString(..., 10) method.
// Notable differences:
// - This method does not accept underscore input, e.g. "100_000",
// - This method does not accept negative zero as valid, e.g "-0",
//   - (this method does not accept any negative input as valid))
func (z *Uint) SetFromDecimal(s string) (err error) {
	// Remove max one leading +
	if len(s) > 0 && s[0] == '+' {
		s = s[1:]
	}
	// Remove any number of leading zeroes
	if len(s) > 0 && s[0] == '0' {
		var i int
		var c rune
		for i, c = range s {
			if c != '0' {
				break
			}
		}
		s = s[i:]
	}
	if len(s) < len(twoPow256Sub1) {
		return z.fromDecimal(s)
	}
	if len(s) == len(twoPow256Sub1) {
		if s > twoPow256Sub1 {
			return ErrBig256Range
		}
		return z.fromDecimal(s)
	}
	return ErrBig256Range
}

// FromDecimal is a convenience-constructor to create an Uint from a
// decimal (base 10) string. Numbers larger than 256 bits are not accepted.
func FromDecimal(decimal string) (*Uint, error) {
	var z Uint
	if err := z.SetFromDecimal(decimal); err != nil {
		return nil, err
	}
	return &z, nil
}

// MustFromDecimal is a convenience-constructor to create an Uint from a
// decimal (base 10) string.
// Returns a new Uint and panics if any error occurred.
func MustFromDecimal(decimal string) *Uint {
	var z Uint
	if err := z.SetFromDecimal(decimal); err != nil {
		panic(err)
	}
	return &z
}

// multipliers holds the values that are needed for fromDecimal
var multipliers = [5]*Uint{
	nil, // represents first round, no multiplication needed
	{[4]uint64{10000000000000000000, 0, 0, 0}},                                     // 10 ^ 19
	{[4]uint64{687399551400673280, 5421010862427522170, 0, 0}},                     // 10 ^ 38
	{[4]uint64{5332261958806667264, 17004971331911604867, 2938735877055718769, 0}}, // 10 ^ 57
	{[4]uint64{0, 8607968719199866880, 532749306367912313, 1593091911132452277}},   // 10 ^ 76
}

// fromDecimal is a helper function to only ever be called via SetFromDecimal
// this function takes a string and chunks it up, calling ParseUint on it up to 5 times
// these chunks are then multiplied by the proper power of 10, then added together.
func (z *Uint) fromDecimal(bs string) error {
	// first clear the input
	z.Clear()
	// the maximum value of uint64 is 18446744073709551615, which is 20 characters
	// one less means that a string of 19 9's is always within the uint64 limit
	var (
		num       uint64
		err       error
		remaining = len(bs)
	)
	if remaining == 0 {
		return errors.New("EOF")
	}
	// We proceed in steps of 19 characters (nibbles), from least significant to most significant.
	// This means that the first (up to) 19 characters do not need to be multiplied.
	// In the second iteration, our slice of 19 characters needs to be multipleied
	// by a factor of 10^19. Et cetera.
	for i, mult := range multipliers {
		if remaining <= 0 {
			return nil // Done
		} else if remaining > 19 {
			num, err = strconv.ParseUint(bs[remaining-19:remaining], 10, 64)
		} else {
			// Final round
			num, err = strconv.ParseUint(bs, 10, 64)
		}
		if err != nil {
			return err
		}
		// add that number to our running total
		if i == 0 {
			z.SetUint64(num)
		} else {
			base := NewUint(num)
			z.Add(z, base.Mul(base, mult))
		}
		// Chop off another 19 characters
		if remaining > 19 {
			bs = bs[0 : remaining-19]
		}
		remaining -= 19
	}
	return nil
}

// Byte sets z to the value of the byte at position n,
// with 'z' considered as a big-endian 32-byte integer
// if 'n' > 32, f is set to 0
// Example: f = '5', n=31 => 5
func (z *Uint) Byte(n *Uint) *Uint {
	// in z, z.arr[0] is the least significant
	if number, overflow := n.Uint64WithOverflow(); !overflow {
		if number < 32 {
			number := z.arr[4-1-number/8]
			offset := (n.arr[0] & 0x7) << 3 // 8*(n.d % 8)
			z.arr[0] = (number & (0xff00000000000000 >> offset)) >> (56 - offset)
			z.arr[3], z.arr[2], z.arr[1] = 0, 0, 0
			return z
		}
	}

	return z.Clear()
}

// BitLen returns the number of bits required to represent z
func (z *Uint) BitLen() int {
	switch {
	case z.arr[3] != 0:
		return 192 + bits.Len64(z.arr[3])
	case z.arr[2] != 0:
		return 128 + bits.Len64(z.arr[2])
	case z.arr[1] != 0:
		return 64 + bits.Len64(z.arr[1])
	default:
		return bits.Len64(z.arr[0])
	}
}

// ByteLen returns the number of bytes required to represent z
func (z *Uint) ByteLen() int {
	return (z.BitLen() + 7) / 8
}

// Clear sets z to 0
func (z *Uint) Clear() *Uint {
	z.arr[3], z.arr[2], z.arr[1], z.arr[0] = 0, 0, 0, 0
	return z
}

const (
	// hextable  = "0123456789abcdef"
	bintable  = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x01\x02\x03\x04\x05\x06\a\b\t\xff\xff\xff\xff\xff\xff\xff\n\v\f\r\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\n\v\f\r\x0e\x0f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
	badNibble = 0xff
)

// SetFromHex sets z from the given string, interpreted as a hexadecimal number.
// OBS! This method is _not_ strictly identical to the (*big.Int).SetString(..., 16) method.
// Notable differences:
// - This method _require_ "0x" or "0X" prefix.
// - This method does not accept zero-prefixed hex, e.g. "0x0001"
// - This method does not accept underscore input, e.g. "100_000",
// - This method does not accept negative zero as valid, e.g "-0x0",
//   - (this method does not accept any negative input as valid)
func (z *Uint) SetFromHex(hex string) error {
	return z.fromHex(hex)
}

// fromHex is the internal implementation of parsing a hex-string.
func (z *Uint) fromHex(hex string) error {
	if err := checkNumberS(hex); err != nil {
		return err
	}
	if len(hex) > 66 {
		return ErrBig256Range
	}
	z.Clear()
	end := len(hex)
	for i := 0; i < 4; i++ {
		start := end - 16
		if start < 2 {
			start = 2
		}
		for ri := start; ri < end; ri++ {
			nib := bintable[hex[ri]]
			if nib == badNibble {
				return ErrSyntax
			}
			z.arr[i] = z.arr[i] << 4
			z.arr[i] += uint64(nib)
		}
		end = start
	}
	return nil
}

// FromHex is a convenience-constructor to create an Uint from
// a hexadecimal string. The string is required to be '0x'-prefixed
// Numbers larger than 256 bits are not accepted.
func FromHex(hex string) (*Uint, error) {
	var z Uint
	if err := z.fromHex(hex); err != nil {
		return nil, err
	}
	return &z, nil
}

// MustFromHex is a convenience-constructor to create an Uint from
// a hexadecimal string.
// Returns a new Uint and panics if any error occurred.
func MustFromHex(hex string) *Uint {
	var z Uint
	if err := z.fromHex(hex); err != nil {
		panic(err)
	}
	return &z
}

// Clone creates a new Uint identical to z
func (z *Uint) Clone() *Uint {
	var x Uint
	x.arr[0] = z.arr[0]
	x.arr[1] = z.arr[1]
	x.arr[2] = z.arr[2]
	x.arr[3] = z.arr[3]

	return &x
}

uint256_test.gno

package uint256

import (
	"testing"
)

func TestSetAllOne(t *testing.T) {
	z := Zero()
	z.SetAllOne()
	if z.String() != twoPow256Sub1 {
		t.Errorf("Expected all ones, got %s", z.String())
	}
}

func TestByte(t *testing.T) {
	tests := []struct {
		input    string
		position uint64
		expected byte
	}{
		{"0x1000000000000000000000000000000000000000000000000000000000000000", 0, 16},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 0, 255},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 31, 255},
	}

	for i, tt := range tests {
		z, _ := FromHex(tt.input)
		n := NewUint(tt.position)
		result := z.Byte(n)

		if result.arr[0] != uint64(tt.expected) {
			t.Errorf("Test case %d failed. Input: %s, Position: %d, Expected: %d, Got: %d",
				i, tt.input, tt.position, tt.expected, result.arr[0])
		}

		// check other array elements are 0
		if result.arr[1] != 0 || result.arr[2] != 0 || result.arr[3] != 0 {
			t.Errorf("Test case %d failed. Non-zero values in upper bytes", i)
		}
	}

	// overflow
	z, _ := FromHex("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")
	n := NewUint(32)
	result := z.Byte(n)

	if !result.IsZero() {
		t.Errorf("Expected zero for position >= 32, got %v", result)
	}
}

func TestBitLen(t *testing.T) {
	tests := []struct {
		input    string
		expected int
	}{
		{"0x0", 0},
		{"0x1", 1},
		{"0xff", 8},
		{"0x100", 9},
		{"0xffff", 16},
		{"0x10000", 17},
		{"0xffffffffffffffff", 64},
		{"0x10000000000000000", 65},
		{"0xffffffffffffffffffffffffffffffff", 128},
		{"0x100000000000000000000000000000000", 129},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 256},
	}

	for i, tt := range tests {
		z, _ := FromHex(tt.input)
		result := z.BitLen()

		if result != tt.expected {
			t.Errorf("Test case %d failed. Input: %s, Expected: %d, Got: %d",
				i, tt.input, tt.expected, result)
		}
	}
}

func TestByteLen(t *testing.T) {
	tests := []struct {
		input    string
		expected int
	}{
		{"0x0", 0},
		{"0x1", 1},
		{"0xff", 1},
		{"0x100", 2},
		{"0xffff", 2},
		{"0x10000", 3},
		{"0xffffffffffffffff", 8},
		{"0x10000000000000000", 9},
		{"0xffffffffffffffffffffffffffffffff", 16},
		{"0x100000000000000000000000000000000", 17},
		{"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 32},
	}

	for i, tt := range tests {
		z, _ := FromHex(tt.input)
		result := z.ByteLen()

		if result != tt.expected {
			t.Errorf("Test case %d failed. Input: %s, Expected: %d, Got: %d",
				i, tt.input, tt.expected, result)
		}
	}
}

func TestClone(t *testing.T) {
	tests := []struct {
		input    string
		expected string
	}{
		{"0x1", "1"},
		{"0x100", "256"},
		{"0x10000000000000000", "18446744073709551616"},
	}

	for _, tt := range tests {
		z, _ := FromHex(tt.input)
		result := z.Clone()
		if result.String() != tt.expected {
			t.Errorf("Test %s failed. Expected %s, got %s", tt.input, tt.expected, result.String())
		}
	}
}

utils.gno

package uint256

func checkNumberS(input string) error {
	const fn = "UnmarshalText"
	l := len(input)
	if l == 0 {
		return errEmptyString(fn, input)
	}
	if l < 2 || input[0] != '0' ||
		(input[1] != 'x' && input[1] != 'X') {
		return errMissingPrefix(fn, input)
	}
	if l == 2 {
		return errEmptyNumber(fn, input)
	}
	if len(input) > 3 && input[2] == '0' {
		return errLeadingZero(fn, input)
	}
	return nil
}