github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/protocol/vm/types.go (about) 1 package vm 2 3 import ( 4 "github.com/holiman/uint256" 5 ) 6 7 var trueBytes = []byte{1} 8 9 // BoolBytes convert bool to bytes 10 func BoolBytes(b bool) (result []byte) { 11 if b { 12 return trueBytes 13 } 14 return []byte{} 15 } 16 17 // AsBool convert bytes to bool 18 func AsBool(bytes []byte) bool { 19 for _, b := range bytes { 20 if b != 0 { 21 return true 22 } 23 } 24 return false 25 } 26 27 // Uint64Bytes convert uint64 to bytes in vm 28 func Uint64Bytes(n uint64) []byte { 29 return BigIntBytes(uint256.NewInt(n)) 30 } 31 32 // BigIntBytes conv big int to little endian bytes, uint256 is version 1.1.1 33 func BigIntBytes(n *uint256.Int) []byte { 34 return reverse(n.Bytes()) 35 } 36 37 // AsBigInt conv little endian bytes to big int 38 func AsBigInt(b []byte) (*uint256.Int, error) { 39 if len(b) > 32 { 40 return nil, ErrBadValue 41 } 42 43 res := uint256.NewInt(0).SetBytes(reverse(b)) 44 if res.Sign() < 0 { 45 return nil, ErrRange 46 } 47 48 return res, nil 49 } 50 51 func bigIntInt64(n *uint256.Int) (int64, error) { 52 if !n.IsUint64() { 53 return 0, ErrBadValue 54 } 55 56 i := int64(n.Uint64()) 57 if i < 0 { 58 return 0, ErrBadValue 59 } 60 return i, nil 61 } 62 63 // reverse []byte. 64 func reverse(b []byte) []byte { 65 r := make([]byte, len(b)) 66 copy(r, b) 67 for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 { 68 r[i], r[j] = r[j], r[i] 69 } 70 return r 71 }