replace the covertion method

--HG--
branch : dev
This commit is contained in:
mikespook 2012-06-26 14:32:26 +08:00
parent 3051e6fe4b
commit e82732a5cc
2 changed files with 60 additions and 4 deletions

View File

@ -5,6 +5,11 @@
package common package common
import (
"bytes"
"encoding/binary"
)
const ( const (
NETWORK = "tcp" NETWORK = "tcp"
// queue size // queue size
@ -55,12 +60,25 @@ const (
// Decode [4]byte to uint32 // Decode [4]byte to uint32
func BytesToUint32(buf [4]byte) uint32 { func BytesToUint32(buf [4]byte) uint32 {
return uint32(buf[0])<<24 + uint32(buf[1])<<16 + uint32(buf[2])<<8 + var r uint32
uint32(buf[3]) b := bytes.NewBuffer(buf[:])
err := binary.Read(b, binary.BigEndian, &r)
if err != nil {
return 0
}
return r
} }
// Encode uint32 to [4]byte // Encode uint32 to [4]byte
func Uint32ToBytes(i uint32) [4]byte { func Uint32ToBytes(i uint32) [4]byte {
return [4]byte{byte((i >> 24) & 0xff), byte((i >> 16) & 0xff), buf := new(bytes.Buffer)
byte((i >> 8) & 0xff), byte(i & 0xff),} 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
} }

38
common/gearman_test.go Normal file
View File

@ -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)
}
}
}