github.com/ledgerwatch/erigon-lib@v1.0.0/recsplit/recsplit_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 recsplit 19 20 import ( 21 "context" 22 "path/filepath" 23 "testing" 24 25 "github.com/ledgerwatch/log/v3" 26 ) 27 28 // go test -trimpath -v -fuzz=FuzzRecSplit -fuzztime=10s ./recsplit 29 30 func FuzzRecSplit(f *testing.F) { 31 logger := log.New() 32 f.Add(2, []byte("1stkey2ndkey")) 33 f.Fuzz(func(t *testing.T, count int, in []byte) { 34 if count < 1 { 35 t.Skip() 36 } 37 if len(in) < count { 38 t.Skip() 39 } 40 41 // split in into count keys 42 dups := make(map[string]struct{}) 43 // Length of one key 44 l := (len(in) + count - 1) / count 45 var i int 46 for i = 0; i < len(in)-l; i += l { 47 dups[string(in[i:i+l])] = struct{}{} 48 } 49 dups[string(in[i:])] = struct{}{} 50 if len(dups) != count { 51 t.Skip() 52 } 53 tmpDir := t.TempDir() 54 indexFile := filepath.Join(tmpDir, "index") 55 rs, err := NewRecSplit(RecSplitArgs{ 56 KeyCount: count, 57 Enums: true, 58 BucketSize: 10, 59 Salt: 0, 60 TmpDir: tmpDir, 61 IndexFile: indexFile, 62 LeafSize: 8, 63 }, logger) 64 if err != nil { 65 t.Fatal(err) 66 } 67 var off uint64 68 for i = 0; i < len(in)-l; i += l { 69 if err := rs.AddKey(in[i:i+l], off); err != nil { 70 t.Fatal(err) 71 } 72 off++ 73 } 74 if err := rs.AddKey(in[i:], off); err != nil { 75 t.Fatal(err) 76 } 77 if err = rs.Build(context.Background()); err != nil { 78 t.Fatal(err) 79 } 80 // Check that there is a bijection 81 idx := MustOpen(indexFile) 82 bitCount := (count + 63) / 64 83 bits := make([]uint64, bitCount) 84 reader := NewIndexReader(idx) 85 for i = 0; i < len(in)-l; i += l { 86 off = reader.Lookup(in[i : i+l]) 87 if int(off) >= count { 88 t.Errorf("off %d >= count %d", off, count) 89 } 90 mask := uint64(1) << (off & 63) 91 if bits[off>>6]&mask != 0 { 92 t.Fatalf("no bijection count=%d, i=%d", count, i/l) 93 } 94 bits[off>>6] |= mask 95 } 96 }) 97 }