From a5018c110c0c9a7d74cd4743458ce0dbeecc09e5 Mon Sep 17 00:00:00 2001 From: dudaodong Date: Sat, 26 Mar 2022 20:54:37 +0800 Subject: [PATCH] fix: fix bug in ToBytes func --- convertor/convertor.go | 47 ++++++++++++++++++++++++++++++------- convertor/convertor_test.go | 13 +++++++--- 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/convertor/convertor.go b/convertor/convertor.go index 9acf416..ea53b22 100644 --- a/convertor/convertor.go +++ b/convertor/convertor.go @@ -6,9 +6,10 @@ package convertor import ( "bytes" - "encoding/gob" + "encoding/binary" "encoding/json" "fmt" + "math" "reflect" "regexp" "strconv" @@ -21,14 +22,44 @@ func ToBool(s string) (bool, error) { } // ToBytes convert interface to bytes -func ToBytes(data any) ([]byte, error) { - var buf bytes.Buffer - enc := gob.NewEncoder(&buf) - err := enc.Encode(data) - if err != nil { - return nil, err +func ToBytes(value any) ([]byte, error) { + v := reflect.ValueOf(value) + + switch value.(type) { + case int, int8, int16, int32, int64: + number := v.Int() + buf := bytes.NewBuffer([]byte{}) + buf.Reset() + err := binary.Write(buf, binary.BigEndian, number) + return buf.Bytes(), err + case uint, uint8, uint16, uint32, uint64: + number := v.Uint() + buf := bytes.NewBuffer([]byte{}) + buf.Reset() + err := binary.Write(buf, binary.BigEndian, number) + return buf.Bytes(), err + case float32: + number := float32(v.Float()) + bits := math.Float32bits(number) + bytes := make([]byte, 4) + binary.BigEndian.PutUint32(bytes, bits) + return bytes, nil + case float64: + number := v.Float() + bits := math.Float64bits(number) + bytes := make([]byte, 8) + binary.BigEndian.PutUint64(bytes, bits) + return bytes, nil + case bool: + return strconv.AppendBool([]byte{}, v.Bool()), nil + case string: + return []byte(v.String()), nil + case []byte: + return v.Bytes(), nil + default: + newValue, err := json.Marshal(value) + return newValue, err } - return buf.Bytes(), nil } // ToChar convert string to char slice diff --git a/convertor/convertor_test.go b/convertor/convertor_test.go index ca679c1..69c597a 100644 --- a/convertor/convertor_test.go +++ b/convertor/convertor_test.go @@ -42,14 +42,21 @@ func TestToBytes(t *testing.T) { "1", } expected := [][]byte{ - {3, 4, 0, 0}, - {3, 2, 0, 0}, - {4, 12, 0, 1, 49}, + {0, 0, 0, 0, 0, 0, 0, 0}, + {102, 97, 108, 115, 101}, + {49}, } for i := 0; i < len(cases); i++ { actual, _ := ToBytes(cases[i]) assert.Equal(expected[i], actual) } + + bytesData, err := ToBytes("abc") + if err != nil { + t.Error(err) + t.Fail() + } + assert.Equal("abc", ToString(bytesData)) } func TestToInt(t *testing.T) {