Skip to content

Commit

Permalink
added registermessages (#191)
Browse files Browse the repository at this point in the history
* added registermessages

* updated comments
  • Loading branch information
ineiti authored and nikkolasg committed May 31, 2017
1 parent f6d891a commit e2fa132
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
12 changes: 12 additions & 0 deletions network/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,18 @@ func RegisterMessage(msg Message) MessageTypeID {
return msgType
}

// RegisterMessages is a convenience function to register multiple messages
// together. It returns the MessageTypeIDs of the registered messages. If you
// give the same message more than once, it will register it only once, but return
// it's id as many times as it appears in the arguments.
func RegisterMessages(msg ...Message) []MessageTypeID {
var ret []MessageTypeID
for _, m := range msg {
ret = append(ret, RegisterMessage(m))
}
return ret
}

func computeMessageType(msg Message) MessageTypeID {
val := reflect.ValueOf(msg)
if val.Kind() == reflect.Ptr {
Expand Down
30 changes: 21 additions & 9 deletions network/encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,49 @@ import (
"github.com/stretchr/testify/require"
)

type TestRegisterS struct {
type TestRegisterS1 struct {
I int
}
type TestRegisterS2 struct {
I int
}

func TestRegister(t *testing.T) {
if !MessageType(&TestRegisterS{}).Equal(ErrorType) {
func TestRegisterMessage(t *testing.T) {
if !MessageType(&TestRegisterS1{}).Equal(ErrorType) {
t.Fatal("TestRegister should not yet be there")
}

trType := RegisterMessage(&TestRegisterS{})
trType := RegisterMessage(&TestRegisterS1{})
if trType.IsNil() {
t.Fatal("Couldn't register TestRegister-struct")
}

if !MessageType(&TestRegisterS{}).Equal(trType) {
if !MessageType(&TestRegisterS1{}).Equal(trType) {
t.Fatal("TestRegister is different now")
}
if !MessageType(TestRegisterS{}).Equal(trType) {
if !MessageType(TestRegisterS1{}).Equal(trType) {
t.Fatal("TestRegister is different now")
}
}

func TestRegisterMessages(t *testing.T) {
oldRegistry := registry
registry = newTypeRegistry()
types := RegisterMessages(&TestRegisterS1{}, &TestRegisterS2{})
assert.True(t, MessageType(&TestRegisterS1{}).Equal(types[0]))
assert.True(t, MessageType(&TestRegisterS2{}).Equal(types[1]))
registry = oldRegistry
}

func TestUnmarshalRegister(t *testing.T) {
trType := RegisterMessage(&TestRegisterS{})
buff, err := Marshal(&TestRegisterS{10})
trType := RegisterMessage(&TestRegisterS1{})
buff, err := Marshal(&TestRegisterS1{10})
require.Nil(t, err)

ty, b, err := Unmarshal(buff)
assert.Nil(t, err)
assert.Equal(t, trType, ty)
assert.Equal(t, 10, b.(*TestRegisterS).I)
assert.Equal(t, 10, b.(*TestRegisterS1).I)

var randType [16]byte
rand.Read(randType[:])
Expand Down

0 comments on commit e2fa132

Please sign in to comment.