From 9df5a3d0d532f99ceaef3d0ea77552fe5c380c8f Mon Sep 17 00:00:00 2001 From: CPunch Date: Wed, 22 Nov 2023 18:18:22 -0600 Subject: [PATCH] start packet_test.go; minor packet.go refactoring --- internal/protocol/packet.go | 14 ++++++------- internal/protocol/packet_test.go | 35 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 8 deletions(-) create mode 100644 internal/protocol/packet_test.go diff --git a/internal/protocol/packet.go b/internal/protocol/packet.go index 42dce7f..21207ca 100644 --- a/internal/protocol/packet.go +++ b/internal/protocol/packet.go @@ -61,10 +61,9 @@ func (pkt Packet) encodeStructField(field reflect.StructField, value reflect.Val // write padding bytes pad, err := strconv.Atoi(field.Tag.Get("pad")) if err == nil { - for i := 0; i < pad; i++ { - if _, err := pkt.readWriter.Write([]byte{0}); err != nil { - return err - } + dummy := make([]byte, pad) + if _, err := pkt.readWriter.Write(dummy); err != nil { + return err } } @@ -126,10 +125,9 @@ func (pkt Packet) decodeStructField(field reflect.StructField, value reflect.Val // consume padding bytes pad, err := strconv.Atoi(field.Tag.Get("pad")) if err == nil { - for i := 0; i < pad; i++ { - if _, err := pkt.readWriter.Read([]byte{0}); err != nil { - return err - } + dummy := make([]byte, pad) + if _, err := pkt.readWriter.Read(dummy); err != nil { + return err } } diff --git a/internal/protocol/packet_test.go b/internal/protocol/packet_test.go new file mode 100644 index 0000000..dc690eb --- /dev/null +++ b/internal/protocol/packet_test.go @@ -0,0 +1,35 @@ +package protocol + +import ( + "bytes" + "testing" +) + +type TestPacketData struct { + A int32 + B int32 + UTF16Str string `size:"32"` + Pad int16 `pad:"2"` + C int32 +} + +func TestPacket(t *testing.T) { + pkt := NewPacket(&bytes.Buffer{}) + if err := pkt.Encode(TestPacketData{ + A: 1, + B: 2, + UTF16Str: "hello world", + C: 3, + }); err != nil { + t.Error(err) + } + + var test TestPacketData + if err := pkt.Decode(&test); err != nil { + t.Error(err) + } + + if test.A != 1 || test.B != 2 || test.C != 3 || test.UTF16Str != "hello world" { + t.Error("packet data does not match!") + } +}