conversion.gno

2.34 Kb ยท 107 lines
  1package int256
  2
  3import (
  4	"math"
  5
  6	"gno.land/p/demo/uint256"
  7)
  8
  9// SetInt64 sets the Int to the value of the provided int64.
 10//
 11// This method allows for easy conversion from standard Go integer types
 12// to Int, correctly handling both positive and negative values.
 13func (z *Int) SetInt64(v int64) *Int {
 14	if v >= 0 {
 15		z.value.SetUint64(uint64(v))
 16	} else {
 17		z.value.SetUint64(uint64(-v)).Neg(&z.value)
 18	}
 19	return z
 20}
 21
 22// SetUint64 sets the Int to the value of the provided uint64.
 23func (z *Int) SetUint64(v uint64) *Int {
 24	z.value.SetUint64(v)
 25	return z
 26}
 27
 28// Uint64 returns the lower 64-bits of z
 29func (z *Int) Uint64() uint64 {
 30	if z.Sign() < 0 {
 31		panic("cannot convert negative int256 to uint64")
 32	}
 33	if z.value.Gt(uint256.NewUint(0).SetUint64(math.MaxUint64)) {
 34		panic("overflow: int256 does not fit in uint64 type")
 35	}
 36	return z.value.Uint64()
 37}
 38
 39// Int64 returns the lower 64-bits of z
 40func (z *Int) Int64() int64 {
 41	if z.Sign() >= 0 {
 42		if z.value.BitLen() > 64 {
 43			panic("overflow: int256 does not fit in int64 type")
 44		}
 45		return int64(z.value.Uint64())
 46	}
 47	var temp uint256.Uint
 48	temp.Sub(uint256.NewUint(0), &z.value) // temp = -z.value
 49	if temp.BitLen() > 64 {
 50		panic("overflow: int256 does not fit in int64 type")
 51	}
 52	return -int64(temp.Uint64())
 53}
 54
 55// Neg sets z to -x and returns z.)
 56func (z *Int) Neg(x *Int) *Int {
 57	if x.IsZero() {
 58		z.value.Clear()
 59	} else {
 60		z.value.Neg(&x.value)
 61	}
 62	return z
 63}
 64
 65// Set sets z to x and returns z.
 66func (z *Int) Set(x *Int) *Int {
 67	z.value.Set(&x.value)
 68	return z
 69}
 70
 71// SetFromUint256 converts a uint256.Uint to Int and sets the value to z.
 72func (z *Int) SetUint256(x *uint256.Uint) *Int {
 73	z.value.Set(x)
 74	return z
 75}
 76
 77// ToString returns a string representation of z in base 10.
 78// The string is prefixed with a minus sign if z is negative.
 79func (z *Int) String() string {
 80	if z.value.IsZero() {
 81		return "0"
 82	}
 83	sign := z.Sign()
 84	var temp uint256.Uint
 85	if sign >= 0 {
 86		temp.Set(&z.value)
 87	} else {
 88		// temp = -z.value
 89		temp.Sub(uint256.NewUint(0), &z.value)
 90	}
 91	s := temp.Dec()
 92	if sign < 0 {
 93		return "-" + s
 94	}
 95	return s
 96}
 97
 98// NilToZero returns the Int if it's not nil, or a new zero-valued Int otherwise.
 99//
100// This method is useful for safely handling potentially nil Int pointers,
101// ensuring that operations always have a valid Int to work with.
102func (z *Int) NilToZero() *Int {
103	if z == nil {
104		return Zero()
105	}
106	return z
107}