2019-02-27 20:55:48 +00:00
|
|
|
package stack
|
|
|
|
|
2019-02-27 22:41:46 +00:00
|
|
|
import (
|
2019-03-16 21:44:03 +00:00
|
|
|
"bytes"
|
2019-02-27 22:41:46 +00:00
|
|
|
"errors"
|
|
|
|
"math/big"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
2019-02-27 20:55:48 +00:00
|
|
|
// ByteArray represents a slice of bytes on the stack
|
|
|
|
type ByteArray struct {
|
|
|
|
*abstractItem
|
|
|
|
val []byte
|
|
|
|
}
|
|
|
|
|
2019-02-27 22:41:46 +00:00
|
|
|
//NewByteArray returns a ByteArray stack item
|
|
|
|
// given a byte slice
|
|
|
|
func NewByteArray(val []byte) *ByteArray {
|
|
|
|
return &ByteArray{
|
|
|
|
&abstractItem{},
|
|
|
|
val,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-27 20:55:48 +00:00
|
|
|
//ByteArray overrides the default abstractItem Bytes array method
|
|
|
|
func (ba *ByteArray) ByteArray() (*ByteArray, error) {
|
|
|
|
return ba, nil
|
|
|
|
}
|
2019-02-27 22:41:46 +00:00
|
|
|
|
2019-03-16 21:44:03 +00:00
|
|
|
//Equals returns true, if two bytearrays are equal
|
|
|
|
func (ba *ByteArray) Equals(other *ByteArray) *Boolean {
|
|
|
|
// If either are nil, return false
|
|
|
|
if ba == nil || other == nil {
|
|
|
|
return NewBoolean(false)
|
|
|
|
}
|
|
|
|
return NewBoolean(bytes.Equal(ba.val, other.val))
|
|
|
|
}
|
|
|
|
|
2019-02-27 22:41:46 +00:00
|
|
|
//Integer overrides the default Integer method to convert an
|
|
|
|
// ByteArray Into an integer
|
|
|
|
func (ba *ByteArray) Integer() (*Int, error) {
|
2019-03-15 22:30:25 +00:00
|
|
|
dest := reverse(ba.val)
|
2019-02-27 22:41:46 +00:00
|
|
|
integerVal := new(big.Int).SetBytes(dest)
|
2019-03-15 22:30:25 +00:00
|
|
|
return NewInt(integerVal)
|
2019-02-27 22:41:46 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
|
2019-03-15 22:30:25 +00:00
|
|
|
// Boolean will convert a byte array into a boolean stack item
|
2019-02-27 22:41:46 +00:00
|
|
|
func (ba *ByteArray) Boolean() (*Boolean, error) {
|
|
|
|
boolean, err := strconv.ParseBool(string(ba.val))
|
|
|
|
if err != nil {
|
|
|
|
return nil, errors.New("cannot convert byte array to a boolean")
|
|
|
|
}
|
2019-03-16 21:44:03 +00:00
|
|
|
return NewBoolean(boolean), nil
|
2019-03-15 22:30:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// XXX: move this into a pkg/util/slice folder
|
|
|
|
// Go mod not working
|
|
|
|
func reverse(b []byte) []byte {
|
|
|
|
if len(b) < 2 {
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
|
|
|
dest := make([]byte, len(b))
|
|
|
|
|
|
|
|
for i, j := 0, len(b)-1; i < j+1; i, j = i+1, j-1 {
|
|
|
|
dest[i], dest[j] = b[j], b[i]
|
|
|
|
}
|
|
|
|
|
|
|
|
return dest
|
2019-02-27 22:41:46 +00:00
|
|
|
}
|