2018-02-04 19:54:51 +00:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/hex"
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
|
|
|
const uint256Size = 32
|
|
|
|
|
|
|
|
// Uint256 is a 32 byte long unsigned integer.
|
|
|
|
type Uint256 [uint256Size]uint8
|
|
|
|
|
2018-03-02 15:24:09 +00:00
|
|
|
// Uint256DecodeString attempts to decode the given string into an Uint256.
|
|
|
|
func Uint256DecodeString(s string) (u Uint256, err error) {
|
2018-02-04 19:54:51 +00:00
|
|
|
if len(s) != uint256Size*2 {
|
2018-03-02 15:24:09 +00:00
|
|
|
return u, fmt.Errorf("expected string size of %d got %d", uint256Size*2, len(s))
|
2018-02-04 19:54:51 +00:00
|
|
|
}
|
|
|
|
b, err := hex.DecodeString(s)
|
|
|
|
if err != nil {
|
2018-03-02 15:24:09 +00:00
|
|
|
return u, err
|
2018-02-04 19:54:51 +00:00
|
|
|
}
|
2018-03-02 15:24:09 +00:00
|
|
|
return Uint256DecodeBytes(b)
|
2018-02-04 19:54:51 +00:00
|
|
|
}
|
|
|
|
|
2018-03-02 15:24:09 +00:00
|
|
|
// Uint256DecodeBytes attempts to decode the given string into an Uint256.
|
|
|
|
func Uint256DecodeBytes(b []byte) (u Uint256, err error) {
|
|
|
|
b = ArrayReverse(b)
|
2018-02-04 19:54:51 +00:00
|
|
|
if len(b) != uint256Size {
|
2018-03-02 15:24:09 +00:00
|
|
|
return u, fmt.Errorf("expected []byte of size %d got %d", uint256Size, len(b))
|
2018-02-04 19:54:51 +00:00
|
|
|
}
|
|
|
|
for i := 0; i < uint256Size; i++ {
|
2018-03-02 15:24:09 +00:00
|
|
|
u[i] = b[i]
|
2018-02-04 19:54:51 +00:00
|
|
|
}
|
2018-03-02 15:24:09 +00:00
|
|
|
return u, nil
|
2018-02-04 19:54:51 +00:00
|
|
|
}
|
|
|
|
|
2018-03-02 15:24:09 +00:00
|
|
|
// ToSlice returns a byte slice representation of u.
|
|
|
|
func (u Uint256) Bytes() []byte {
|
2018-02-04 19:54:51 +00:00
|
|
|
b := make([]byte, uint256Size)
|
|
|
|
for i := 0; i < uint256Size; i++ {
|
|
|
|
b[i] = byte(u[i])
|
|
|
|
}
|
|
|
|
return b
|
|
|
|
}
|
|
|
|
|
2018-03-02 15:24:09 +00:00
|
|
|
// BytesReverse return a reversed byte representation of u.
|
|
|
|
func (u Uint256) BytesReverse() []byte {
|
|
|
|
return ArrayReverse(u.Bytes())
|
2018-02-04 19:54:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Equals returns true if both Uint256 values are the same.
|
|
|
|
func (u Uint256) Equals(other Uint256) bool {
|
|
|
|
return u.String() == other.String()
|
|
|
|
}
|
|
|
|
|
|
|
|
// String implements the stringer interface.
|
|
|
|
func (u Uint256) String() string {
|
2018-03-02 15:24:09 +00:00
|
|
|
return hex.EncodeToString(ArrayReverse(u.Bytes()))
|
2018-02-04 19:54:51 +00:00
|
|
|
}
|