github.com/fluhus/gostuff@v0.4.1-0.20240331134726-be71864f2b5d/rhash/fuzz_test.go (about)

     1  package rhash
     2  
     3  import (
     4  	"hash"
     5  	"testing"
     6  
     7  	"github.com/fluhus/gostuff/snm"
     8  )
     9  
    10  func FuzzBuz64(f *testing.F) {
    11  	fuzz64(f, func(n int) hash.Hash64 { return NewBuz64(n) })
    12  }
    13  
    14  func FuzzRabin64(f *testing.F) {
    15  	fuzz64(f, func(n int) hash.Hash64 { return NewRabinFingerprint64(n) })
    16  }
    17  
    18  func FuzzBuz32(f *testing.F) {
    19  	fuzz32(f, func(n int) hash.Hash32 { return NewBuz32(n) })
    20  }
    21  
    22  func FuzzRabin32(f *testing.F) {
    23  	fuzz32(f, func(n int) hash.Hash32 { return NewRabinFingerprint32(n) })
    24  }
    25  
    26  func fuzz64(f *testing.F, fn func(n int) hash.Hash64) {
    27  	const m = 10
    28  	prefix := snm.Slice(30, func(i int) byte { return byte(i) })
    29  
    30  	f.Add([]byte{})
    31  	f.Fuzz(func(t *testing.T, a []byte) {
    32  		a = append(prefix, a...)
    33  		h := fn(m)
    34  		h.Write(a[len(a)-m:])
    35  		want := h.Sum64()
    36  		for i := range a[m:] {
    37  			h.Write(a[i:])
    38  			if got := h.Sum64(); got != want {
    39  				t.Fatalf("Sum64(%v)=%v, want %v", a[i:], got, want)
    40  			}
    41  		}
    42  	})
    43  }
    44  
    45  func fuzz32(f *testing.F, fn func(n int) hash.Hash32) {
    46  	const m = 10
    47  	prefix := snm.Slice(30, func(i int) byte { return byte(i) })
    48  
    49  	f.Add([]byte{})
    50  	f.Fuzz(func(t *testing.T, a []byte) {
    51  		a = append(prefix, a...)
    52  		h := fn(m)
    53  		h.Write(a[len(a)-m:])
    54  		want := h.Sum32()
    55  		for i := range a[m:] {
    56  			h.Write(a[i:])
    57  			if got := h.Sum32(); got != want {
    58  				t.Fatalf("Sum32(%v)=%v, want %v", a[i:], got, want)
    59  			}
    60  		}
    61  	})
    62  }