github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/protocol/vm/types.go (about) 1 package vm 2 3 import "encoding/binary" 4 5 var trueBytes = []byte{1} 6 7 func BoolBytes(b bool) (result []byte) { 8 if b { 9 return trueBytes 10 } 11 return []byte{} 12 } 13 14 func AsBool(bytes []byte) bool { 15 for _, b := range bytes { 16 if b != 0 { 17 return true 18 } 19 } 20 return false 21 } 22 23 func Int64Bytes(n int64) []byte { 24 if n == 0 { 25 return []byte{} 26 } 27 res := make([]byte, 8) 28 // converting int64 to uint64 is a safe operation that 29 // preserves all data 30 binary.LittleEndian.PutUint64(res, uint64(n)) 31 for len(res) > 0 && res[len(res)-1] == 0 { 32 res = res[:len(res)-1] 33 } 34 return res 35 } 36 37 func AsInt64(b []byte) (int64, error) { 38 if len(b) == 0 { 39 return 0, nil 40 } 41 if len(b) > 8 { 42 return 0, ErrBadValue 43 } 44 45 var padded [8]byte 46 copy(padded[:], b) 47 48 res := binary.LittleEndian.Uint64(padded[:]) 49 // converting uint64 to int64 is a safe operation that 50 // preserves all data 51 return int64(res), nil 52 }