plugeth/common/types.go

83 lines
1.7 KiB
Go
Raw Normal View History

2015-03-16 10:27:38 +00:00
package common
2015-03-16 16:09:08 +00:00
import "fmt"
type Hash [32]byte
2015-03-16 10:59:52 +00:00
var (
zeroHash Hash
zeroAddress Address
)
func BytesToHash(b []byte) Hash {
var h Hash
h.SetBytes(b)
return h
}
func StringToHash(s string) Hash { return BytesToHash([]byte(s)) }
func BytesToAddress(b []byte) Address {
var a Address
a.SetBytes(b)
return a
}
func StringToAddress(s string) Address { return BytesToAddress([]byte(s)) }
2015-03-16 10:59:52 +00:00
// Don't use the default 'String' method in case we want to overwrite
// Get the string representation of the underlying hash
func (h Hash) Str() string {
2015-03-16 10:59:52 +00:00
return string(h[:])
}
// Sets the hash to the value of b. If b is larger than len(h) it will panic
2015-03-16 15:28:16 +00:00
func (h *Hash) SetBytes(b []byte) {
2015-03-16 10:59:52 +00:00
if len(b) > len(h) {
2015-03-16 16:09:08 +00:00
panic(fmt.Sprintf("unable to set bytes. too big = %d", len(b)))
2015-03-16 10:59:52 +00:00
}
// reverse loop
2015-03-16 15:28:16 +00:00
for i := len(b) - 1; i >= 0; i-- {
2015-03-16 10:59:52 +00:00
h[i] = b[i]
}
}
// Set string `s` to h. If s is larger than len(h) it will panic
2015-03-16 15:28:16 +00:00
func (h *Hash) SetString(s string) { h.SetBytes([]byte(s)) }
2015-03-16 11:20:17 +00:00
// Sets h to other
2015-03-16 15:28:16 +00:00
func (h *Hash) Set(other Hash) {
for i, v := range other {
h[i] = v
}
}
type Address [20]byte
2015-03-16 10:59:52 +00:00
// Get the string representation of the underlying address
func (a Address) Str() string {
return string(a[:])
}
// Sets the address to the value of b. If b is larger than len(a) it will panic
func (a *Address) SetBytes(b []byte) {
2015-03-16 11:20:17 +00:00
if len(b) > len(a) {
2015-03-16 16:09:08 +00:00
panic(fmt.Sprintf("unable to set bytes. too big = %d", len(b)))
2015-03-16 10:59:52 +00:00
}
// reverse loop
2015-03-16 16:09:08 +00:00
for i := len(b) - 1; i >= 0; i-- {
2015-03-16 11:20:17 +00:00
a[i] = b[i]
2015-03-16 10:59:52 +00:00
}
}
// Set string `s` to a. If s is larger than len(a) it will panic
func (a *Address) SetString(s string) { a.SetBytes([]byte(s)) }
// Sets a to other
func (a *Address) Set(other Address) {
for i, v := range other {
a[i] = v
}
}