github.com/aeternity/aepp-sdk-go@v1.0.3-0.20190606142815-1c0ffdc21fd9/utils/utils.go (about) 1 package utils 2 3 import ( 4 "errors" 5 "fmt" 6 "math/big" 7 8 "github.com/go-openapi/strfmt" 9 ) 10 11 // BigInt is an alias for math/big.Int, for use with Swagger generated code. 12 // Even though it has some corresponding methods, convert it as soon as possible into big.Int. 13 type BigInt big.Int 14 15 // String casts BigInt into big.Int and uses its String method. 16 func (b *BigInt) String() string { 17 bc := big.Int(*b) 18 return bc.String() 19 } 20 21 // Validate ensures that the BigInt's value is >= 0. 22 // The actual check does not need 'formats' from swagger, which is why Validate() wraps that function. 23 func (b *BigInt) Validate(formats strfmt.Registry) error { 24 v := b.LargerOrEqualToZero() 25 if !v { 26 return fmt.Errorf("%v was not >=0", b.String()) 27 } 28 return nil 29 } 30 31 // LargerThanZero returns true if it is >0 32 func (b *BigInt) LargerThanZero() bool { 33 zero := new(BigInt) 34 35 if b.Cmp(zero) != 1 { 36 return false 37 } 38 return true 39 } 40 41 // LargerOrEqualToZero checks that the number is >=0 42 func (b *BigInt) LargerOrEqualToZero() bool { 43 zero := new(BigInt) 44 45 if b.Cmp(zero) == -1 { 46 return false 47 } 48 return true 49 } 50 51 // UnmarshalJSON implements the json.Unmarshaler interface. 52 func (b *BigInt) UnmarshalJSON(text []byte) error { 53 bc := new(big.Int) 54 err := bc.UnmarshalJSON(text) 55 if err != nil { 56 return err 57 } 58 b.Set(bc) 59 return nil 60 } 61 62 // Set makes a BigInt equal to a given big.Int. 63 func (b *BigInt) Set(i *big.Int) *BigInt { 64 iB := BigInt(*i) 65 *b = iB 66 return b 67 } 68 69 // Cmp compares two BigInts just like big.Int 70 func (b *BigInt) Cmp(i *BigInt) int { 71 b2 := big.Int(*b) 72 i2 := big.Int(*i) 73 return b2.Cmp(&i2) 74 } 75 76 // NewIntFromString returns a new math/big.Int from a string representation 77 func NewIntFromString(number string) (i *big.Int, err error) { 78 i = new(big.Int) 79 _, success := i.SetString(number, 10) 80 if success == false { 81 return nil, errors.New("Could not parse string as a number") 82 } 83 return i, nil 84 } 85 86 // RequireIntFromString returns a new big.Int from a string representation or panics if NewBigIntFromString would have returned an error. 87 func RequireIntFromString(number string) *big.Int { 88 i, err := NewIntFromString(number) 89 if err != nil { 90 panic(err) 91 } 92 return i 93 } 94 95 // NewIntFromUint64 returns a new big.Int from a uint64 representation 96 func NewIntFromUint64(number uint64) (i *big.Int) { 97 i = new(big.Int) 98 i.SetUint64(number) 99 return i 100 }