Make use of direct byte encoding / decoding

With the lates github.com/abcum/cork package, it is now possible to encode and decode a cork data stream without creating a new buffer each time. Instead the github.com/abcum/bump pacakge efficiently buffers the byte slice without any unnecessary allocations.
This commit is contained in:
Tobie Morgan Hitchcock 2017-11-16 19:44:46 +00:00
parent 44591abfe5
commit 0ce8e78577

View file

@ -15,30 +15,35 @@
package pack package pack
import ( import (
"bytes"
"github.com/abcum/cork" "github.com/abcum/cork"
) )
var opt = cork.Handle{ var opt = cork.Handle{
Precision: false, SortMaps: true,
ArrType: make([]interface{}, 0), ArrType: make([]interface{}, 0),
MapType: make(map[string]interface{}), MapType: make(map[string]interface{}),
} }
// Encode encodes a data object into a CORK. // Encode encodes a data object into a CORK.
func Encode(src interface{}) (dst []byte) { func Encode(src interface{}) (dst []byte) {
buf := bytes.NewBuffer(nil) enc := cork.NewEncoderBytesFromPool(&dst)
enc := cork.NewEncoderFromPool(buf).Options(&opt) enc.Options(&opt)
enc.Encode(src) err := enc.Encode(src)
enc.Done() enc.Reset()
return buf.Bytes() if err != nil {
panic(err)
}
return
} }
// Decode decodes a CORK into a data object. // Decode decodes a CORK into a data object.
func Decode(src []byte, dst interface{}) { func Decode(src []byte, dst interface{}) {
buf := bytes.NewReader(src) dec := cork.NewDecoderBytesFromPool(src)
dec := cork.NewDecoderFromPool(buf).Options(&opt) dec.Options(&opt)
dec.Decode(dst) err := dec.Decode(dst)
dec.Done() dec.Reset()
if err != nil {
panic(err)
}
return return
} }