diff options
Diffstat (limited to 'pkg')
| -rw-r--r-- | pkg/image/compression.go | 17 | ||||
| -rw-r--r-- | pkg/image/compression_test.go | 31 |
2 files changed, 28 insertions, 20 deletions
diff --git a/pkg/image/compression.go b/pkg/image/compression.go index 9878b460d..a2a51b146 100644 --- a/pkg/image/compression.go +++ b/pkg/image/compression.go @@ -9,6 +9,7 @@ import ( "encoding/base64" "fmt" "io" + "io/ioutil" ) func Compress(rawData []byte) []byte { @@ -28,14 +29,20 @@ func Compress(rawData []byte) []byte { return buffer.Bytes() } -func Decompress(compressedData []byte) ([]byte, error) { +func MustDecompress(compressed []byte) (data []byte, dtor func()) { buf := new(bytes.Buffer) - err := DecompressWriter(buf, compressedData) - return buf.Bytes(), err + if err := decompressWriter(buf, compressed); err != nil { + panic(err) + } + return buf.Bytes(), func() {} +} + +func DecompressCheck(compressed []byte) error { + return decompressWriter(ioutil.Discard, compressed) } -func DecompressWriter(w io.Writer, compressedData []byte) error { - zlibReader, err := zlib.NewReader(bytes.NewReader(compressedData)) +func decompressWriter(w io.Writer, compressed []byte) error { + zlibReader, err := zlib.NewReader(bytes.NewReader(compressed)) if err != nil { return fmt.Errorf("could not initialise zlib: %v", err) } diff --git a/pkg/image/compression_test.go b/pkg/image/compression_test.go index cf18ed340..0107f82aa 100644 --- a/pkg/image/compression_test.go +++ b/pkg/image/compression_test.go @@ -13,32 +13,33 @@ import ( ) func TestCompress(t *testing.T) { + t.Parallel() r := rand.New(testutil.RandSource(t)) - err := testRoundTrip(r, Compress, Decompress) - if err != nil { - t.Fatalf("compress/decompress %v", err) + for i := 0; i < testutil.IterCount(); i++ { + t.Run(fmt.Sprint(i), func(t *testing.T) { + randBytes := testutil.RandMountImage(r) + resultBytes := Compress(randBytes) + resultBytes, dtor := MustDecompress(resultBytes) + defer dtor() + if !bytes.Equal(randBytes, resultBytes) { + t.Fatalf("roundtrip changes data (length %v->%v)", len(randBytes), len(resultBytes)) + } + }) } } func TestEncode(t *testing.T) { + t.Parallel() r := rand.New(testutil.RandSource(t)) - err := testRoundTrip(r, EncodeB64, DecodeB64) - if err != nil { - t.Fatalf("encode/decode Base64 %v", err) - } -} - -func testRoundTrip(r *rand.Rand, transform func([]byte) []byte, inverse func([]byte) ([]byte, error)) error { for i := 0; i < testutil.IterCount(); i++ { randBytes := testutil.RandMountImage(r) - resultBytes := transform(randBytes) - resultBytes, err := inverse(resultBytes) + resultBytes := EncodeB64(randBytes) + resultBytes, err := DecodeB64(resultBytes) if err != nil { - return err + t.Fatalf("decoding failed: %v", err) } if !bytes.Equal(randBytes, resultBytes) { - return fmt.Errorf("roundtrip changes data (original length %d)", len(randBytes)) + t.Fatalf("roundtrip changes data (original length %d)", len(randBytes)) } } - return nil } |
