Skip to content

Commit

Permalink
rename Pack/Unpack to Encode/Decode
Browse files Browse the repository at this point in the history
  • Loading branch information
vipally committed Nov 1, 2017
1 parent ea070d7 commit b47d83d
Show file tree
Hide file tree
Showing 8 changed files with 127 additions and 117 deletions.
33 changes: 19 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# binary [![Build Status](https://travis-ci.org/vipally/binary.svg?branch=master)](https://travis-ci.org/vipally/binary) [![Coverage Status](https://coveralls.io/repos/github/vipally/binary/badge.svg?branch=master)](https://coveralls.io/github/vipally/binary?branch=master) [![GoDoc](https://godoc.org/github.com/vipally/binary?status.svg)](https://godoc.org/github.com/vipally/binary) ![Version](https://img.shields.io/badge/version-1.0.0.final-green.svg)
Package binary is uesed to Pack/Unpack between go data and byte slice.
# binary

[![Build Status](https://travis-ci.org/vipally/binary.svg?branch=master)](https://travis-ci.org/vipally/binary) [![Coverage Status](https://coveralls.io/repos/github/vipally/binary/badge.svg?branch=master)](https://coveralls.io/github/vipally/binary?branch=master) [![GoDoc](https://godoc.org/github.com/vipally/binary?status.svg)](https://godoc.org/github.com/vipally/binary) ![Version](https://img.shields.io/badge/version-1.1.0-green.svg)

***

Package binary is uesed to Encode/Decode between go data and byte slice.

The main purpose of this package is to replace package "std.binary".

Expand Down Expand Up @@ -30,7 +35,7 @@ Site : [https://github.com/vipally](https://github.com/vipally)
And their direct pointers.
eg: *string, *struct, *map, *slice, *int32.

# 2. [recommended usage] Use Pack/UnPack to read/write memory buffer directly.
# 2. [recommended usage] Use Encode/Decode to read/write memory buffer directly.
## Use RegStruct to improve struct encoding/decoding efficiency.
type someRegedStruct struct {
A int `binary:"ignore"`
Expand All @@ -39,31 +44,31 @@ Site : [https://github.com/vipally](https://github.com/vipally)
}
binary.RegStruct((*someRegedStruct)(nil))

If data implements interface Packer, it will use data.Pack/data.Unpack
If data implements interface BinaryEncoder, it will use data.Encode/data.Decode
to encode/decode data.
NOTE that data.Unpack must implement on pointer receiever to enable modifying
receiever.Even though Size/Pack of data can implement on non-pointer receiever,
binary.Pack(&data, nil) is required if data has implement interface Packer.
binary.Pack(data, nil) will probably NEVER use Packer methods to Pack/Unpack
NOTE that data.Decode must implement on pointer receiever to enable modifying
receiever.Even though Size/Encode of data can implement on non-pointer receiever,
binary.Encode(&data, nil) is required if data has implement interface BinaryEncoder.
binary.Encode(data, nil) will probably NEVER use BinaryEncoder methods to Encode/Decode
data.
eg:

import "github.com/vipally/binary"

//1.Pack with default buffer
if bytes, err := binary.Pack(&data, nil); err==nil{
//1.Encode with default buffer
if bytes, err := binary.Encode(&data, nil); err==nil{
//...
}

//2.Pack with existing buffer
//2.Encode with existing buffer
size := binary.Sizeof(data)
buffer := make([]byte, size)
if bytes, err := binary.Pack(&data, buffer); err==nil{
if bytes, err := binary.Encode(&data, buffer); err==nil{
//...
}

//3.Unpack from buffer
if err := binary.Unpack(bytes, &data); err==nil{
//3.Decode from buffer
if err := binary.Decode(bytes, &data); err==nil{
//...
}

Expand Down
6 changes: 3 additions & 3 deletions bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ func testBenchPack(b *testing.B, data interface{}, caseName string) {
b.SetBytes(int64(Sizeof(data)))
b.ResetTimer()
for i := 0; i < b.N; i++ {
Pack(data, buff)
Encode(data, buff)
}
b.StopTimer()
}
Expand Down Expand Up @@ -310,15 +310,15 @@ func testBenchRead(b *testing.B, data, w interface{}, caseName string) {
}
}
func testBenchUnpack(b *testing.B, data, w interface{}, caseName string) {
buf, err := Pack(data, buff)
buf, err := Encode(data, buff)
if err != nil {
b.Error(caseName, err)
}
b.SetBytes(int64(len(buf)))

b.ResetTimer()
for i := 0; i < b.N; i++ {
Unpack(buf, w)
Decode(buf, w)
}
b.StopTimer()
if b.N > 0 && !reflect.DeepEqual(data, w) {
Expand Down
68 changes: 34 additions & 34 deletions coder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ func TestPack(t *testing.T) {
if !validField(vt.Field(i)) {
continue
}
b, err := Pack(v.Field(i).Interface(), nil)
b, err := Encode(v.Field(i).Interface(), nil)
c := check[:len(b)]
check = check[len(b):]
if err != nil {
Expand All @@ -363,7 +363,7 @@ func TestPack(t *testing.T) {

func TestUnpack(t *testing.T) {
var v fullStruct
err := Unpack(littleFullAll, &v)
err := Decode(littleFullAll, &v)
if err != nil {
t.Error(err)
}
Expand Down Expand Up @@ -450,18 +450,18 @@ func TestPackEmptyPointer(t *testing.T) {
PStruct *struct{ A int }
PStruct2 *struct{ B *[]string }
}
b, err := Pack(&s, nil)
b, err := Encode(&s, nil)
if err != nil {
t.Error(err)
}
ss := s

err = Unpack(b, &ss)
err = Decode(b, &ss)
if err != nil {
t.Error(err)
}

b2, err2 := Pack(&ss, nil)
b2, err2 := Encode(&ss, nil)
if err2 != nil {
t.Error(err)
}
Expand All @@ -486,7 +486,7 @@ func TestHideStructField(t *testing.T) {
s.b = 0x22334455
s.C = 0x33445566
check := []byte{0x44, 0x33, 0x22, 0x11}
b, err := Pack(s, nil)
b, err := Encode(s, nil)
if err != nil {
t.Error(err)
}
Expand All @@ -495,7 +495,7 @@ func TestHideStructField(t *testing.T) {
}
var ss, ssCheck T
ssCheck.A = s.A
err = Unpack(b, &ss)
err = Decode(b, &ss)
if err != nil {
t.Error(err)
}
Expand Down Expand Up @@ -577,12 +577,12 @@ func TestDecoderSkip(t *testing.T) {
}

var r [4]s
b, err := Pack(&w, nil)
b, err := Encode(&w, nil)
if err != nil {
t.Error(err)
}

err2 := Unpack(b, &r)
err2 := Decode(b, &r)
if err2 != nil {
t.Error(err2)
}
Expand Down Expand Up @@ -625,7 +625,7 @@ func TestFastValue(t *testing.T) {

func TestPackDonotSupportedType(t *testing.T) {
ts := doNotSupportTypes
if _, err := Pack(ts, nil); err == nil {
if _, err := Encode(ts, nil); err == nil {
t.Errorf("PackDonotSupportedType: have err == nil, want non-nil")
}

Expand All @@ -635,7 +635,7 @@ func TestPackDonotSupportedType(t *testing.T) {

tv := reflect.Indirect(reflect.ValueOf(&ts))
for i, n := 0, tv.NumField(); i < n; i++ {
if _, err := Pack(tv.Field(i).Interface(), nil); err == nil {
if _, err := Encode(tv.Field(i).Interface(), nil); err == nil {
t.Errorf("PackDonotSupportedType.%v: have err == nil, want non-nil", tv.Field(i).Type())
} else {
//fmt.Println(err)
Expand All @@ -647,7 +647,7 @@ func TestPackDonotSupportedType(t *testing.T) {
//fmt.Println(err)
}

if err := Unpack(buff, tv.Field(i).Addr().Interface()); err == nil {
if err := Decode(buff, tv.Field(i).Addr().Interface()); err == nil {
t.Errorf("Unpack DonotSupportedType.%v: have err == nil, want non-nil", tv.Field(i).Type())
} else {
//fmt.Printf("Unpack error: %#v\n%s\n", tv.Field(i).Addr().Type().String(), err.Error())
Expand Down Expand Up @@ -726,14 +726,14 @@ func TestRegStruct(t *testing.T) {
}
a.S.A = 9
a.S.B = "abc"
b, err := Pack(&a, nil)
b, err := Encode(&a, nil)
if err != nil {
t.Error(err)
}

var r StructForReg
//fmt.Printf("%#v\n%#v\n", a, b)
err = Unpack(b, &r)
err = Decode(b, &r)
if err != nil {
t.Error(err)
}
Expand Down Expand Up @@ -787,50 +787,50 @@ type sizerOnly struct{ A uint8 }

func (this sizerOnly) Size() int { return 1 }

type packerOnly struct{ B uint8 }
type encoderOnly struct{ B uint8 }

func (this packerOnly) Pack(buffer []byte) ([]byte, error) { return nil, nil }
func (this encoderOnly) Encode(buffer []byte) ([]byte, error) { return nil, nil }

type unpackerOnly struct {
type decoderOnly struct {
C uint8
}

func (this *unpackerOnly) Unpack(buffer []byte) error { return nil }
func (this *decoderOnly) Decode(buffer []byte) error { return nil }

type sizepackerOnly struct {
sizerOnly
packerOnly
encoderOnly
}
type sizeunpackerOnly struct {
sizerOnly
unpackerOnly
decoderOnly
}
type packunpackerOnly struct {
packerOnly
unpackerOnly
encoderOnly
decoderOnly
}
type fullPackUnpacker struct {
type fullSerializer struct {
sizerOnly
packerOnly
unpackerOnly
encoderOnly
decoderOnly
}
type fullPackUnpackerUnpackerror struct {
fullPackUnpacker
type fullSerializerError struct {
fullSerializer
}

func (this *fullPackUnpackerUnpackerror) Unpack(buffer []byte) error {
func (this *fullSerializerError) Decode(buffer []byte) error {
return fmt.Errorf("expected error")
}

func TestPackUnpacker(t *testing.T) {
var a sizerOnly
var b packerOnly
var c unpackerOnly
var b encoderOnly
var c decoderOnly
var d sizepackerOnly
var e sizeunpackerOnly
var f packunpackerOnly
var g fullPackUnpackerUnpackerror
var h fullPackUnpacker
var g fullSerializerError
var h fullSerializer

testCase := func(data interface{}, testcase int) (info interface{}) {
defer func() {
Expand All @@ -845,13 +845,13 @@ func TestPackUnpacker(t *testing.T) {
case 1:
Sizeof(data)
case 2:
if _, err := Pack(data, nil); err != nil {
if _, err := Encode(data, nil); err != nil {
info = err
}

case 3:
buff := make([]byte, 1000)
if err := Unpack(buff, data); err != nil {
if err := Decode(buff, data); err != nil {
info = err
}
case 4:
Expand Down
28 changes: 14 additions & 14 deletions decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ func (this *Decoder) Uvarint() (uint64, int) {
// x must be interface of pointer for modify.
// It will return none-nil error if x contains unsupported types
// or buffer is not enough.
// It will check if x implements interface Unpacker and use x.Unpack first.
// It will check if x implements interface BinaryEncoder and use x.Encode first.
func (this *Decoder) Value(x interface{}) (err error) {
defer func() {
if info := recover(); info != nil {
Expand All @@ -234,28 +234,28 @@ func (this *Decoder) Value(x interface{}) (err error) {

v := reflect.ValueOf(x)

if p, ok := x.(Unpacker); ok {
if p, ok := x.(BinaryDecoder); ok {
size := 0
if sizer, _ok := x.(Sizer); _ok { //interface verification
if sizer, _ok := x.(BinarySizer); _ok { //interface verification
size = sizer.Size()
} else {
panic(fmt.Errorf("expect but not Sizer: %s", v.Type().String()))
panic(fmt.Errorf("expect but not BinarySizer: %s", v.Type().String()))
}
if _, _ok := x.(Packer); !_ok { //interface verification
panic(fmt.Errorf("unexpect but not Packer: %s", v.Type().String()))
if _, _ok := x.(BinaryEncoder); !_ok { //interface verification
panic(fmt.Errorf("unexpect but not BinaryEncoder: %s", v.Type().String()))
}
err := p.Unpack(this.buff[this.pos:])
err := p.Decode(this.buff[this.pos:])
if err != nil {
return err
}
this.reserve(size)
return nil
} else {
if _, _ok := x.(Sizer); _ok { //interface verification
panic(fmt.Errorf("unexpected Sizer: %s", v.Type().String()))
if _, _ok := x.(BinarySizer); _ok { //interface verification
panic(fmt.Errorf("unexpected BinarySizer: %s", v.Type().String()))
}
if _, _ok := x.(Packer); _ok { //interface verification
panic(fmt.Errorf("unexpected Packer: %s", v.Type().String()))
if _, _ok := x.(BinaryEncoder); _ok { //interface verification
panic(fmt.Errorf("unexpected BinaryEncoder: %s", v.Type().String()))
}
}

Expand Down Expand Up @@ -338,7 +338,7 @@ func (this *Decoder) value(v reflect.Value, topLevel bool) error {
v.SetString(this.String())

case reflect.Slice, reflect.Array:
if sizeofNilPointer(v.Type().Elem()) < 0 { //verify array element is valid
if !validUserType(v.Type().Elem()) { //verify array element is valid
return fmt.Errorf("binary.Decoder.Value: unsupported type %s", v.Type().String())
}
if this.boolArray(v) < 0 { //deal with bool array first
Expand All @@ -362,8 +362,8 @@ func (this *Decoder) value(v reflect.Value, topLevel bool) error {
t := v.Type()
kt := t.Key()
vt := t.Elem()
if sizeofNilPointer(kt) < 0 ||
sizeofNilPointer(vt) < 0 { //verify map key and value type are both valid
if !validUserType(kt) ||
!validUserType(vt) { //verify map key and value type are both valid
return fmt.Errorf("binary.Decoder.Value: unsupported type %s", v.Type().String())
}

Expand Down
Loading

0 comments on commit b47d83d

Please sign in to comment.