Playground
arithmetic.gno
package int256
import (
"gno.land/p/onbloc/uint256/v0"
)
const divisionByZeroError = "division by zero"
// Add adds two int256 values and saves the result in z.
func (z *Int) Add(x, y *Int) *Int {
z.value.Add(&x.value, &y.value)
return z
}
// AddUint256 adds int256 and uint256 values and saves the result in z.
func (z *Int) AddUint256(x *Int, y *uint256.Uint) *Int {
z.value.Add(&x.value, y)
return z
}
// Sub subtracts two int256 values and saves the result in z.
func (z *Int) Sub(x, y *Int) *Int {
z.value.Sub(&x.value, &y.value)
return z
}
// SubUint256 subtracts uint256 and int256 values and saves the result in z.
func (z *Int) SubUint256(x *Int, y *uint256.Uint) *Int {
z.value.Sub(&x.value, y)
return z
}
// Mul multiplies two int256 values and saves the result in z.
//
// It considers the signs of the operands to determine the sign of the result.
func (z *Int) Mul(x, y *Int) *Int {
xAbs, xSign := x.Abs(), x.Sign()
yAbs, ySign := y.Abs(), y.Sign()
z.value.Mul(xAbs, yAbs)
if xSign != ySign {
z.value.Neg(&z.value)
}
return z
}
// Abs returns the absolute value of z.
func (z *Int) Abs() *uint256.Uint {
if z.Sign() >= 0 {
return &z.value
}
var absValue uint256.Uint
absValue.Sub(uint0, &z.value).Neg(&z.value)
return &absValue
}
// Div performs integer division z = x / y and returns z.
// If y == 0, it panics with a "division by zero" error.
//
// This function handles signed division using two's complement representation:
// 1. Determine the sign of the quotient based on the signs of x and y.
// 2. Perform unsigned division on the absolute values.
// 3. Adjust the result's sign if necessary.
//
// Example visualization for 8-bit integers (scaled down from 256-bit for simplicity):
//
// Let x = -6 (11111010 in two's complement) and y = 3 (00000011)
//
// Step 2: Determine signs
//
// x: negative (MSB is 1)
// y: positive (MSB is 0)
//
// Step 3: Calculate absolute values
//
// |x| = 6: 11111010 -> 00000110
// NOT: 00000101
// +1: 00000110
//
// |y| = 3: 00000011 (already positive)
//
// Step 4: Unsigned division
//
// 6 / 3 = 2: 00000010
//
// Step 5: Adjust sign (x and y have different signs)
//
// -2: 00000010 -> 11111110
// NOT: 11111101
// +1: 11111110
//
// Note: This implementation rounds towards zero, as is standard in Go.
func (z *Int) Div(x, y *Int) *Int {
// Step 1: Check for division by zero
if y.IsZero() {
panic(divisionByZeroError)
}
// Step 2, 3: Calculate the absolute values of x and y
xAbs, xSign := x.Abs(), x.Sign()
yAbs, ySign := y.Abs(), y.Sign()
// Step 4: Perform unsigned division on the absolute values
z.value.Div(xAbs, yAbs)
// Step 5: Adjust the sign of the result
// if x and y have different signs, the result must be negative
if xSign != ySign {
z.value.Neg(&z.value)
}
return z
}
// Example visualization for 8-bit integers (scaled down from 256-bit for simplicity):
//
// Let x = -7 (11111001 in two's complement) and y = 3 (00000011)
//
// Step 2: Determine signs
//
// x: negative (MSB is 1)
// y: positive (MSB is 0)
//
// Step 3: Calculate absolute values
//
// |x| = 7: 11111001 -> 00000111
// NOT: 00000110
// +1: 00000111
//
// |y| = 3: 00000011 (already positive)
//
// Step 4: Unsigned division
//
// 7 / 3 = 2: 00000010
//
// Step 5: Adjust sign (x and y have different signs)
//
// -2: 00000010 -> 11111110
// NOT: 11111101
// +1: 11111110
//
// Final result: -2 (11111110 in two's complement)
//
// Note: This implementation rounds towards zero, as is standard in Go.
func (z *Int) Quo(x, y *Int) *Int {
// Step 1: Check for division by zero
if y.IsZero() {
panic(divisionByZeroError)
}
// Step 2, 3: Calculate the absolute values of x and y
xAbs, xSign := x.Abs(), x.Sign()
yAbs, ySign := y.Abs(), y.Sign()
// perform unsigned division on the absolute values
z.value.Div(xAbs, yAbs)
// Step 5: Adjust the sign of the result
// if x and y have different signs, the result must be negative
if xSign != ySign {
z.value.Neg(&z.value)
}
return z
}
// Rem sets z to the remainder x%y for y != 0 and returns z.
//
// The function performs the following steps:
// 1. Check for division by zero
// 2. Determine the signs of x and y
// 3. Calculate the absolute values of x and y
// 4. Perform unsigned division and get the remainder
// 5. Adjust the sign of the remainder
//
// Example visualization for 8-bit integers (scaled down from 256-bit for simplicity):
//
// Let x = -7 (11111001 in two's complement) and y = 3 (00000011)
//
// Step 2: Determine signs
//
// x: negative (MSB is 1)
// y: positive (MSB is 0)
//
// Step 3: Calculate absolute values
//
// |x| = 7: 11111001 -> 00000111
// NOT: 00000110
// +1: 00000111
//
// |y| = 3: 00000011 (already positive)
//
// Step 4: Unsigned division
//
// 7 / 3 = 2 remainder 1
// q = 2: 00000010 (not used in result)
// r = 1: 00000001
//
// Step 5: Adjust sign of remainder (x is negative)
//
// -1: 00000001 -> 11111111
// NOT: 11111110
// +1: 11111111
//
// Final result: -1 (11111111 in two's complement)
//
// Note: The sign of the remainder is always the same as the sign of the dividend (x).
func (z *Int) Rem(x, y *Int) *Int {
// Step 1: Check for division by zero
if y.IsZero() {
panic(divisionByZeroError)
}
// Step 2, 3
xAbs, xSign := x.Abs(), x.Sign()
yAbs := y.Abs()
// Step 4: Perform unsigned division and get the remainder
var q, r uint256.Uint
q.DivMod(xAbs, yAbs, &r)
// Step 5: Adjust the sign of the remainder
if xSign < 0 {
r.Neg(&r)
}
z.value.Set(&r)
return z
}
// Mod sets z to the modulus x%y for y != 0 and returns z.
// The result (z) has the same sign as the divisor y.
func (z *Int) Mod(x, y *Int) *Int {
return z.ModE(x, y)
}
// DivE performs Euclidean division of x by y, setting z to the quotient and returning z.
// If y == 0, it panics with a "division by zero" error.
//
// Euclidean division satisfies the following properties:
// 1. The remainder is always non-negative: 0 <= x mod y < |y|
// 2. It follows the identity: x = y * (x div y) + (x mod y)
func (z *Int) DivE(x, y *Int) *Int {
if y.IsZero() {
panic(divisionByZeroError)
}
// Compute the truncated division quotient
z.Quo(x, y)
// Compute the remainder
r := new(Int).Rem(x, y)
// If the remainder is negative, adjust the quotient
if r.Sign() < 0 {
if y.Sign() > 0 {
z.Sub(z, NewInt(1))
} else {
z.Add(z, NewInt(1))
}
}
return z
}
// ModE computes the Euclidean modulus of x by y, setting z to the result and returning z.
// If y == 0, it panics with a "division by zero" error.
//
// The Euclidean modulus is always non-negative and satisfies:
//
// 0 <= x mod y < |y|
//
// Example visualization for 8-bit integers (scaled down from 256-bit for simplicity):
//
// Case 1: Let x = -7 (11111001 in two's complement) and y = 3 (00000011)
//
// Step 1: Compute remainder (using Rem)
//
// Result of Rem: -1 (11111111 in two's complement)
//
// Step 2: Adjust sign (result is negative, y is positive)
//
// -1 + 3 = 2
// 11111111 + 00000011 = 00000010
//
// Final result: 2 (00000010)
//
// Case 2: Let x = -7 (11111001 in two's complement) and y = -3 (11111101 in two's complement)
//
// Step 1: Compute remainder (using Rem)
//
// Result of Rem: -1 (11111111 in two's complement)
//
// Step 2: Adjust sign (result is negative, y is negative)
//
// No adjustment needed
//
// Final result: -1 (11111111 in two's complement)
//
// Note: This implementation ensures that the result always has the same sign as y,
// which is different from the Rem operation.
func (z *Int) ModE(x, y *Int) *Int {
if y.IsZero() {
panic(divisionByZeroError)
}
// Perform T-division to get the remainder
z.Rem(x, y)
// Adjust the remainder if necessary
if z.Sign() >= 0 {
return z
}
if y.Sign() > 0 {
return z.Add(z, y)
}
return z.Sub(z, y)
}
// Sets z to the sum x + y, where z and x are uint256s and y is an int256.
//
// If the y is positive, it adds y.value to x. otherwise, it subtracts y.Abs() from x.
func AddDelta(z, x *uint256.Uint, y *Int) {
if y.Sign() >= 0 {
z.Add(x, &y.value)
} else {
z.Sub(x, y.Abs())
}
}
// Sets z to the sum x + y, where z and x are uint256s and y is an int256.
//
// This function returns true if the addition overflows, false otherwise.
func AddDeltaOverflow(z, x *uint256.Uint, y *Int) bool {
var overflow bool
if y.Sign() >= 0 {
_, overflow = z.AddOverflow(x, &y.value)
} else {
var absY uint256.Uint
absY.Sub(uint0, &y.value) // absY = -y.value
_, overflow = z.SubOverflow(x, &absY)
}
return overflow
}
arithmetic_test.gno
package int256
import (
"testing"
"gno.land/p/onbloc/uint256/v0"
)
const (
// 2^255 - 1
MAX_INT256 = "57896044618658097711785492504343953926634992332820282019728792003956564819967"
// -(2^255 - 1)
MINUS_MAX_INT256 = "-57896044618658097711785492504343953926634992332820282019728792003956564819967"
// 2^255 - 1
MAX_UINT256 = "115792089237316195423570985008687907853269984665640564039457584007913129639935"
MAX_UINT256_MINUS_1 = "115792089237316195423570985008687907853269984665640564039457584007913129639934"
MINUS_MAX_UINT256 = "-115792089237316195423570985008687907853269984665640564039457584007913129639935"
MINUS_MAX_UINT256_PLUS_1 = "-115792089237316195423570985008687907853269984665640564039457584007913129639934"
TWO_POW_128 = "340282366920938463463374607431768211456"
MINUS_TWO_POW_128 = "-340282366920938463463374607431768211456"
MINUS_TWO_POW_128_MINUS_1 = "-340282366920938463463374607431768211457"
TWO_POW_128_MINUS_1 = "340282366920938463463374607431768211455"
TWO_POW_129_MINUS_1 = "680564733841876926926749214863536422911"
TWO_POW_254 = "28948022309329048855892746252171976963317496166410141009864396001978282409984"
MINUS_TWO_POW_254 = "-28948022309329048855892746252171976963317496166410141009864396001978282409984"
HALF_MAX_INT256 = "28948022309329048855892746252171976963317496166410141009864396001978282409983"
MINUS_HALF_MAX_INT256 = "-28948022309329048855892746252171976963317496166410141009864396001978282409983"
TWO_POW_255 = "57896044618658097711785492504343953926634992332820282019728792003956564819968"
MIN_INT256 = "-57896044618658097711785492504343953926634992332820282019728792003956564819968"
MIN_INT256_MINUS_1 = "-57896044618658097711785492504343953926634992332820282019728792003956564819969"
)
func TestAdd(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"0", "1", "1"},
{"1", "0", "1"},
{"1", "1", "2"},
{"1", "2", "3"},
// NEGATIVE
{"-1", "1", "0"},
{"1", "-1", "0"},
{"3", "-3", "0"},
{"-1", "-1", "-2"},
{"-1", "-2", "-3"},
{"-1", "3", "2"},
{"3", "-1", "2"},
// OVERFLOW
{MAX_UINT256, "1", "0"},
{MAX_INT256, "1", MIN_INT256},
{MIN_INT256, "-1", MAX_INT256},
{MAX_INT256, MAX_INT256, "-2"},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
want, err := FromDecimal(tc.want)
if err != nil {
t.Error(err)
continue
}
got := New()
got.Add(x, y)
if got.Neq(want) {
t.Errorf("Add(%s, %s) = %v, want %v", tc.x, tc.y, got.String(), want.String())
}
}
}
func TestAddUint256(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"0", "1", "1"},
{"1", "0", "1"},
{"1", "1", "2"},
{"1", "2", "3"},
{"-1", "1", "0"},
{"-1", "3", "2"},
{MINUS_MAX_UINT256_PLUS_1, MAX_UINT256, "1"},
{MINUS_MAX_UINT256, MAX_UINT256_MINUS_1, "-1"},
// OVERFLOW
{MINUS_MAX_UINT256, MAX_UINT256, "0"},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := uint256.FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
want, err := FromDecimal(tc.want)
if err != nil {
t.Error(err)
continue
}
got := New()
got.AddUint256(x, y)
if got.Neq(want) {
t.Errorf("AddUint256(%s, %s) = %v, want %v", tc.x, tc.y, got.String(), want.String())
}
}
}
func TestAddDelta(t *testing.T) {
tests := []struct {
z, x, y, want string
}{
{"0", "0", "0", "0"},
{"0", "0", "1", "1"},
{"0", "1", "0", "1"},
{"0", "1", "1", "2"},
{"1", "2", "3", "5"},
{"5", "10", "-3", "7"},
// underflow
{"1", "2", "-3", MAX_UINT256},
}
for _, tc := range tests {
z, err := uint256.FromDecimal(tc.z)
if err != nil {
t.Error(err)
continue
}
x, err := uint256.FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
want, err := uint256.FromDecimal(tc.want)
if err != nil {
t.Error(err)
continue
}
AddDelta(z, x, y)
if z.Neq(want) {
t.Errorf("AddDelta(%s, %s, %s) = %v, want %v", tc.z, tc.x, tc.y, z.String(), want.String())
}
}
}
func TestAddDeltaOverflow(t *testing.T) {
tests := []struct {
z, x, y string
want bool
}{
{"0", "0", "0", false},
// underflow
{"1", "2", "-3", true},
}
for _, tc := range tests {
z, err := uint256.FromDecimal(tc.z)
if err != nil {
t.Error(err)
continue
}
x, err := uint256.FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
result := AddDeltaOverflow(z, x, y)
if result != tc.want {
t.Errorf("AddDeltaOverflow(%s, %s, %s) = %v, want %v", tc.z, tc.x, tc.y, result, tc.want)
}
}
}
func TestSub(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"1", "0", "1"},
{"1", "1", "0"},
{"-1", "1", "-2"},
{"1", "-1", "2"},
{"-1", "-1", "0"},
{MINUS_MAX_UINT256, MINUS_MAX_UINT256, "0"},
{MINUS_MAX_UINT256, "0", MINUS_MAX_UINT256},
{MAX_INT256, MIN_INT256, "-1"},
{MIN_INT256, MIN_INT256, "0"},
{MAX_INT256, MAX_INT256, "0"},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
want, err := FromDecimal(tc.want)
if err != nil {
t.Error(err)
continue
}
got := New()
got.Sub(x, y)
if got.Neq(want) {
t.Errorf("Sub(%s, %s) = %v, want %v", tc.x, tc.y, got.String(), want.String())
}
}
}
func TestSubUint256(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"0", "1", "-1"},
{"1", "0", "1"},
{"1", "1", "0"},
{"1", "2", "-1"},
{"-1", "1", "-2"},
{"-1", "3", "-4"},
// underflow
{MINUS_MAX_UINT256, "1", "0"},
{MINUS_MAX_UINT256, "2", "-1"},
{MINUS_MAX_UINT256, "3", "-2"},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := uint256.FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
want, err := FromDecimal(tc.want)
if err != nil {
t.Error(err)
continue
}
got := New()
got.SubUint256(x, y)
if got.Neq(want) {
t.Errorf("SubUint256(%s, %s) = %v, want %v", tc.x, tc.y, got.String(), want.String())
}
}
}
func TestMul(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"5", "3", "15"},
{"-5", "3", "-15"},
{"5", "-3", "-15"},
{"0", "3", "0"},
{"3", "0", "0"},
{"-5", "-3", "15"},
{MAX_UINT256, "1", MAX_UINT256},
{MAX_INT256, "2", "-2"},
{TWO_POW_254, "2", MIN_INT256},
{MINUS_TWO_POW_254, "2", MIN_INT256},
{MAX_INT256, "1", MAX_INT256},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
want, err := FromDecimal(tc.want)
if err != nil {
t.Error(err)
continue
}
got := New()
got.Mul(x, y)
if got.Neq(want) {
t.Errorf("Mul(%s, %s) = %v, want %v", tc.x, tc.y, got.String(), want.String())
}
}
}
func TestDiv(t *testing.T) {
tests := []struct {
x, y, expected string
}{
{"1", "1", "1"},
{"0", "1", "0"},
{"-1", "1", "-1"},
{"1", "-1", "-1"},
{"-1", "-1", "1"},
{"-6", "3", "-2"},
{"10", "-2", "-5"},
{"-10", "3", "-3"},
{"7", "3", "2"},
{"-7", "3", "-2"},
// the maximum value of a positive number in int256 is less than the maximum value of a uint256
{MAX_INT256, "2", HALF_MAX_INT256},
{MINUS_MAX_INT256, "2", MINUS_HALF_MAX_INT256},
{MAX_INT256, "-1", MINUS_MAX_INT256},
}
for _, tt := range tests {
t.Run(tt.x+"/"+tt.y, func(t *testing.T) {
x := MustFromDecimal(tt.x)
y := MustFromDecimal(tt.y)
result := Zero().Div(x, y)
if result.String() != tt.expected {
t.Errorf("Div(%s, %s) = %s, want %s", tt.x, tt.y, result.String(), tt.expected)
}
})
}
t.Run("Division by zero", func(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("Div(1, 0) did not panic")
}
}()
x := MustFromDecimal("1")
y := MustFromDecimal("0")
Zero().Div(x, y)
})
}
func TestQuo(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"0", "1", "0"},
{"0", "-1", "0"},
{"10", "1", "10"},
{"10", "-1", "-10"},
{"-10", "1", "-10"},
{"-10", "-1", "10"},
{"10", "-3", "-3"},
{"-10", "3", "-3"},
{"10", "3", "3"},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
want, err := FromDecimal(tc.want)
if err != nil {
t.Error(err)
continue
}
got := New()
got.Quo(x, y)
if got.Neq(want) {
t.Errorf("Quo(%s, %s) = %v, want %v", tc.x, tc.y, got.String(), want.String())
}
}
}
func TestRem(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"0", "1", "0"},
{"0", "-1", "0"},
{"10", "1", "0"},
{"10", "-1", "0"},
{"-10", "1", "0"},
{"-10", "-1", "0"},
{"10", "3", "1"},
{"10", "-3", "1"},
{"-10", "3", "-1"},
{"-10", "-3", "-1"},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
want, err := FromDecimal(tc.want)
if err != nil {
t.Error(err)
continue
}
got := New()
got.Rem(x, y)
if got.Neq(want) {
t.Errorf("Rem(%s, %s) = %v, want %v", tc.x, tc.y, got.String(), want.String())
}
}
}
func TestMod(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"0", "1", "0"},
{"0", "-1", "0"},
{"10", "1", "0"},
{"10", "-1", "0"},
{"-10", "1", "0"},
{"-10", "-1", "0"},
{"10", "3", "1"},
{"10", "-3", "1"},
{"-10", "3", "2"},
{"-10", "-3", "2"},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
want, err := FromDecimal(tc.want)
if err != nil {
t.Error(err)
continue
}
got := New()
got.Mod(x, y)
if got.Neq(want) {
t.Errorf("Mod(%s, %s) = %v, want %v", tc.x, tc.y, got.String(), want.String())
}
}
}
func TestModeOverflow(t *testing.T) {
tests := []struct {
x, y, want string
}{
{MIN_INT256, "2", "0"}, // MIN_INT256 % 2 = 0
{MAX_INT256, "2", "1"}, // MAX_INT256 % 2 = 1
{MIN_INT256, "-1", "0"}, // MIN_INT256 % -1 = 0
{MAX_INT256, "-1", "0"}, // MAX_INT256 % -1 = 0
}
for _, tt := range tests {
x := MustFromDecimal(tt.x)
y := MustFromDecimal(tt.y)
want := MustFromDecimal(tt.want)
got := New().Mod(x, y)
if got.Neq(want) {
t.Errorf("Mod(%s, %s) = %v, want %v", tt.x, tt.y, got.String(), want.String())
}
}
}
func TestModPanic(t *testing.T) {
tests := []struct {
x, y string
}{
{"10", "0"},
{"10", "-0"},
{"-10", "0"},
{"-10", "-0"},
}
for _, tc := range tests {
defer func() {
if r := recover(); r == nil {
t.Errorf("Mod(%s, %s) did not panic", tc.x, tc.y)
}
}()
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
result := New().Mod(x, y)
t.Errorf("Mod(%s, %s) = %v, want %v", tc.x, tc.y, result.String(), "0")
}
}
func TestDivE(t *testing.T) {
testCases := []struct {
x, y int64
want int64
}{
{8, 3, 2},
{8, -3, -2},
{-8, 3, -3},
{-8, -3, 3},
{1, 2, 0},
{1, -2, 0},
{-1, 2, -1},
{-1, -2, 1},
{0, 1, 0},
{0, -1, 0},
}
for _, tc := range testCases {
x := NewInt(tc.x)
y := NewInt(tc.y)
want := NewInt(tc.want)
got := new(Int).DivE(x, y)
if got.Cmp(want) != 0 {
t.Errorf("DivE(%v, %v) = %v, want %v", tc.x, tc.y, got, want)
}
}
}
func TestDivEByZero(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("DivE did not panic on division by zero")
}
}()
x := NewInt(1)
y := NewInt(0)
new(Int).DivE(x, y)
}
func TestModEByZero(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("ModE did not panic on division by zero")
}
}()
x := NewInt(1)
y := NewInt(0)
new(Int).ModE(x, y)
}
func TestLargeNumbers(t *testing.T) {
x, _ := new(Int).SetString("123456789012345678901234567890")
y, _ := new(Int).SetString("987654321098765432109876543210")
// Expected results (calculated separately)
expectedQ, _ := new(Int).SetString("0")
expectedR, _ := new(Int).SetString("123456789012345678901234567890")
gotQ := new(Int).DivE(x, y)
gotR := new(Int).ModE(x, y)
if gotQ.Cmp(expectedQ) != 0 {
t.Errorf("DivE with large numbers: got %v, want %v", gotQ, expectedQ)
}
if gotR.Cmp(expectedR) != 0 {
t.Errorf("ModE with large numbers: got %v, want %v", gotR, expectedR)
}
}
func TestAbs(t *testing.T) {
tests := []struct {
x, want string
}{
{"0", "0"},
{"1", "1"},
{"-1", "1"},
{"-2", "2"},
{"-100000000000", "100000000000"},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
got := x.Abs()
if got.String() != tc.want {
t.Errorf("Abs(%s) = %v, want %v", tc.x, got.String(), tc.want)
}
}
}
bitwise.gno
package int256
// Not sets z to the bitwise NOT of x and returns z.
//
// The bitwise NOT operation flips each bit of the operand.
func (z *Int) Not(x *Int) *Int {
z.value.Not(&x.value)
return z
}
// And sets z to the bitwise AND of x and y and returns z.
//
// The bitwise AND operation results in a value that has a bit set
// only if both corresponding bits of the operands are set.
func (z *Int) And(x, y *Int) *Int {
z.value.And(&x.value, &y.value)
return z
}
// Or sets z to the bitwise OR of x and y and returns z.
//
// The bitwise OR operation results in a value that has a bit set
// if at least one of the corresponding bits of the operands is set.
func (z *Int) Or(x, y *Int) *Int {
z.value.Or(&x.value, &y.value)
return z
}
// Xor sets z to the bitwise XOR of x and y and returns z.
//
// The bitwise XOR operation results in a value that has a bit set
// only if the corresponding bits of the operands are different.
func (z *Int) Xor(x, y *Int) *Int {
z.value.Xor(&x.value, &y.value)
return z
}
// Rsh sets z to the result of right-shifting x by n bits and returns z.
//
// Right shift operation moves all bits in the operand to the right by the specified number of positions.
// Bits shifted out on the right are discarded, and zeros are shifted in on the left.
func (z *Int) Rsh(x *Int, n uint) *Int {
z.value.Rsh(&x.value, n)
return z
}
// Lsh sets z to the result of left-shifting x by n bits and returns z.
//
// Left shift operation moves all bits in the operand to the left by the specified number of positions.
// Bits shifted out on the left are discarded, and zeros are shifted in on the right.
func (z *Int) Lsh(x *Int, n uint) *Int {
z.value.Lsh(&x.value, n)
return z
}
bitwise_test.gno
package int256
import (
"testing"
)
func TestBitwise_And(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"5", "1", "1"}, // 0101 & 0001 = 0001
{"-1", "1", "1"}, // 1111 & 0001 = 0001
{"-5", "3", "3"}, // 1111...1011 & 0000...0011 = 0000...0011
{MAX_UINT256, MAX_UINT256, MAX_UINT256},
{TWO_POW_128, TWO_POW_128_MINUS_1, "0"}, // 2^128 & (2^128 - 1) = 0
{TWO_POW_128, MAX_UINT256, TWO_POW_128}, // 2^128 & MAX_INT256
{MAX_UINT256, TWO_POW_128, TWO_POW_128}, // MAX_INT256 & 2^128
}
for _, tc := range tests {
x, _ := FromDecimal(tc.x)
y, _ := FromDecimal(tc.y)
want, _ := FromDecimal(tc.want)
got := new(Int).And(x, y)
if got.Neq(want) {
t.Errorf("And(%s, %s) = %s, want %s", x.String(), y.String(), got.String(), want.String())
}
}
}
func TestBitwise_Or(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"5", "1", "5"}, // 0101 | 0001 = 0101
{"-1", "1", "-1"}, // 1111 | 0001 = 1111
{"-5", "3", "-5"}, // 1111...1011 | 0000...0011 = 1111...1011
{TWO_POW_128, TWO_POW_128_MINUS_1, TWO_POW_129_MINUS_1},
{TWO_POW_128, MAX_UINT256, MAX_UINT256},
{"0", TWO_POW_128, TWO_POW_128}, // 0 | 2^128 = 2^128
{MAX_UINT256, TWO_POW_128, MAX_UINT256}, // MAX_INT256 | 2^128 = MAX_INT256
}
for _, tc := range tests {
x, _ := FromDecimal(tc.x)
y, _ := FromDecimal(tc.y)
want, _ := FromDecimal(tc.want)
got := new(Int).Or(x, y)
if got.Neq(want) {
t.Errorf(
"Or(%s, %s) = %s, want %s",
x.String(), y.String(), got.String(), want.String(),
)
}
}
}
func TestBitwise_Not(t *testing.T) {
tests := []struct {
x, want string
}{
{"5", "-6"}, // 0101 -> 1111...1010
{"-1", "0"}, // 1111...1111 -> 0000...0000
{TWO_POW_128, MINUS_TWO_POW_128_MINUS_1}, // NOT 2^128
{TWO_POW_255, MIN_INT256_MINUS_1}, // NOT 2^255
}
for _, tc := range tests {
x, _ := FromDecimal(tc.x)
want, _ := FromDecimal(tc.want)
got := new(Int).Not(x)
if got.Neq(want) {
t.Errorf("Not(%s) = %s, want %s", x.String(), got.String(), want.String())
}
}
}
func TestBitwise_Xor(t *testing.T) {
tests := []struct {
x, y, want string
}{
{"5", "1", "4"}, // 0101 ^ 0001 = 0100
{"-1", "1", "-2"}, // 1111...1111 ^ 0000...0001 = 1111...1110
{"-5", "3", "-8"}, // 1111...1011 ^ 0000...0011 = 1111...1000
{TWO_POW_128, TWO_POW_128, "0"}, // 2^128 ^ 2^128 = 0
{MAX_UINT256, TWO_POW_128, MINUS_TWO_POW_128_MINUS_1}, // MAX_INT256 ^ 2^128
{TWO_POW_255, MAX_UINT256, MIN_INT256_MINUS_1}, // 2^255 ^ MAX_INT256
}
for _, tt := range tests {
x, _ := FromDecimal(tt.x)
y, _ := FromDecimal(tt.y)
want, _ := FromDecimal(tt.want)
got := new(Int).Xor(x, y)
if got.Neq(want) {
t.Errorf("Xor(%s, %s) = %s, want %s", x.String(), y.String(), got.String(), want.String())
}
}
}
func TestBitwise_Rsh(t *testing.T) {
tests := []struct {
x string
n uint
want string
}{
{"5", 1, "2"}, // 0101 >> 1 = 0010
{"42", 3, "5"}, // 00101010 >> 3 = 00000101
{TWO_POW_128, 128, "1"},
{MAX_UINT256, 255, "1"},
{TWO_POW_255, 254, "2"},
{MINUS_TWO_POW_128, 128, TWO_POW_128_MINUS_1},
}
for _, tt := range tests {
x, _ := FromDecimal(tt.x)
want, _ := FromDecimal(tt.want)
got := new(Int).Rsh(x, tt.n)
if got.Neq(want) {
t.Errorf("Rsh(%s, %d) = %s, want %s", x.String(), tt.n, got.String(), want.String())
}
}
}
func TestBitwise_Lsh(t *testing.T) {
tests := []struct {
x string
n uint
want string
}{
{"5", 2, "20"}, // 0101 << 2 = 10100
{"42", 5, "1344"}, // 00101010 << 5 = 10101000000
{"1", 128, TWO_POW_128}, // 1 << 128 = 2^128
{"2", 254, TWO_POW_255},
{"1", 255, MIN_INT256}, // 1 << 255 = MIN_INT256 (overflow)
}
for _, tt := range tests {
x, _ := FromDecimal(tt.x)
want, _ := FromDecimal(tt.want)
got := new(Int).Lsh(x, tt.n)
if got.Neq(want) {
t.Errorf("Lsh(%s, %d) = %s, want %s", x.String(), tt.n, got.String(), want.String())
}
}
}
cmp.gno
package int256
func (z *Int) Eq(x *Int) bool {
return z.value.Eq(&x.value)
}
func (z *Int) Neq(x *Int) bool {
return !z.Eq(x)
}
// Cmp compares z and x and returns:
//
// - 1 if z > x
// - 0 if z == x
// - -1 if z < x
func (z *Int) Cmp(x *Int) int {
zSign, xSign := z.Sign(), x.Sign()
if zSign == xSign {
return z.value.Cmp(&x.value)
}
if zSign == 0 {
return -xSign
}
return zSign
}
// IsZero returns true if z == 0
func (z *Int) IsZero() bool {
return z.value.IsZero()
}
// IsNeg returns true if z < 0
func (z *Int) IsNeg() bool {
return z.Sign() < 0
}
func (z *Int) Lt(x *Int) bool {
return z.Cmp(x) < 0
}
func (z *Int) Gt(x *Int) bool {
return z.Cmp(x) > 0
}
func (z *Int) Le(x *Int) bool {
return z.Cmp(x) <= 0
}
func (z *Int) Ge(x *Int) bool {
return z.Cmp(x) >= 0
}
// Clone creates a new Int identical to z
func (z *Int) Clone() *Int {
return New().FromUint256(&z.value)
}
cmp_test.gno
package int256
import "testing"
func TestEq(t *testing.T) {
tests := []struct {
x, y string
want bool
}{
{"0", "0", true},
{"0", "1", false},
{"1", "0", false},
{"-1", "0", false},
{"0", "-1", false},
{"1", "1", true},
{"-1", "-1", true},
{"115792089237316195423570985008687907853269984665640564039457584007913129639935", "-115792089237316195423570985008687907853269984665640564039457584007913129639935", false},
{"-115792089237316195423570985008687907853269984665640564039457584007913129639935", "-115792089237316195423570985008687907853269984665640564039457584007913129639935", true},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
got := x.Eq(y)
if got != tc.want {
t.Errorf("Eq(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want)
}
}
}
func TestNeq(t *testing.T) {
tests := []struct {
x, y string
want bool
}{
{"0", "0", false},
{"0", "1", true},
{"1", "0", true},
{"-1", "0", true},
{"0", "-1", true},
{"1", "1", false},
{"-1", "-1", false},
{"115792089237316195423570985008687907853269984665640564039457584007913129639935", "-115792089237316195423570985008687907853269984665640564039457584007913129639935", true},
{"-115792089237316195423570985008687907853269984665640564039457584007913129639935", "-115792089237316195423570985008687907853269984665640564039457584007913129639935", false},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
got := x.Neq(y)
if got != tc.want {
t.Errorf("Neq(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want)
}
}
}
func TestCmp(t *testing.T) {
tests := []struct {
x, y string
want int
}{
{"0", "0", 0},
{"0", "1", -1},
{"1", "0", 1},
{"-1", "0", -1},
{"0", "-1", 1},
{"1", "1", 0},
{"115792089237316195423570985008687907853269984665640564039457584007913129639935", "-115792089237316195423570985008687907853269984665640564039457584007913129639935", -1},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
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},
{"-0", true},
{"1", false},
{"-1", false},
{"10", false},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
got := x.IsZero()
if got != tc.want {
t.Errorf("IsZero(%s) = %v, want %v", tc.x, got, tc.want)
}
}
}
func TestIsNeg(t *testing.T) {
tests := []struct {
x string
want bool
}{
{"0", false},
{"-0", false},
{"1", false},
{"-1", true},
{"10", false},
{"-10", true},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
got := x.IsNeg()
if got != tc.want {
t.Errorf("IsNeg(%s) = %v, want %v", tc.x, got, tc.want)
}
}
}
func TestLt(t *testing.T) {
tests := []struct {
x, y string
want bool
}{
{"0", "0", false},
{"0", "1", true},
{"1", "0", false},
{"-1", "0", true},
{"0", "-1", false},
{"1", "1", false},
{"-1", "-1", false},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
got := x.Lt(y)
if got != tc.want {
t.Errorf("Lt(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want)
}
}
}
func TestGt(t *testing.T) {
tests := []struct {
x, y string
want bool
}{
{"0", "0", false},
{"0", "1", false},
{"1", "0", true},
{"-1", "0", false},
{"0", "-1", true},
{"1", "1", false},
{"-1", "-1", false},
}
for _, tc := range tests {
x, err := FromDecimal(tc.x)
if err != nil {
t.Error(err)
continue
}
y, err := FromDecimal(tc.y)
if err != nil {
t.Error(err)
continue
}
got := x.Gt(y)
if got != tc.want {
t.Errorf("Gt(%s, %s) = %v, want %v", tc.x, tc.y, got, tc.want)
}
}
}
func TestClone(t *testing.T) {
tests := []string{
"0",
"-0",
"1",
"-1",
"10",
"-10",
"115792089237316195423570985008687907853269984665640564039457584007913129639935",
"-115792089237316195423570985008687907853269984665640564039457584007913129639935",
}
for _, xStr := range tests {
x, err := FromDecimal(xStr)
if err != nil {
t.Error(err)
continue
}
y := x.Clone()
if x.Neq(y) {
t.Errorf("cloned value is not equal to original value")
}
}
}
conversion.gno
package int256
import (
"math"
"gno.land/p/onbloc/uint256/v0"
)
// SetInt64 sets the Int to the value of the provided int64.
//
// This method allows for easy conversion from standard Go integer types
// to Int, correctly handling both positive and negative values.
func (z *Int) SetInt64(v int64) *Int {
if v >= 0 {
z.value.SetUint64(uint64(v))
} else {
z.value.SetUint64(uint64(-v)).Neg(&z.value)
}
return z
}
// SetUint64 sets the Int to the value of the provided uint64.
func (z *Int) SetUint64(v uint64) *Int {
z.value.SetUint64(v)
return z
}
// Uint64 returns the lower 64-bits of z
func (z *Int) Uint64() uint64 {
if z.Sign() < 0 {
panic("cannot convert negative int256 to uint64")
}
if z.value.Gt(uint256.NewUint(0).SetUint64(math.MaxUint64)) {
panic("overflow: int256 does not fit in uint64 type")
}
return z.value.Uint64()
}
// Int64 returns the lower 64-bits of z
func (z *Int) Int64() int64 {
if z.Sign() >= 0 {
if z.value.BitLen() > 64 {
panic("overflow: int256 does not fit in int64 type")
}
return int64(z.value.Uint64())
}
var temp uint256.Uint
temp.Sub(uint256.NewUint(0), &z.value) // temp = -z.value
if temp.BitLen() > 64 {
panic("overflow: int256 does not fit in int64 type")
}
return -int64(temp.Uint64())
}
// Neg sets z to -x and returns z.)
func (z *Int) Neg(x *Int) *Int {
if x.IsZero() {
z.value.Clear()
} else {
z.value.Neg(&x.value)
}
return z
}
// Set sets z to x and returns z.
func (z *Int) Set(x *Int) *Int {
z.value.Set(&x.value)
return z
}
// SetFromUint256 converts a uint256.Uint to Int and sets the value to z.
func (z *Int) SetUint256(x *uint256.Uint) *Int {
z.value.Set(x)
return z
}
// ToString returns a string representation of z in base 10.
// The string is prefixed with a minus sign if z is negative.
func (z *Int) String() string {
if z.value.IsZero() {
return "0"
}
sign := z.Sign()
var temp uint256.Uint
if sign >= 0 {
temp.Set(&z.value)
} else {
// temp = -z.value
temp.Sub(uint256.NewUint(0), &z.value)
}
s := temp.Dec()
if sign < 0 {
return "-" + s
}
return s
}
// NilToZero returns the Int if it's not nil, or a new zero-valued Int otherwise.
//
// This method is useful for safely handling potentially nil Int pointers,
// ensuring that operations always have a valid Int to work with.
func (z *Int) NilToZero() *Int {
if z == nil {
return Zero()
}
return z
}
conversion_test.gno
package int256
import (
"testing"
"gno.land/p/onbloc/uint256/v0"
)
func TestSetInt64(t *testing.T) {
tests := []struct {
v int64
expect int
}{
{0, 0},
{1, 1},
{-1, -1},
{9223372036854775807, 1}, // overflow (max int64)
{-9223372036854775808, -1}, // underflow (min int64)
}
for _, tt := range tests {
z := New().SetInt64(tt.v)
if z.Sign() != tt.expect {
t.Errorf("SetInt64(%d) = %d, want %d", tt.v, z.Sign(), tt.expect)
}
}
}
func TestUint64(t *testing.T) {
tests := []struct {
x string
want uint64
}{
{"0", 0},
{"1", 1},
{"9223372036854775807", 9223372036854775807},
{"9223372036854775808", 9223372036854775808},
{"18446744073709551615", 18446744073709551615},
}
for _, tt := range tests {
z := MustFromDecimal(tt.x)
got := z.Uint64()
if got != tt.want {
t.Errorf("Uint64(%s) = %d, want %d", tt.x, got, tt.want)
}
}
}
func TestUint64_Panic(t *testing.T) {
tests := []struct {
x string
}{
{"-1"},
{"18446744073709551616"},
{"18446744073709551617"},
}
for _, tt := range tests {
defer func() {
if r := recover(); r == nil {
t.Errorf("Uint64(%s) did not panic", tt.x)
}
}()
z := MustFromDecimal(tt.x)
z.Uint64()
}
}
func TestInt64(t *testing.T) {
tests := []struct {
x string
want int64
}{
{"0", 0},
{"1", 1},
{"9223372036854775807", 9223372036854775807},
{"-1", -1},
{"-9223372036854775808", -9223372036854775808},
}
for _, tt := range tests {
z := MustFromDecimal(tt.x)
got := z.Int64()
if got != tt.want {
t.Errorf("Uint64(%s) = %d, want %d", tt.x, got, tt.want)
}
}
}
func TestInt64_Panic(t *testing.T) {
tests := []struct {
x string
}{
{"18446744073709551616"},
{"18446744073709551617"},
}
for _, tt := range tests {
defer func() {
if r := recover(); r == nil {
t.Errorf("Int64(%s) did not panic", tt.x)
}
}()
z := MustFromDecimal(tt.x)
z.Int64()
}
}
func TestNeg(t *testing.T) {
tests := []struct {
x string
want string
}{
{"0", "0"},
{"1", "-1"},
{"-1", "1"},
{"9223372036854775807", "-9223372036854775807"},
{"-18446744073709551615", "18446744073709551615"},
}
for _, tt := range tests {
z := MustFromDecimal(tt.x)
z.Neg(z)
got := z.String()
if got != tt.want {
t.Errorf("Neg(%s) = %s, want %s", tt.x, got, tt.want)
}
}
}
func TestSet(t *testing.T) {
tests := []struct {
x string
want string
}{
{"0", "0"},
{"1", "1"},
{"-1", "-1"},
{"9223372036854775807", "9223372036854775807"},
{"-18446744073709551615", "-18446744073709551615"},
}
for _, tt := range tests {
z := MustFromDecimal(tt.x)
z.Set(z)
got := z.String()
if got != tt.want {
t.Errorf("Set(%s) = %s, want %s", tt.x, got, tt.want)
}
}
}
func TestSetUint256(t *testing.T) {
tests := []struct {
x string
want string
}{
{"0", "0"},
{"1", "1"},
{"9223372036854775807", "9223372036854775807"},
{"18446744073709551615", "18446744073709551615"},
}
for _, tt := range tests {
got := New()
z := uint256.MustFromDecimal(tt.x)
got.SetUint256(z)
if got.String() != tt.want {
t.Errorf("SetUint256(%s) = %s, want %s", tt.x, got.String(), tt.want)
}
}
}
func TestString(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"0", "0"},
{"1", "1"},
{"-1", "-1"},
{"123456789", "123456789"},
{"-123456789", "-123456789"},
{"18446744073709551615", "18446744073709551615"}, // max uint64
{"-18446744073709551615", "-18446744073709551615"},
{TWO_POW_128_MINUS_1, TWO_POW_128_MINUS_1},
{MINUS_TWO_POW_128, MINUS_TWO_POW_128},
{MIN_INT256, MIN_INT256},
{MAX_INT256, MAX_INT256},
}
for _, tt := range tests {
x, err := FromDecimal(tt.input)
if err != nil {
t.Errorf("Failed to parse input (%s): %v", tt.input, err)
continue
}
output := x.String()
if output != tt.expected {
t.Errorf("String(%s) = %s, want %s", tt.input, output, tt.expected)
}
}
}
func TestNilToZero(t *testing.T) {
z := New().NilToZero()
if z.Sign() != 0 {
t.Errorf("NilToZero() = %d, want %d", z.Sign(), 0)
}
}
doc.gno
// The int256 package provides a 256-bit signed interger type for gno, // supporting arithmetic operations and bitwise manipulation. // // It designed for applications that require high-precision arithmetic // beyond the standard 64-bit range. // // ## Features // // - 256-bit Signed Integers: Support for large integer ranging from -2^255 to 2^255-1. // - Two's Complement Representation: Efficient storage and computation using two's complement. // - Arithmetic Operations: Add, Sub, Mul, Div, Mod, Inc, Dec, etc. // - Bitwise Operations: And, Or, Xor, Not, etc. // - Comparison Operations: Cmp, Eq, Lt, Gt, etc. // - Conversion Functions: Int to Uint, Uint to Int, etc. // - String Parsing and Formatting: Convert to and from decimal string representation. // // ## Notes // // - Some methods may panic when encountering invalid inputs or overflows. // - The `int256.Int` type can interact with `uint256.Uint` from the `p/demo/uint256` package. // - Unlike `math/big.Int`, the `int256.Int` type has fixed size (256-bit) and does not support // arbitrary precision arithmetic. // // # Division and modulus operations // // This package provides three different division and modulus operations: // // - Div and Rem: Truncated division (T-division) // - Quo and Mod: Floored division (F-division) // - DivE and ModE: Euclidean division (E-division) // // Truncated division (Div, Rem) is the most common implementation in modern processors // and programming languages. It rounds quotients towards zero and the remainder // always has the same sign as the dividend. // // Floored division (Quo, Mod) always rounds quotients towards negative infinity. // This ensures that the modulus is always non-negative for a positive divisor, // which can be useful in certain algorithms. // // Euclidean division (DivE, ModE) ensures that the remainder is always non-negative, // regardless of the signs of the dividend and divisor. This has several mathematical // advantages: // // 1. It satisfies the unique division with remainder theorem. // 2. It preserves division and modulus properties for negative divisors. // 3. It allows for optimizations in divisions by powers of two. // // [+] Currently, ModE and Mod are shared the same implementation. // // ## Performance considerations: // // - For most operations, the performance difference between these division types is negligible. // - Euclidean division may require an extra comparison and potentially an addition, // which could impact performance in extremely performance-critical scenarios. // - For divisions by powers of two, Euclidean division can be optimized to use // bitwise operations, potentially offering better performance. // // ## Usage guidelines: // // - Use Div and Rem for general-purpose division that matches most common expectations. // - Use Quo and Mod when you need a non-negative remainder for positive divisors, // or when implementing algorithms that assume floored division. // - Use DivE and ModE when you need the mathematical properties of Euclidean division, // or when working with algorithms that specifically require it. // // Note: When working with negative numbers, be aware of the differences in behavior // between these division types, especially at the boundaries of integer ranges. // // ## References // // Daan Leijen, “Division and Modulus for Computer Scientists”: // https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/divmodnote-letter.pdf package int256
gnomod.toml
module = "gno.land/p/onbloc/int256/v0" gno = "0.9" [addpkg] creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"
int256.gno
package int256
import (
"errors"
"gno.land/p/onbloc/uint256/v0"
)
var (
int1 = NewInt(1)
uint0 = uint256.NewUint(0)
uint1 = uint256.NewUint(1)
)
type Int struct {
value uint256.Uint
}
// New creates and returns a new Int initialized to zero.
func New() *Int {
return &Int{}
}
// NewInt allocates and returns a new Int set to the value of the provided int64.
func NewInt(x int64) *Int {
return New().SetInt64(x)
}
// Zero returns a new Int initialized to 0.
//
// This function is useful for creating a starting point for calculations or
// when an explicit zero value is needed.
func Zero() *Int { return &Int{} }
// One returns a new Int initialized to one.
//
// This function is convenient for operations that require a unit value,
// such as incrementing or serving as an identity element in multiplication.
func One() *Int {
return &Int{
value: *uint256.NewUint(1),
}
}
// Sign determines the sign of the Int.
//
// It returns -1 for negative numbers, 0 for zero, and +1 for positive numbers.
func (z *Int) Sign() int {
if z == nil || z.IsZero() {
return 0
}
// Right shift the value by 255 bits to check the sign bit.
// In two's complement representation, the most significant bit (MSB) is the sign bit.
// If the MSB is 0, the number is positive; if it is 1, the number is negative.
//
// Example:
// Original value: 1 0 1 0 ... 0 1 (256 bits)
// After Rsh 255: 0 0 0 0 ... 0 1 (1 bit)
//
// This approach is highly efficient as it avoids the need for comparisons
// or arithmetic operations on the full 256-bit number. Instead it reduces
// the problem to checking a single bit.
//
// Additionally, this method will work correctly for all values,
// including the minimum possible negative number (which in two's complement
// doesn't have a positive counterpart in the same bit range).
var temp uint256.Uint
if temp.Rsh(&z.value, 255).IsZero() {
return 1
}
return -1
}
// FromDecimal creates a new Int from a decimal string representation.
// It handles both positive and negative values.
//
// This function is useful for parsing user input or reading numeric data
// from text-based formats.
func FromDecimal(s string) (*Int, error) {
return New().SetString(s)
}
// MustFromDecimal is similar to FromDecimal but panics if the input string
// is not a valid decimal representation.
func MustFromDecimal(s string) *Int {
z, err := FromDecimal(s)
if err != nil {
panic(err)
}
return z
}
// SetString sets the Int to the value represented by the input string.
// This method supports decimal string representations of integers and handles
// both positive and negative values.
func (z *Int) SetString(s string) (*Int, error) {
if len(s) == 0 {
return nil, errors.New("cannot set int256 from empty string")
}
// Check for negative sign
neg := s[0] == '-'
if neg || s[0] == '+' {
s = s[1:]
}
// Convert string to uint256
temp, err := uint256.FromDecimal(s)
if err != nil {
return nil, err
}
// If negative, negate the uint256 value
if neg {
temp.Neg(temp)
}
z.value.Set(temp)
return z, nil
}
// FromUint256 sets the Int to the value of the provided Uint256.
//
// This method allows for conversion from unsigned 256-bit integers
// to signed integers.
func (z *Int) FromUint256(v *uint256.Uint) *Int {
z.value.Set(v)
return z
}
int256_test.gno
package int256
import (
"testing"
"gno.land/p/onbloc/uint256/v0"
)
func TestInitializers(t *testing.T) {
tests := []struct {
name string
fn func() *Int
wantSign int
wantStr string
}{
{"Zero", Zero, 0, "0"},
{"New", New, 0, "0"},
{"One", One, 1, "1"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
z := tt.fn()
if z.Sign() != tt.wantSign {
t.Errorf("%s() = %d, want %d", tt.name, z.Sign(), tt.wantSign)
}
if z.String() != tt.wantStr {
t.Errorf("%s() = %s, want %s", tt.name, z.String(), tt.wantStr)
}
})
}
}
func TestNewInt(t *testing.T) {
tests := []struct {
input int64
expected int
}{
{0, 0},
{1, 1},
{-1, -1},
{9223372036854775807, 1}, // max int64
{-9223372036854775808, -1}, // min int64
}
for _, tt := range tests {
z := NewInt(tt.input)
if z.Sign() != tt.expected {
t.Errorf("NewInt(%d) = %d, want %d", tt.input, z.Sign(), tt.expected)
}
}
}
func TestFromDecimal(t *testing.T) {
tests := []struct {
input string
expected int
isError bool
}{
{"0", 0, false},
{"1", 1, false},
{"-1", -1, false},
{"123456789", 1, false},
{"-123456789", -1, false},
{"invalid", 0, true},
}
for _, tt := range tests {
z, err := FromDecimal(tt.input)
if tt.isError {
if err == nil {
t.Errorf("FromDecimal(%s) expected error, but got nil", tt.input)
}
} else {
if err != nil {
t.Errorf("FromDecimal(%s) unexpected error: %v", tt.input, err)
} else if z.Sign() != tt.expected {
t.Errorf("FromDecimal(%s) sign is incorrect. Expected: %d, Actual: %d", tt.input, tt.expected, z.Sign())
}
}
}
}
func TestMustFromDecimal(t *testing.T) {
tests := []struct {
input string
expected int
shouldPanic bool
}{
{"0", 0, false},
{"1", 1, false},
{"-1", -1, false},
{"123", 1, false},
{"invalid", 0, true},
}
for _, tt := range tests {
if tt.shouldPanic {
defer func() {
if r := recover(); r == nil {
t.Errorf("MustFromDecimal(%q) expected panic, but got nil", tt.input)
}
}()
}
z := MustFromDecimal(tt.input)
if !tt.shouldPanic && z.Sign() != tt.expected {
t.Errorf("MustFromDecimal(%q) sign is incorrect. Expected: %d, Actual: %d", tt.input, tt.expected, z.Sign())
}
}
}
func TestSetUint64(t *testing.T) {
tests := []uint64{
0,
1,
18446744073709551615, // max uint64
}
for _, tt := range tests {
z := New().SetUint64(tt)
if z.Sign() < 0 {
t.Errorf("SetUint64(%d) result is negative", tt)
}
if tt == 0 && z.Sign() != 0 {
t.Errorf("SetUint64(0) result is not zero")
}
if tt > 0 && z.Sign() != 1 {
t.Errorf("SetUint64(%d) result is not positive", tt)
}
}
}
func TestFromUint256(t *testing.T) {
tests := []struct {
input *uint256.Uint
expected int
}{
{uint256.NewUint(0), 0},
{uint256.NewUint(1), 1},
{uint256.NewUint(18446744073709551615), 1},
}
for _, tt := range tests {
z := New().FromUint256(tt.input)
if z.Sign() != tt.expected {
t.Errorf("FromUint256(%v) = %d, want %d", tt.input, z.Sign(), tt.expected)
}
}
}
func TestSign(t *testing.T) {
tests := []struct {
x string
want int
}{
{"0", 0},
{"-0", 0},
{"+0", 0},
{"1", 1},
{"-1", -1},
{"9223372036854775807", 1},
{"-9223372036854775808", -1},
}
for _, tt := range tests {
z := MustFromDecimal(tt.x)
got := z.Sign()
if got != tt.want {
t.Errorf("Sign(%s) = %d, want %d", tt.x, got, tt.want)
}
}
}
func BenchmarkSign(b *testing.B) {
z := New()
for i := 0; i < b.N; i++ {
z.SetUint64(uint64(i))
z.Sign()
}
}
func TestSetAndToString(t *testing.T) {
tests := []struct {
input string
expected int
isError bool
}{
{"0", 0, false},
{"1", 1, false},
{"-1", -1, false},
{"123456789", 1, false},
{"-123456789", -1, false},
{"invalid", 0, true},
}
for _, tt := range tests {
z, err := New().SetString(tt.input)
if tt.isError {
if err == nil {
t.Errorf("SetString(%s) expected error, but got nil", tt.input)
}
} else {
if err != nil {
t.Errorf("SetString(%s) unexpected error: %v", tt.input, err)
} else if z.Sign() != tt.expected {
t.Errorf("SetString(%s) sign is incorrect. Expected: %d, Actual: %d", tt.input, tt.expected, z.Sign())
} else if z.String() != tt.input {
t.Errorf("SetString(%s) string representation is incorrect. Expected: %s, Actual: %s", tt.input, tt.input, z.String())
}
}
}
}