github.com/fufuok/utils@v1.0.10/xhash/hasher_xxhash_test.go (about) 1 //go:build go1.18 2 // +build go1.18 3 4 package xhash 5 6 import ( 7 "strconv" 8 "strings" 9 "testing" 10 11 "github.com/fufuok/utils/assert" 12 ) 13 14 func TestGenHasher64(t *testing.T) { 15 hasher0 := GenHasher64[string]() 16 var h0 string 17 h0 = "ff" 18 assert.Equal(t, hasher0(h0), hasher0(h0)) 19 20 hasher1 := GenHasher64[int]() 21 var h1 int 22 h1 = 123 23 assert.Equal(t, hasher1(h1), hasher1(h1)) 24 25 type L1 int 26 type L2 L1 27 hasher2 := GenHasher64[L2]() 28 var h2 L2 29 h2 = 123 30 assert.Equal(t, hasher2(h2), hasher2(h2)) 31 assert.Equal(t, hasher1(h1), hasher2(h2)) 32 33 type foo struct { 34 x int 35 y int 36 } 37 hasher3 := GenHasher64[*foo]() 38 h3 := new(foo) 39 h31 := h3 40 assert.Equal(t, hasher3(h3), hasher3(h31)) 41 42 hasher4 := GenHasher[float64]() 43 assert.Equal(t, hasher4(3.1415926), hasher4(3.1415926)) 44 assert.NotEqual(t, hasher4(3.1415926), hasher4(3.1415927)) 45 46 hasher5 := GenHasher[complex128]() 47 assert.Equal(t, hasher5(complex(3, 5)), hasher5(complex(3, 5))) 48 assert.NotEqual(t, hasher5(complex(4, 5)), hasher5(complex(3, 5))) 49 50 hasher6 := GenHasher[byte]() 51 assert.Equal(t, hasher6('\n'), hasher6(10)) 52 assert.NotEqual(t, hasher6('\r'), hasher6('\n')) 53 54 hasher7 := GenHasher[uintptr]() 55 assert.Equal(t, hasher7(8), hasher7(8)) 56 assert.NotEqual(t, hasher7(7), hasher7(8)) 57 } 58 59 func TestCollision_GenHasher64(t *testing.T) { 60 n := 20_000_000 61 sHasher := GenHasher64[string]() 62 iHasher := GenHasher64[int]() 63 ms := make(map[uint64]string) 64 mi := make(map[uint64]int) 65 for i := 0; i < n; i++ { 66 s := strconv.Itoa(i) 67 hs := sHasher(s) 68 hi := iHasher(i) 69 if v, ok := ms[hs]; ok { 70 t.Fatalf("Collision: %s(%d) == %s(%d)", v, sHasher(v), s, sHasher(s)) 71 } 72 if v, ok := mi[hi]; ok { 73 t.Fatalf("Collision: %d(%d) == %d(%d)", v, iHasher(v), i, iHasher(i)) 74 } 75 ms[hs] = s 76 mi[hi] = i 77 } 78 79 hi := iHasher(7) 80 if _, ok := mi[hi]; !ok { 81 t.Fatalf("The number 7 should exist") 82 } 83 if len(ms) != len(mi) || len(ms) != n { 84 t.Fatalf("Hash count: %d, %d, %d", len(ms), len(mi), n) 85 } 86 } 87 88 func BenchmarkHasher_GenHasher64(b *testing.B) { 89 sHasher := GenHasher64[string]() 90 iHasher := GenHasher64[int]() 91 b.ReportAllocs() 92 b.ResetTimer() 93 b.Run("string", func(b *testing.B) { 94 for i := 0; i < b.N; i++ { 95 _ = sHasher(strconv.Itoa(i)) 96 } 97 }) 98 b.Run("int", func(b *testing.B) { 99 for i := 0; i < b.N; i++ { 100 _ = iHasher(i) 101 } 102 }) 103 } 104 105 func BenchmarkHasher_Parallel_GenHasher64(b *testing.B) { 106 sHasher := GenHasher64[string]() 107 s := strings.Repeat(testString, 10) 108 b.ReportAllocs() 109 b.ResetTimer() 110 b.RunParallel(func(pb *testing.PB) { 111 for pb.Next() { 112 _ = sHasher(s) 113 } 114 }) 115 }