-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollision_test.go
More file actions
209 lines (166 loc) · 4.43 KB
/
collision_test.go
File metadata and controls
209 lines (166 loc) · 4.43 KB
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package cuid2
import (
"fmt"
"log"
"math"
"math/big"
"strconv"
"sync"
"testing"
)
func TestCollisions(t *testing.T) {
n := int64(math.Pow(float64(7), float64(8)) * 2)
log.Printf("Testing %v unique Cuids...", n)
numPools := int64(7)
pools := createIdPools(numPools, n/numPools)
ids := []string{}
for _, pool := range pools {
ids = append(ids, pool.ids...)
}
sampleIds := ids[:10]
set := map[string]struct{}{}
for _, id := range ids {
set[id] = struct{}{}
}
histogram := pools[0].histogram
log.Println("Sample Cuids:", sampleIds)
log.Println("Histogram:", histogram)
expectedBinSize := math.Ceil(float64(n / numPools / int64(len(histogram))))
tolerance := 0.05
minBinSize := math.Round(expectedBinSize * (1 - tolerance))
maxBinSize := math.Round(expectedBinSize * (1 + tolerance))
log.Println("Expected bin size:", expectedBinSize)
log.Println("Min bin size:", minBinSize)
log.Println("Maximum bin size:", maxBinSize)
collisionsDetected := int64(len(set)) - n
if collisionsDetected > 0 {
t.Fatalf("%v collisions detected", int64(len(set))-n)
}
for _, binSize := range histogram {
withinDistributionTolerance := binSize > minBinSize && binSize < maxBinSize
if !withinDistributionTolerance {
t.Errorf("Histogram of generated Cuids is not within the distribution tolerance of %v", tolerance)
t.Fatalf("Expected bin size: %v, min: %v, max: %v, actual: %v", expectedBinSize, minBinSize, maxBinSize, binSize)
}
}
validateCuids(t, ids)
}
type IdPool struct {
ids []string
numbers []big.Int
histogram []float64
}
func NewIdPool(max int) func() *IdPool {
return func() *IdPool {
set := map[string]struct{}{}
for i := 0; i < max; i++ {
set[Generate()] = struct{}{}
if i%100000 == 0 {
progress := float64(i) / float64(max)
log.Printf("%d%%", int64(progress*100))
}
if len(set) < i {
log.Printf("Collision at: %v", i)
break
}
}
log.Println("No collisions detected")
ids := []string{}
numbers := []big.Int{}
for element := range set {
ids = append(ids, element)
numbers = append(numbers, *idToBigInt(element[1:]))
}
return &IdPool{
ids: ids,
numbers: numbers,
histogram: buildHistogram(numbers, 20),
}
}
}
func idToBigInt(id string) *big.Int {
bigInt := new(big.Int)
for _, char := range id {
base36Rune, _ := strconv.ParseInt(string(char), 36, 64)
bigInt.Add(big.NewInt(base36Rune), bigInt.Mul(bigInt, big.NewInt(36)))
}
return bigInt
}
func buildHistogram(numbers []big.Int, bucketCount int) []float64 {
log.Println("Building histogram...")
buckets := make([]float64, bucketCount)
counter := 1
numPermutations, _ := big.NewFloat(math.Pow(float64(36), float64(DefaultIdLength-1))).Int(nil)
bucketLength := new(big.Int).Div(
numPermutations,
big.NewInt(int64(bucketCount)),
)
for _, number := range numbers {
if new(big.Int).Mod(big.NewInt(int64(counter)), bucketLength).Int64() == 0 {
log.Println(number)
}
bucket := new(big.Int).Div(
&number,
bucketLength,
)
if new(big.Int).Mod(big.NewInt(int64(counter)), bucketLength).Int64() == 0 {
log.Println(bucket)
}
buckets[bucket.Int64()]++
counter++
}
return buckets
}
func worker(id int, jobs <-chan func() *IdPool, results chan<- *IdPool) {
for job := range jobs {
log.Println("worker", id, "started job")
results <- job()
}
}
func createIdPools(numPools int64, maxIdsPerPool int64) []*IdPool {
jobsList := []func() *IdPool{}
for i := 0; i < int(numPools); i++ {
jobsList = append(jobsList, NewIdPool(int(maxIdsPerPool)))
}
jobs := make(chan func() *IdPool, numPools)
results := make(chan *IdPool, numPools)
for w := 1; w <= int(numPools); w++ {
go worker(w, jobs, results)
}
for _, job := range jobsList {
jobs <- job
}
close(jobs)
pools := []*IdPool{}
for a := 1; a <= int(numPools); a++ {
pool := <-results
pools = append(pools, pool)
}
return pools
}
func validateCuids(t *testing.T, ids []string) {
log.Printf("Validating all %v Cuids...", len(ids))
wg := new(sync.WaitGroup)
validationErrors := make(chan error)
for _, id := range ids {
wg.Add(1)
go func(id string) {
defer wg.Done()
if !IsCuid(id) {
validationErrors <- fmt.Errorf("Cuid (%v) is not valid", id)
}
}(id)
}
go func() {
wg.Wait()
close(validationErrors)
}()
numInvalidIds := 0
for err := range validationErrors {
log.Println(err.Error())
numInvalidIds++
}
if numInvalidIds > 0 {
t.Fatalf("%v Cuids were invalid", numInvalidIds)
}
}