Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DecodeMessage: skip bytes Buffer, reducing alloc overhead #175

Merged
merged 2 commits into from
Apr 15, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 17 additions & 15 deletions message.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package nsq

import (
"bytes"
"encoding/binary"
"errors"
"io"
"io/ioutil"
"sync/atomic"
"time"
)
Expand Down Expand Up @@ -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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Docstring nitpick: message ID is binary w/r/t the protocol. Practically we chose to use ascii printable characters for now.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(if we want to reword that, that's in the official docs)

// | 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
}