Skip to content

Instantly share code, notes, and snippets.

@safx
Created June 24, 2014 12:02
Show Gist options
  • Save safx/ec446da5c0694201c280 to your computer and use it in GitHub Desktop.
Save safx/ec446da5c0694201c280 to your computer and use it in GitHub Desktop.
GoConvey Sample
package sample
import "errors"
func HexStringToInteger(s string) (int, error) {
num := 0
signum := 1
if signum == 0 {
return 0, nil
}
for i, j := range(s) {
switch {
case j == '-' && i == 0: signum = -1
case '0' <= j && j <= '9': num = num * 16 + int(j - '0')
case 'a' <= j && j <= 'f': num = num * 16 + int(j - 'a') + 10
case 'A' <= j && j <= 'F': num = num * 16 + int(j - 'A') + 10
default: return 0, errors.New("Unexpected char")
}
}
return num * signum, nil
}
package sample
import (
"errors"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestHexStringToInteger(t *testing.T) {
Convey("数字とa〜fだけの文字列のときは数値を返す", t, func() {
r, _ := HexStringToInteger("0")
So(r, ShouldEqual, 0)
r, _ = HexStringToInteger("1")
So(r, ShouldEqual, 1)
r, _ = HexStringToInteger("c")
So(r, ShouldEqual, 12)
r, _ = HexStringToInteger("10")
So(r, ShouldEqual, 16)
r, _ = HexStringToInteger("64")
So(r, ShouldEqual, 100)
r, _ = HexStringToInteger("ff")
So(r, ShouldEqual, 255)
})
Convey("数字とA〜Fだけの文字列をときは数値を返す", t, func() {
r, _ := HexStringToInteger("FF")
So(r, ShouldEqual, 255)
r, _ = HexStringToInteger("FFFF")
So(r, ShouldEqual, 65535)
})
Convey("先頭の-が付いているときは負の値を返す", t, func() {
r, _ := HexStringToInteger("-FF")
So(r, ShouldEqual, -255)
})
Convey("先頭以外に-を含むときはエラーを返す", t, func() {
r, e := HexStringToInteger("F-F")
So(r, ShouldEqual, 0)
So(e, ShouldHaveSameTypeAs, errors.New(""))
r, e = HexStringToInteger("FF-")
So(r, ShouldEqual, 0)
So(e, ShouldHaveSameTypeAs, errors.New(""))
})
Convey("数値とA〜F、a〜f以外の文字を含む場合はエラーを返す", t, func() {
r, e := HexStringToInteger("q")
So(r, ShouldEqual, 0)
So(e, ShouldHaveSameTypeAs, errors.New(""))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment