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