From 23172133f2ce444e1ef2d555bb17fd22a06d9070 Mon Sep 17 00:00:00 2001 From: Armon Dadgar Date: Sat, 6 Jun 2015 00:21:17 +0200 Subject: [PATCH] structs: adding encode and decode --- nomad/structs/structs.go | 22 ++++++++++++++++++++++ nomad/structs/structs_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 nomad/structs/structs_test.go diff --git a/nomad/structs/structs.go b/nomad/structs/structs.go index fe467534c..33bac4f6c 100644 --- a/nomad/structs/structs.go +++ b/nomad/structs/structs.go @@ -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 +} diff --git a/nomad/structs/structs_test.go b/nomad/structs/structs_test.go new file mode 100644 index 000000000..d6e3dfd75 --- /dev/null +++ b/nomad/structs/structs_test.go @@ -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) + } +}