refactor: remove MakeFromBytes() function which is almost the same as ReadBinary()

This commit is contained in:
Bryan Boreham
2019-09-16 16:44:38 +00:00
parent 3f8ba95bea
commit 2bbd4a3f0d
3 changed files with 10 additions and 33 deletions

View File

@@ -1,6 +1,7 @@
package multitenant
import (
"bytes"
"fmt"
"net"
"sort"
@@ -183,13 +184,14 @@ func (c *MemcacheClient) FetchReports(ctx context.Context, keys []string) (map[s
continue
}
go func(key string) {
rep, err := report.MakeFromBytes(item.Value)
rep := report.MakeReport()
err := rep.ReadBinary(ctx, bytes.NewBuffer(item.Value), true, true)
if err != nil {
log.Warningf("Corrupt report in memcache %v: %v", key, err)
ch <- result{key: key}
return
}
ch <- result{key: key, report: rep}
ch <- result{key: key, report: &rep}
}(key)
}

View File

@@ -129,33 +129,6 @@ func (rep *Report) ReadBytes(buf []byte, codecHandle codec.Handle) error {
return codec.NewDecoderBytes(buf, codecHandle).Decode(&rep)
}
// MakeFromBytes constructs a Report from a gzipped msgpack.
func MakeFromBytes(buf []byte) (*Report, error) {
compressedSize := len(buf)
r, err := gzip.NewReader(bytes.NewBuffer(buf))
if err != nil {
return nil, err
}
buffer := bufferPool.Get().(*bytes.Buffer)
buffer.Reset()
defer bufferPool.Put(buffer)
uncompressedSize, err := buffer.ReadFrom(r)
if err != nil {
return nil, err
}
log.Debugf(
"Received report sizes: compressed %d bytes, uncompressed %d bytes (%.2f%%)",
compressedSize,
uncompressedSize,
float32(compressedSize)/float32(uncompressedSize)*100,
)
rep := MakeReport()
if err := rep.ReadBytes(buffer.Bytes(), &codec.MsgpackHandle{}); err != nil {
return nil, err
}
return &rep, nil
}
// MakeFromFile construct a Report from a file, with the encoding
// determined by the extension (".msgpack" or ".json", with an
// optional ".gz").

View File

@@ -1,6 +1,7 @@
package report_test
import (
"bytes"
"context"
"reflect"
"testing"
@@ -14,7 +15,7 @@ import (
func TestRoundtrip(t *testing.T) {
r1 := report.MakeReport()
buf, _ := r1.WriteBinary()
bytes := append([]byte{}, buf.Bytes()...) // copy the contents for later
original := append([]byte{}, buf.Bytes()...) // copy the contents for later
r2, err := report.MakeFromBinary(context.Background(), buf)
if err != nil {
t.Error(err)
@@ -22,12 +23,13 @@ func TestRoundtrip(t *testing.T) {
if !reflect.DeepEqual(r1, *r2) {
t.Errorf("%v != %v", r1, *r2)
}
r3, err := report.MakeFromBytes(bytes)
r3 := report.MakeReport()
err = r3.ReadBinary(context.Background(), bytes.NewBuffer(original), true, true)
if err != nil {
t.Error(err)
}
if !reflect.DeepEqual(r1, *r3) {
t.Errorf("%v != %v", r1, *r3)
if !reflect.DeepEqual(r1, r3) {
t.Errorf("%v != %v", r1, r3)
}
}