Move ToHex/FromHex into bytes

This commit is contained in:
Taylor Gerring 2015-03-22 13:32:52 +01:00
parent 9682a3ef3e
commit 08b21acff1
4 changed files with 43 additions and 42 deletions

View File

@ -9,6 +9,28 @@ import (
"strings" "strings"
) )
func ToHex(b []byte) string {
hex := Bytes2Hex(b)
// Prefer output of "0x0" instead of "0x"
if len(hex) == 0 {
hex = "0"
}
return "0x" + hex
}
func FromHex(s string) []byte {
if len(s) > 1 {
if s[0:2] == "0x" {
s = s[2:]
}
if len(s)%2 == 1 {
s = "0" + s
}
return Hex2Bytes(s)
}
return nil
}
type Bytes []byte type Bytes []byte
func (self Bytes) String() string { func (self Bytes) String() string {

View File

@ -1,6 +1,9 @@
package common package common
import ( import (
"bytes"
"testing"
checker "gopkg.in/check.v1" checker "gopkg.in/check.v1"
) )
@ -191,3 +194,21 @@ func (s *BytesSuite) TestRightPadString(c *checker.C) {
c.Assert(resstd, checker.Equals, exp) c.Assert(resstd, checker.Equals, exp)
c.Assert(resshrt, checker.Equals, val) c.Assert(resshrt, checker.Equals, val)
} }
func TestFromHex(t *testing.T) {
input := "0x01"
expected := []byte{1}
result := FromHex(input)
if bytes.Compare(expected, result) != 0 {
t.Errorf("Expected % x got % x", expected, result)
}
}
func TestFromHexOddLength(t *testing.T) {
input := "0x1"
expected := []byte{1}
result := FromHex(input)
if bytes.Compare(expected, result) != 0 {
t.Errorf("Expected % x got % x", expected, result)
}
}

View File

@ -65,27 +65,6 @@ func DefaultDataDir() string {
} }
} }
func ToHex(b []byte) string {
hex := Bytes2Hex(b)
// Prefer output of "0x0" instead of "0x"
if len(hex) == 0 {
hex = "0"
}
return "0x" + hex
}
func FromHex(s string) []byte {
if len(s) > 1 {
if s[0:2] == "0x" {
s = s[2:]
}
if len(s)%2 == 1 {
s = "0" + s
}
return Hex2Bytes(s)
}
return nil
}
func IsWindows() bool { func IsWindows() bool {
return runtime.GOOS == "windows" return runtime.GOOS == "windows"
} }

View File

@ -1,10 +1,8 @@
package common package common
import ( import (
"bytes"
"math/big" "math/big"
"os" "os"
"testing"
checker "gopkg.in/check.v1" checker "gopkg.in/check.v1"
) )
@ -68,22 +66,3 @@ func (s *CommonSuite) TestLarge(c *checker.C) {
c.Assert(adalarge, checker.Equals, "10000E7 Einstein") c.Assert(adalarge, checker.Equals, "10000E7 Einstein")
c.Assert(weilarge, checker.Equals, "100 Babbage") c.Assert(weilarge, checker.Equals, "100 Babbage")
} }
//fromHex
func TestFromHex(t *testing.T) {
input := "0x01"
expected := []byte{1}
result := FromHex(input)
if bytes.Compare(expected, result) != 0 {
t.Errorf("Expected % x got % x", expected, result)
}
}
func TestFromHexOddLength(t *testing.T) {
input := "0x1"
expected := []byte{1}
result := FromHex(input)
if bytes.Compare(expected, result) != 0 {
t.Errorf("Expected % x got % x", expected, result)
}
}