diff --git a/message.go b/message.go index a5a7fa4d..4779f40c 100644 --- a/message.go +++ b/message.go @@ -1,10 +1,9 @@ package nsq import ( - "bytes" "encoding/binary" + "errors" "io" - "io/ioutil" "sync/atomic" "time" ) @@ -139,24 +138,27 @@ func (m *Message) WriteTo(w io.Writer) (int64, error) { return total, nil } -// DecodeMessage deseralizes data (as []byte) and creates a new Message +// DecodeMessage deserializes data (as []byte) and creates a new Message +// message format: +// [x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x][x]... +// | (int64) || || (hex string encoded in ASCII) || (binary) +// | 8-byte || || 16-byte || N-byte +// ------------------------------------------------------------------------------------------... +// nanosecond timestamp ^^ message ID message body +// (uint16) +// 2-byte +// attempts func DecodeMessage(b []byte) (*Message, error) { var msg Message - msg.Timestamp = int64(binary.BigEndian.Uint64(b[:8])) - msg.Attempts = binary.BigEndian.Uint16(b[8:10]) - - buf := bytes.NewBuffer(b[10:]) - - _, err := io.ReadFull(buf, msg.ID[:]) - if err != nil { - return nil, err + if len(b) < 10+MsgIDLength { + return nil, errors.New("not enough data to decode valid message") } - msg.Body, err = ioutil.ReadAll(buf) - if err != nil { - return nil, err - } + msg.Timestamp = int64(binary.BigEndian.Uint64(b[:8])) + msg.Attempts = binary.BigEndian.Uint16(b[8:10]) + copy(msg.ID[:], b[10:10+MsgIDLength]) + msg.Body = b[10+MsgIDLength:] return &msg, nil }