1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-13 17:22:27 +08:00

fix: fix bug in ToBytes func

This commit is contained in:
dudaodong
2022-03-26 20:54:37 +08:00
parent 142deb83b2
commit a5018c110c
2 changed files with 49 additions and 11 deletions

View File

@@ -6,9 +6,10 @@ package convertor
import ( import (
"bytes" "bytes"
"encoding/gob" "encoding/binary"
"encoding/json" "encoding/json"
"fmt" "fmt"
"math"
"reflect" "reflect"
"regexp" "regexp"
"strconv" "strconv"
@@ -21,14 +22,44 @@ func ToBool(s string) (bool, error) {
} }
// ToBytes convert interface to bytes // ToBytes convert interface to bytes
func ToBytes(data any) ([]byte, error) { func ToBytes(value any) ([]byte, error) {
var buf bytes.Buffer v := reflect.ValueOf(value)
enc := gob.NewEncoder(&buf)
err := enc.Encode(data) switch value.(type) {
if err != nil { case int, int8, int16, int32, int64:
return nil, err 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 // ToChar convert string to char slice

View File

@@ -42,14 +42,21 @@ func TestToBytes(t *testing.T) {
"1", "1",
} }
expected := [][]byte{ expected := [][]byte{
{3, 4, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0},
{3, 2, 0, 0}, {102, 97, 108, 115, 101},
{4, 12, 0, 1, 49}, {49},
} }
for i := 0; i < len(cases); i++ { for i := 0; i < len(cases); i++ {
actual, _ := ToBytes(cases[i]) actual, _ := ToBytes(cases[i])
assert.Equal(expected[i], actual) 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) { func TestToInt(t *testing.T) {