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

feat: add EncodeByte and DecodeByte

This commit is contained in:
dudaodong
2022-08-29 15:08:50 +08:00
parent d62284e9a6
commit f5ec5eb58d
4 changed files with 168 additions and 10 deletions

View File

@@ -7,6 +7,7 @@ package convertor
import (
"bytes"
"encoding/binary"
"encoding/gob"
"encoding/json"
"fmt"
"math"
@@ -243,3 +244,21 @@ func ToChannel(array []interface{}) <-chan interface{} {
return ch
}
// EncodeByte encode data to byte
func EncodeByte(data interface{}) ([]byte, error) {
buffer := bytes.NewBuffer(nil)
encoder := gob.NewEncoder(buffer)
err := encoder.Encode(data)
if err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
// DecodeByte decode byte data to target object
func DecodeByte(data []byte, target interface{}) error {
buffer := bytes.NewBuffer(data)
decoder := gob.NewDecoder(buffer)
return decoder.Decode(target)
}

View File

@@ -195,3 +195,21 @@ func TestToChannel(t *testing.T) {
_, ok := <-ch
assert.Equal(false, ok)
}
func TestEncodeByte(t *testing.T) {
assert := internal.NewAssert(t, "TestEncodeByte")
byteData, _ := EncodeByte("abc")
expected := []byte{6, 12, 0, 3, 97, 98, 99}
assert.Equal(expected, byteData)
}
func TestDecodeByte(t *testing.T) {
assert := internal.NewAssert(t, "TestDecodeByte")
var obj string
byteData := []byte{6, 12, 0, 3, 97, 98, 99}
DecodeByte(byteData, &obj)
assert.Equal("abc", obj)
}