From c6e685964f0a0d643b50f7b9297d893bd890603c Mon Sep 17 00:00:00 2001 From: Lukas Herman Date: Fri, 15 May 2020 00:35:57 -0400 Subject: [PATCH] Fix wrong required size --- pkg/io/io.go | 2 +- pkg/io/io_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 pkg/io/io_test.go diff --git a/pkg/io/io.go b/pkg/io/io.go index d235335..26f3216 100644 --- a/pkg/io/io.go +++ b/pkg/io/io.go @@ -4,7 +4,7 @@ package io // InsufficientBufferError. func Copy(dst, src []byte) (n int, err error) { if len(dst) < len(src) { - return 0, &InsufficientBufferError{len(dst)} + return 0, &InsufficientBufferError{len(src)} } return copy(dst, src), nil diff --git a/pkg/io/io_test.go b/pkg/io/io_test.go new file mode 100644 index 0000000..047e3a1 --- /dev/null +++ b/pkg/io/io_test.go @@ -0,0 +1,45 @@ +package io + +import ( + "log" + "testing" +) + +func TestCopy(t *testing.T) { + var dst []byte + src := make([]byte, 4) + + n, err := Copy(dst, src) + if err == nil { + t.Fatal("expected err to be non-nill") + } + + if n != 0 { + t.Fatalf("expected n to be 0, but got %d", n) + } + + e, ok := err.(*InsufficientBufferError) + if !ok { + t.Fatalf("expected error to be InsufficientBufferError") + } + + if e.RequiredSize != len(src) { + t.Fatalf("expected required size to be %d, but got %d", len(src), e.RequiredSize) + } + + dst = make([]byte, 2*e.RequiredSize) + n, err = Copy(dst, src) + if err != nil { + t.Fatalf("expected to not get an error after expanding the buffer") + } + + if n != len(src) { + t.Fatalf("expected n to be %d, but got %d", len(src), n) + } + + for i := 0; i < len(src); i++ { + if src[i] != dst[i] { + log.Fatalf("expected value at %d to be %d, but got %d", i, src[i], dst[i]) + } + } +}