github.com/fufuok/freelru@v0.13.3/hasher_test.go (about) 1 package freelru 2 3 //lint:file-ignore U1000 unused fields are necessary to access the hasher 4 //lint:file-ignore SA4000 hash code comparisons use identical expressions 5 // From: https://github.com/puzpuzpuz/xsync/blob/main/util_hash_test.go 6 7 import ( 8 "fmt" 9 "testing" 10 ) 11 12 func TestMakeHashFunc(t *testing.T) { 13 type User struct { 14 Name string 15 City string 16 } 17 18 hashString := MakeHasher[string]() 19 hashUser := MakeHasher[User]() 20 21 // Not that much to test TBH. 22 // check that hash is not always the same 23 for i := 0; ; i++ { 24 if hashString("foo") != hashString("bar") { 25 break 26 } 27 if i >= 100 { 28 t.Error("hashString is always the same") 29 break 30 } 31 } 32 33 a := hashString("foo") 34 b := hashString("foo") 35 if a != b { 36 t.Error("hashString is not deterministic") 37 } 38 39 ua := hashUser(User{Name: "Ivan", City: "Sofia"}) 40 ub := hashUser(User{Name: "Ivan", City: "Sofia"}) 41 if ua != ub { 42 t.Error("hashUser is not deterministic") 43 } 44 } 45 46 func BenchmarkMakeHashFunc(b *testing.B) { 47 type Point struct { 48 X, Y, Z int 49 } 50 51 type User struct { 52 ID int 53 FirstName string 54 LastName string 55 IsActive bool 56 City string 57 } 58 59 type PadInside struct { 60 A int 61 B byte 62 C int 63 } 64 65 type PadTrailing struct { 66 A int 67 B byte 68 } 69 70 doBenchmarkMakeHashFunc(b, int64(116)) 71 doBenchmarkMakeHashFunc(b, int32(116)) 72 doBenchmarkMakeHashFunc(b, 3.14) 73 doBenchmarkMakeHashFunc(b, "test key test key test key test key test key test key test key test key test key ") 74 doBenchmarkMakeHashFunc(b, Point{1, 2, 3}) 75 doBenchmarkMakeHashFunc(b, User{ID: 1, FirstName: "Ivan", LastName: "Ivanov", IsActive: true, City: "Sofia"}) 76 doBenchmarkMakeHashFunc(b, PadInside{}) 77 doBenchmarkMakeHashFunc(b, PadTrailing{}) 78 doBenchmarkMakeHashFunc(b, [1024]byte{}) 79 doBenchmarkMakeHashFunc(b, [128]Point{}) 80 doBenchmarkMakeHashFunc(b, [128]User{}) 81 doBenchmarkMakeHashFunc(b, [128]PadInside{}) 82 doBenchmarkMakeHashFunc(b, [128]PadTrailing{}) 83 } 84 85 func doBenchmarkMakeHashFunc[T comparable](b *testing.B, val T) { 86 hash := MakeHasher[T]() 87 b.Run(fmt.Sprintf("%T", val), func(b *testing.B) { 88 b.ReportAllocs() 89 for i := 0; i < b.N; i++ { 90 _ = hash(val) 91 } 92 }) 93 }