diff --git a/common/gearman.go b/common/gearman.go index cc9d41e..e9cc5e4 100644 --- a/common/gearman.go +++ b/common/gearman.go @@ -5,6 +5,11 @@ package common +import ( + "bytes" + "encoding/binary" +) + const ( NETWORK = "tcp" // queue size @@ -55,12 +60,25 @@ const ( // Decode [4]byte to uint32 func BytesToUint32(buf [4]byte) uint32 { - return uint32(buf[0])<<24 + uint32(buf[1])<<16 + uint32(buf[2])<<8 + - uint32(buf[3]) + var r uint32 + b := bytes.NewBuffer(buf[:]) + err := binary.Read(b, binary.BigEndian, &r) + if err != nil { + return 0 + } + return r } // Encode uint32 to [4]byte func Uint32ToBytes(i uint32) [4]byte { - return [4]byte{byte((i >> 24) & 0xff), byte((i >> 16) & 0xff), - byte((i >> 8) & 0xff), byte(i & 0xff),} + buf := new(bytes.Buffer) + err := binary.Write(buf, binary.BigEndian, i) + if err != nil { + return [4]byte{0, 0, 0, 0} + } + var r [4]byte + for k, v := range buf.Bytes() { + r[k] = v + } + return r } diff --git a/common/gearman_test.go b/common/gearman_test.go new file mode 100644 index 0000000..746b8b1 --- /dev/null +++ b/common/gearman_test.go @@ -0,0 +1,38 @@ +package common + +import ( + "bytes" + "testing" +) + +var ( + testCase = map[uint32][4]byte { + 0: [...]byte{0, 0, 0, 0}, + 1: [...]byte{0, 0, 0, 1}, + 256: [...]byte{0, 0, 1, 0}, + 256 * 256: [...]byte{0, 1, 0, 0}, + 256 * 256 * 256: [...]byte{1, 0, 0, 0}, + 256 * 256 * 256 + 256 * 256 + 256 + 1: [...]byte{1, 1, 1, 1}, + 4294967295 : [...]byte{0xFF, 0xFF, 0xFF, 0xFF}, + } +) + +func TestUint32ToBytes(t *testing.T) { + for k, v := range testCase { + b := Uint32ToBytes(k) + if bytes.Compare(b[:], v[:]) != 0 { + t.Errorf("%v was expected, but %v was got", v, b) + } + } +} + +func TestBytesToUint32s(t *testing.T) { + for k, v := range testCase { + u := BytesToUint32([4]byte(v)) + if u != k { + t.Errorf("%v was expected, but %v was got", k, u) + } + } +} + +