structs: adding encode and decode

This commit is contained in:
Armon Dadgar
2015-06-06 00:21:17 +02:00
parent 5605fea9fa
commit 23172133f2
2 changed files with 55 additions and 0 deletions

View File

@@ -1,5 +1,11 @@
package structs
import (
"bytes"
"github.com/hashicorp/go-msgpack/codec"
)
type MessageType uint8
const (
@@ -14,3 +20,19 @@ const (
// old servers to crash when the FSM attempts to process them.
IgnoreUnknownTypeFlag MessageType = 128
)
// msgpackHandle is a shared handle for encoding/decoding of structs
var msgpackHandle = &codec.MsgpackHandle{}
// Decode is used to decode a MsgPack encoded object
func Decode(buf []byte, out interface{}) error {
return codec.NewDecoder(bytes.NewReader(buf), msgpackHandle).Decode(out)
}
// Encode is used to encode a MsgPack object with type prefix
func Encode(t MessageType, msg interface{}) ([]byte, error) {
var buf bytes.Buffer
buf.WriteByte(uint8(t))
err := codec.NewEncoder(&buf, msgpackHandle).Encode(msg)
return buf.Bytes(), err
}

View File

@@ -0,0 +1,33 @@
package structs
import (
"reflect"
"testing"
)
func TestEncodeDecode(t *testing.T) {
type FooRequest struct {
Foo string
Bar int
Baz bool
}
arg := &FooRequest{
Foo: "test",
Bar: 42,
Baz: true,
}
buf, err := Encode(1, arg)
if err != nil {
t.Fatalf("err: %v", err)
}
var out FooRequest
err = Decode(buf[1:], &out)
if err != nil {
t.Fatalf("err: %v", err)
}
if !reflect.DeepEqual(arg, &out) {
t.Fatalf("bad: %#v %#v", arg, out)
}
}