Skip to content

Commit

Permalink
add Go-style documentation header
Browse files Browse the repository at this point in the history
  • Loading branch information
lim-yoona committed Oct 8, 2023
1 parent 1f9dee5 commit bc6d4f0
Showing 1 changed file with 13 additions and 0 deletions.
13 changes: 13 additions & 0 deletions msgpack.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,38 @@ import (
"net"
)

// IMsgPack is an interface that defined a packager,
// which carries HeadLen, and provides Pack() and Unpack() method.
type IMsgPack interface {
// Get the head length of the message package.
GetHeadLen() uint32
// Pack returns bytes stream packed from a message.
Pack(Imessage) ([]byte, error)
// Unpack returns a message from bytes stream.
Unpack() (Imessage, error)
}

// MsgPack implements the interface IMsgPack,
// carrying HeadLen and conn for Pack() and Unpack().
type MsgPack struct {
HeadLen uint32
conn net.Conn
}

// NewMsgPack returns a packager `*MsgPack`
func NewMsgPack(headlen uint32, conn net.Conn) *MsgPack {
return &MsgPack{
HeadLen: headlen,
conn: conn,
}
}

// GetHeadLen return HeadLen of the message.
func (mp *MsgPack) GetHeadLen() uint32 {
return mp.HeadLen
}

// Pack packs a message to bytes stream.
func (mp *MsgPack) Pack(msg Imessage) ([]byte, error) {
buffer := bytes.NewBuffer([]byte{})
if err := binary.Write(buffer, binary.LittleEndian, msg.GetDataLen()); err != nil {
Expand All @@ -43,6 +54,8 @@ func (mp *MsgPack) Pack(msg Imessage) ([]byte, error) {
}
return buffer.Bytes(), nil
}

// Unpack unpacks a certain length bytes stream to a message.
func (mp *MsgPack) Unpack() (Imessage, error) {
headDate := make([]byte, mp.GetHeadLen())
_, err := io.ReadFull(mp.conn, headDate)
Expand Down

0 comments on commit bc6d4f0

Please sign in to comment.