Skip to content

Commit

Permalink
refactor: clean up code
Browse files Browse the repository at this point in the history
  • Loading branch information
cooldogedev committed Jun 30, 2024
1 parent 458e799 commit 5cfe35b
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 17 deletions.
18 changes: 6 additions & 12 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,22 +30,18 @@ func NewClient(conn net.Conn, pool packet.Pool) *Client {
}

func (c *Client) ReadPacket() (pk packet.Packet, err error) {
payload, err := c.reader.ReadPacket()
if err != nil {
return nil, err
}

buf := internal.BufferPool.Get().(*bytes.Buffer)
buf.Write(payload)
defer func() {
buf.Reset()
internal.BufferPool.Put(buf)

if r := recover(); r != nil {
err = fmt.Errorf("panic while decoding packet: %v", r)
}
}()

payload, err := c.reader.ReadPacket()
if err != nil {
return nil, err
}

buf := bytes.NewBuffer(payload)
var packetID uint32
if err := binary.Read(buf, binary.LittleEndian, &packetID); err != nil {
return nil, err
Expand All @@ -55,7 +51,6 @@ func (c *Client) ReadPacket() (pk packet.Packet, err error) {
if !ok {
return nil, fmt.Errorf("unknown packet ID: %v", packetID)
}

pk = factory()
pk.Decode(buf)
return
Expand All @@ -71,7 +66,6 @@ func (c *Client) WritePacket(pk packet.Packet) error {
if err := binary.Write(buf, binary.LittleEndian, pk.ID()); err != nil {
return err
}

pk.Encode(buf)
return c.writer.Write(buf.Bytes())
}
Expand Down
6 changes: 1 addition & 5 deletions server/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,17 +238,13 @@ func (c *Conn) read(decode bool) (any, error) {

// decode decodes a packet payload and returns the decoded packet or an error if the packet could not be decoded.
func (c *Conn) decode(payload []byte) (pk packet.Packet, err error) {
buf := internal.BufferPool.Get().(*bytes.Buffer)
buf.Write(payload)
defer func() {
buf.Reset()
internal.BufferPool.Put(buf)

if r := recover(); r != nil {
err = fmt.Errorf("panic while reading packet: %v", r)
}
}()

buf := bytes.NewBuffer(payload)
header := &packet.Header{}
if err := header.Read(buf); err != nil {
return nil, err
Expand Down

0 comments on commit 5cfe35b

Please sign in to comment.