From c49ccaee639efae8b8249272a79e700e2c1954c6 Mon Sep 17 00:00:00 2001 From: Hrutvik Kanabar Date: Fri, 21 Oct 2022 15:34:55 +0000 Subject: prog: add (de)compression wrappers Add the file `compression.go`, with entry points for compressing/decompressing using `zlib`, and encoding/decoding Base64. Also add roundtrip compress/decompress and encode/decode tests. --- prog/compression_test.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 prog/compression_test.go (limited to 'prog/compression_test.go') diff --git a/prog/compression_test.go b/prog/compression_test.go new file mode 100644 index 000000000..b46f70999 --- /dev/null +++ b/prog/compression_test.go @@ -0,0 +1,50 @@ +// Copyright 2022 syzkaller project authors. All rights reserved. +// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. + +package prog + +import ( + "bytes" + "fmt" + "math/rand" + "testing" +) + +func TestCompress(t *testing.T) { + r := rand.New(randSource(t)) + err := testRoundTrip(r, Compress, Decompress) + if err != nil { + t.Fatalf("compress/decompress %v", err) + } +} + +func TestEncode(t *testing.T) { + r := rand.New(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 < iterCount(); i++ { + randBytes := randomBytes(r) + resultBytes := transform(randBytes) + resultBytes, err := inverse(resultBytes) + if err != nil { + return err + } + if !bytes.Equal(randBytes, resultBytes) { + return fmt.Errorf("roundtrip changes data (original length %d)", len(randBytes)) + } + } + return nil +} + +func randomBytes(r *rand.Rand) []byte { + const maxLen = 1 << 20 // 1 MB. + len := r.Intn(maxLen) + slice := make([]byte, len) + r.Read(slice) + return slice +} -- cgit mrf-deployment