-
Notifications
You must be signed in to change notification settings - Fork 0
/
obfid_test.go
129 lines (101 loc) · 2.41 KB
/
obfid_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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package obfid
import (
"math/rand"
"reflect"
"testing"
)
func TestHard(t *testing.T) {
t.Skip("test takes 30sec+, here just for a reference")
prime := uint64(32_452_867)
random := uint64(32_452_867)
offset := uint64(10_000_000)
bits := 30
generator, err := NewGenerator(prime, random, offset, bits)
mustOk(t, err)
const size = 100_000_000
m := make(map[uint64]uint64, size)
for num := uint64(0); num < size; num++ {
enc := generator.Encode(num)
dec := generator.Decode(enc)
m[enc] = num
mustEqual(t, num, dec)
}
t.Logf("size: %v", len(m))
}
func TestGenerator(t *testing.T) {
generator, err := NewGenerator(32_452_867, 123, 1_000_000, 30)
mustOk(t, err)
for num := uint64(0); num < 30; num++ {
enc := generator.Encode(num)
dec := generator.Decode(enc)
t.Logf("%d => %d => %d", num, enc, dec)
mustEqual(t, num, dec)
}
}
func TestGeneratorSmall(t *testing.T) {
generator, err := NewGenerator(32_452_867, 123, 1_000_000, 5)
mustOk(t, err)
res := map[uint64]struct{}{}
for num := uint64(0); num < 100; num++ {
enc := generator.Encode(num)
dec := generator.Decode(enc)
t.Logf("%d => %d => %d", num, enc, dec)
mustEqual(t, num%32, dec)
res[dec] = struct{}{}
}
for i := uint64(0); i < 32; i++ {
delete(res, i)
}
mustEqual(t, len(res), 0)
}
func Test_inverse(t *testing.T) {
inv, err := inverse(32_452_867, 1<<31-1)
mustOk(t, err)
mustEqual(t, inv, uint64(23970219))
}
func BenchmarkEncode(b *testing.B) {
generator, err := NewGenerator(32_452_867, 123, 1_000_000, 30)
mustOk(b, err)
var count uint64
b.ResetTimer()
for i := 0; i < b.N; i++ {
count += generator.Encode(uint64(i))
}
sink(count)
}
func BenchmarkDecode(b *testing.B) {
generator, err := NewGenerator(32_452_867, 123, 1_000_000, 30)
mustOk(b, err)
var count uint64
b.ResetTimer()
for i := 0; i < b.N; i++ {
count += generator.Decode(uint64(i))
}
sink(count)
}
func Benchmark_inverse(b *testing.B) {
for i := 0; i < b.N; i++ {
inv, err := inverse(32_452_867, 1<<31-1)
mustOk(b, err)
if want := uint64(23970219); inv != want {
b.Fatalf("\nhave: %+v\nwant: %+v\n", inv, want)
}
}
}
func mustOk(tb testing.TB, err error) {
tb.Helper()
if err != nil {
tb.Fatal(err)
}
}
func mustEqual(tb testing.TB, have, want interface{}) {
tb.Helper()
if !reflect.DeepEqual(have, want) {
tb.Fatalf("\nhave: %+v\nwant: %+v\n", have, want)
}
}
func sink(v uint64) {
if rand.Float32() > 1 {
panic(v)
}
}