github.com/ledgerwatch/erigon-lib@v1.0.0/compress/compress_fuzz_test.go (about)

     1  //go:build !nofuzz
     2  
     3  /*
     4  Copyright 2021 Erigon contributors
     5  
     6  Licensed under the Apache License, Version 2.0 (the "License");
     7  you may not use this file except in compliance with the License.
     8  You may obtain a copy of the License at
     9  
    10  	http://www.apache.org/licenses/LICENSE-2.0
    11  
    12  Unless required by applicable law or agreed to in writing, software
    13  distributed under the License is distributed on an "AS IS" BASIS,
    14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    15  See the License for the specific language governing permissions and
    16  limitations under the License.
    17  */
    18  package compress
    19  
    20  import (
    21  	"context"
    22  	"fmt"
    23  	"math/rand"
    24  	"path/filepath"
    25  	"testing"
    26  
    27  	"github.com/ledgerwatch/erigon-lib/common/cmp"
    28  	"github.com/ledgerwatch/log/v3"
    29  )
    30  
    31  func FuzzCompress(f *testing.F) {
    32  	logger := log.New()
    33  	f.Fuzz(func(t *testing.T, x []byte, pos []byte, workers int8) {
    34  		t.Helper()
    35  		t.Parallel()
    36  		if len(pos) < 1 || workers < 1 {
    37  			t.Skip()
    38  			return
    39  		}
    40  		var a [][]byte
    41  		j := 0
    42  		for i := 0; i < len(pos) && j < len(x); i++ {
    43  			if pos[i] == 0 {
    44  				continue
    45  			}
    46  			next := cmp.Min(j+int(pos[i]*10), len(x)-1)
    47  			bbb := x[j:next]
    48  			a = append(a, bbb)
    49  			j = next
    50  		}
    51  
    52  		ctx := context.Background()
    53  		tmpDir := t.TempDir()
    54  		file := filepath.Join(tmpDir, fmt.Sprintf("compressed-%d", rand.Int31()))
    55  		c, err := NewCompressor(ctx, t.Name(), file, tmpDir, 2, int(workers), log.LvlDebug, logger)
    56  		if err != nil {
    57  			t.Fatal(err)
    58  		}
    59  		defer c.Close()
    60  		for _, b := range a {
    61  			if err = c.AddWord(b); err != nil {
    62  				t.Fatal(err)
    63  			}
    64  		}
    65  		if err = c.Compress(); err != nil {
    66  			t.Fatal(err)
    67  		}
    68  		c.Close()
    69  		d, err := NewDecompressor(file)
    70  		if err != nil {
    71  			t.Fatal(err)
    72  		}
    73  		defer d.Close()
    74  		g := d.MakeGetter()
    75  		buf := make([]byte, 0, 100)
    76  		for g.HasNext() {
    77  			buf, _ = g.Next(buf[:0])
    78  		}
    79  	})
    80  }