Skip to content
This repository has been archived by the owner on Apr 5, 2024. It is now read-only.

Commit

Permalink
TCPCL: Keepalive/Session Upkeep Message
Browse files Browse the repository at this point in the history
  • Loading branch information
oxzi committed Sep 5, 2019
1 parent d7215a3 commit c9fd2e6
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
44 changes: 44 additions & 0 deletions cla/tcpcl/message_keepalive.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package tcpcl

import "fmt"

// KEEPALIVE is the Message Header code for a Keepalive Message.
const KEEPALIVE uint8 = 0x04

// KeepaliveMessage is the KEEPALIVE message for session upkeep.
type KeepaliveMessage uint8

// NewKeepaliveMessage creates a new KeepaliveMessage.
func NewKeepaliveMessage() KeepaliveMessage {
return KeepaliveMessage(KEEPALIVE)
}

func (_ KeepaliveMessage) String() string {
return "KEEPALIVE"
}

// MarshalBinary encodes this KeepaliveMessage into its binary form.
func (km KeepaliveMessage) MarshalBinary() (data []byte, err error) {
if uint8(km) != KEEPALIVE {
err = fmt.Errorf("KEEPALIVE's value is %d instead of %d", uint8(km), KEEPALIVE)
return
}

data = []byte{KEEPALIVE}
return
}

// UnmarshalBinary decodes a KeepaliveMessage from its binary form.
func (km *KeepaliveMessage) UnmarshalBinary(data []byte) error {
if len(data) != 1 {
return fmt.Errorf("KEEPALIVE's octet length is %d instead of 1", len(data))
}

if x := uint8(data[0]); x != KEEPALIVE {
return fmt.Errorf("KEEPALIVE's value is %d instead of %d", x, KEEPALIVE)
} else {
*km = KeepaliveMessage(x)
}

return nil
}
35 changes: 35 additions & 0 deletions cla/tcpcl/message_keepalive_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package tcpcl

import (
"bytes"
"testing"
)

func TestKeepaliveMessage(t *testing.T) {
tests := []struct {
valid bool
data []byte
}{
{true, []byte{KEEPALIVE}},
{false, []byte{0x21}},
{false, []byte{}},
{false, []byte{0x23, 0x42}},
}

for _, test := range tests {
var km KeepaliveMessage

if err := km.UnmarshalBinary(test.data); (err == nil) != test.valid {
t.Fatalf("Error state was not expected; valid := %t, got := %v", test.valid, err)
} else if !test.valid {
continue
}

if data, err := NewKeepaliveMessage().MarshalBinary(); err != nil {
t.Fatal(err)
} else if !bytes.Equal(data, test.data) {
t.Fatalf("Data does not match, expected %x and got %x", test.data, data)
}

}
}

0 comments on commit c9fd2e6

Please sign in to comment.