nsqio / go-nsq

The official Go package for NSQ
MIT License
2.59k stars 444 forks source link

DecodeMessage: skip bytes Buffer, reducing alloc overhead #175

Closed Dieterbe closed 8 years ago

Dieterbe commented 8 years ago

see https://github.com/nsqio/go-nsq/issues/174#issuecomment-210256321 for more discussion and before and after

mreiferson commented 8 years ago

restarted that one test failure, just looks like a flakey test

mreiferson commented 8 years ago

green light, thanks @Dieterbe

If you don't mind addressing that one comment and squashing in, this LGTM!

twmb commented 8 years ago
package nsq

import (
    "bytes"
    "math/rand"
    "reflect"
    "sync"
    "testing"
    "testing/quick"
    "time"
)

var quickID = func() func() MessageID {
    t := reflect.TypeOf(MessageID{})
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    var m sync.Mutex
    return func() MessageID {
        m.Lock()
        v, _ := quick.Value(t, r)
        m.Unlock()
        return v.Interface().(MessageID)
    }
}()

func TestDecodeMessage(t *testing.T) {
    // Create our message: nsqd rejects length 0 messages.
    message := NewMessage(quickID(), make([]byte, 1))
    // Encode the message.
    buf := new(bytes.Buffer)
    message.WriteTo(buf)
    encoded := buf.Bytes()
    // We expect a valid, min length message to decode idempotently.
    decodeRight, err := DecodeMessage(encoded)
    if err != nil {
        t.Errorf("expected idempotent encode/decode, got err: %v", err)
    }
    if !reflect.DeepEqual(message, decodeRight) {
        t.Error("expected idempotent encode/decode, not")
    }
    // We expect a message with no body to not decode.
    encoded = encoded[:len(encoded)-1] // trim the 1 byte body
    _, err = DecodeMessage(encoded)
    if err == nil {
        t.Error("expected invalid encode to not decode")
    }
}

TIL that nsqd rejects length 0 messages.