common/math: add HexOrDecimal64, HexOrDecimal256

This commit is contained in:
Felix Lange
2017-03-07 23:19:44 +01:00
parent 61d2150a07
commit 04fa6a3744
4 changed files with 54 additions and 12 deletions

View File

@ -18,6 +18,7 @@
package math
import (
"fmt"
"math/big"
)
@ -35,6 +36,24 @@ const (
wordBytes = wordBits / 8
)
// HexOrDecimal256 marshals big.Int as hex or decimal.
type HexOrDecimal256 big.Int
// UnmarshalText implements encoding.TextUnmarshaler.
func (i *HexOrDecimal256) UnmarshalText(input []byte) error {
bigint, ok := ParseBig256(string(input))
if !ok {
return fmt.Errorf("invalid hex or decimal integer %q", input)
}
*i = HexOrDecimal256(*bigint)
return nil
}
// MarshalText implements encoding.TextMarshaler.
func (i *HexOrDecimal256) MarshalText() ([]byte, error) {
return []byte(fmt.Sprintf("%#x", (*big.Int)(i))), nil
}
// ParseBig256 parses s as a 256 bit integer in decimal or hexadecimal syntax.
// Leading zeros are accepted. The empty string parses as zero.
func ParseBig256(s string) (*big.Int, bool) {