-
Notifications
You must be signed in to change notification settings - Fork 23
/
chd_builder.go
232 lines (200 loc) · 5.4 KB
/
chd_builder.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
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
package mph
import (
"bytes"
"errors"
"fmt"
"math/rand"
"sort"
"time"
)
type chdHasher struct {
r []uint64
size uint64
buckets uint64
rand *rand.Rand
}
type bucket struct {
index uint64
keys [][]byte
values [][]byte
}
func (b *bucket) String() string {
a := "bucket{"
for _, k := range b.keys {
a += string(k) + ", "
}
return a + "}"
}
// Intermediate data structure storing buckets + outer hash index.
type bucketVector []bucket
func (b bucketVector) Len() int { return len(b) }
func (b bucketVector) Less(i, j int) bool { return len(b[i].keys) > len(b[j].keys) }
func (b bucketVector) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
// Build a new CDH MPH.
type CHDBuilder struct {
keys [][]byte
values [][]byte
seed int64
seeded bool
}
// Create a new CHD hash table builder.
func Builder() *CHDBuilder {
return &CHDBuilder{}
}
// Seed the RNG. This can be used to reproducible building.
func (b *CHDBuilder) Seed(seed int64) {
b.seed = seed
b.seeded = true
}
// Add a key and value to the hash table.
func (b *CHDBuilder) Add(key []byte, value []byte) {
b.keys = append(b.keys, key)
b.values = append(b.values, value)
}
// Try to find a hash function that does not cause collisions with table, when
// applied to the keys in the bucket.
func tryHash(hasher *chdHasher, seen map[uint64]bool, keys [][]byte, values [][]byte, indices []uint16, bucket *bucket, ri uint16, r uint64) bool {
// Track duplicates within this bucket.
duplicate := make(map[uint64]bool)
// Make hashes for each entry in the bucket.
hashes := make([]uint64, len(bucket.keys))
for i, k := range bucket.keys {
h := hasher.Table(r, k)
hashes[i] = h
if seen[h] {
return false
}
if duplicate[h] {
return false
}
duplicate[h] = true
}
// Update seen hashes
for _, h := range hashes {
seen[h] = true
}
// Add the hash index.
indices[bucket.index] = ri
// Update the the hash table.
for i, h := range hashes {
keys[h] = bucket.keys[i]
values[h] = bucket.values[i]
}
return true
}
func (b *CHDBuilder) Build() (*CHD, error) {
n := uint64(len(b.keys))
m := n / 2
if m == 0 {
m = 1
}
keys := make([][]byte, n)
values := make([][]byte, n)
hasher := newCHDHasher(n, m, b.seed, b.seeded)
buckets := make(bucketVector, m)
indices := make([]uint16, m)
// An extra check to make sure we don't use an invalid index
for i := range indices {
indices[i] = ^uint16(0)
}
// Have we seen a hash before?
seen := make(map[uint64]bool)
// Used to ensure there are no duplicate keys.
duplicates := make(map[string]bool)
for i := range b.keys {
key := b.keys[i]
value := b.values[i]
k := string(key)
if duplicates[k] {
return nil, errors.New("duplicate key " + k)
}
duplicates[k] = true
oh := hasher.HashIndexFromKey(key)
buckets[oh].index = oh
buckets[oh].keys = append(buckets[oh].keys, key)
buckets[oh].values = append(buckets[oh].values, value)
}
// Order buckets by size (retaining the hash index)
collisions := 0
sort.Sort(buckets)
nextBucket:
for i, bucket := range buckets {
if len(bucket.keys) == 0 {
continue
}
// Check existing hash functions.
for ri, r := range hasher.r {
if tryHash(hasher, seen, keys, values, indices, &bucket, uint16(ri), r) {
continue nextBucket
}
}
// Keep trying new functions until we get one that does not collide.
// The number of retries here is very high to allow a very high
// probability of not getting collisions.
for i := 0; i < 10000000; i++ {
if i > collisions {
collisions = i
}
ri, r := hasher.Generate()
if tryHash(hasher, seen, keys, values, indices, &bucket, ri, r) {
hasher.Add(r)
continue nextBucket
}
}
// Failed to find a hash function with no collisions.
return nil, fmt.Errorf(
"failed to find a collision-free hash function after ~10000000 attempts, for bucket %d/%d with %d entries: %s",
i, len(buckets), len(bucket.keys), &bucket)
}
// println("max bucket collisions:", collisions)
// println("keys:", len(table))
// println("hash functions:", len(hasher.r))
keylist := make([]dataSlice, len(b.keys))
valuelist := make([]dataSlice, len(b.values))
var buf bytes.Buffer
for i, k := range keys {
keylist[i].start = uint64(buf.Len())
buf.Write(k)
keylist[i].end = uint64(buf.Len())
valuelist[i].start = uint64(buf.Len())
buf.Write(values[i])
valuelist[i].end = uint64(buf.Len())
}
return &CHD{
r: hasher.r,
indices: indices,
mmap: buf.Bytes(),
keys: keylist,
values: valuelist,
}, nil
}
func newCHDHasher(size, buckets uint64, seed int64, seeded bool) *chdHasher {
if !seeded {
seed = time.Now().UnixNano()
}
rs := rand.NewSource(seed)
c := &chdHasher{size: size, buckets: buckets, rand: rand.New(rs)}
c.Add(c.rand.Uint64())
return c
}
// Hash index from key.
func (h *chdHasher) HashIndexFromKey(b []byte) uint64 {
return (hasher(b) ^ h.r[0]) % h.buckets
}
// Table hash from random value and key. Generate() returns these random values.
func (h *chdHasher) Table(r uint64, b []byte) uint64 {
return (hasher(b) ^ h.r[0] ^ r) % h.size
}
func (c *chdHasher) Generate() (uint16, uint64) {
return c.Len(), c.rand.Uint64()
}
// Add a random value generated by Generate().
func (c *chdHasher) Add(r uint64) {
c.r = append(c.r, r)
}
func (c *chdHasher) Len() uint16 {
return uint16(len(c.r))
}
func (h *chdHasher) String() string {
return fmt.Sprintf("chdHasher{size: %d, buckets: %d, r: %v}", h.size, h.buckets, h.r)
}