mirror of
https://github.com/kemko/nomad.git
synced 2026-01-01 16:05:42 +03:00
structs: adding encode and decode
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
33
nomad/structs/structs_test.go
Normal file
33
nomad/structs/structs_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user