From 9209dcfa26e8f7ffea454a77b09f443eafd6b839 Mon Sep 17 00:00:00 2001 From: Alexander Neumann Date: Sat, 23 Jan 2016 23:41:55 +0100 Subject: [PATCH] Add LoadAll() --- backend/utils.go | 18 ++++++++++++++++++ backend/utils_test.go | 44 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 backend/utils.go create mode 100644 backend/utils_test.go diff --git a/backend/utils.go b/backend/utils.go new file mode 100644 index 000000000..c40d35e12 --- /dev/null +++ b/backend/utils.go @@ -0,0 +1,18 @@ +package backend + +// LoadAll reads all data stored in the backend for the handle. The buffer buf +// is resized to accomodate all data in the blob. +func LoadAll(be Backend, h Handle, buf []byte) ([]byte, error) { + fi, err := be.Stat(h) + if err != nil { + return nil, err + } + + if fi.Size > int64(len(buf)) { + buf = make([]byte, int(fi.Size)) + } + + n, err := be.Load(h, buf, 0) + buf = buf[:n] + return buf, err +} diff --git a/backend/utils_test.go b/backend/utils_test.go new file mode 100644 index 000000000..426f866de --- /dev/null +++ b/backend/utils_test.go @@ -0,0 +1,44 @@ +package backend_test + +import ( + "bytes" + "math/rand" + "testing" + + "github.com/restic/restic/backend" + "github.com/restic/restic/backend/mem" + . "github.com/restic/restic/test" +) + +const KiB = 1 << 10 +const MiB = 1 << 20 + +func TestLoadAll(t *testing.T) { + b := mem.New() + + for i := 0; i < 20; i++ { + data := Random(23+i, rand.Intn(MiB)+500*KiB) + + id := backend.Hash(data) + + blob, err := b.Create() + OK(t, err) + + _, err = blob.Write([]byte(data)) + OK(t, err) + OK(t, blob.Finalize(backend.Data, id.String())) + + buf, err := backend.LoadAll(b, backend.Handle{Type: backend.Data, Name: id.String()}, nil) + OK(t, err) + + if len(buf) != len(data) { + t.Errorf("length of returned buffer does not match, want %d, got %d", len(data), len(buf)) + continue + } + + if !bytes.Equal(buf, data) { + t.Errorf("wrong data returned") + continue + } + } +}