Skip to content

Commit d9fdc91

Browse files
committed
map
1 parent 1be17ca commit d9fdc91

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed

test/m.go

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package test
2+
3+
// Deal的定义
4+
type DealTiny struct {
5+
Dealid int32
6+
Classid int32
7+
Mttypeid int32
8+
Bizacctid int32
9+
Isonline bool
10+
Geocnt int32
11+
}
12+
13+
type DealMap struct {
14+
table []DealTiny
15+
buckets int
16+
size int
17+
}
18+
19+
// round 到最近的2的倍数
20+
func minBuckets(v int) int {
21+
v--
22+
v |= v >> 1
23+
v |= v >> 2
24+
v |= v >> 4
25+
v |= v >> 8
26+
v |= v >> 16
27+
v++
28+
return v
29+
}
30+
31+
func hashInt32(x int) int {
32+
x = ((x >> 16) ^ x) * 0x45d9f3b
33+
x = ((x >> 16) ^ x) * 0x45d9f3b
34+
x = ((x >> 16) ^ x)
35+
return x
36+
}
37+
38+
func NewDealMap(maxsize int) *DealMap {
39+
buckets := minBuckets(maxsize)
40+
return &DealMap{size: 0, buckets: buckets, table: make([]DealTiny, buckets)}
41+
}
42+
43+
// TODO rehash策略
44+
func (m *DealMap) Put(d DealTiny) {
45+
num_probes, bucket_count_minus_one := 0, m.buckets-1
46+
bucknum := hashInt32(int(d.Dealid)) & bucket_count_minus_one
47+
for {
48+
if m.table[bucknum].Dealid == 0 { // insert, 不支持放入ID为0的Deal
49+
m.size += 1
50+
m.table[bucknum] = d
51+
return
52+
}
53+
if m.table[bucknum].Dealid == d.Dealid { // update
54+
m.table[bucknum] = d
55+
return
56+
}
57+
num_probes += 1 // Open addressing with Linear probing
58+
bucknum = (bucknum + num_probes) & bucket_count_minus_one
59+
}
60+
}
61+
62+
func (m *DealMap) Get(id int32) (DealTiny, bool) {
63+
num_probes, bucket_count_minus_one := 0, m.buckets-1
64+
bucknum := hashInt32(int(id)) & bucket_count_minus_one
65+
for {
66+
if m.table[bucknum].Dealid == id {
67+
return m.table[bucknum], true
68+
}
69+
if m.table[bucknum].Dealid == 0 {
70+
return m.table[bucknum], false
71+
}
72+
num_probes += 1
73+
bucknum = (bucknum + num_probes) & bucket_count_minus_one
74+
}
75+
}
76+
77+
func (m *DealMap) Delete(id int32) (DealTiny, bool) {
78+
num_probes, bucket_count_minus_one := 0, m.buckets-1
79+
bucknum := hashInt32(int(id)) & bucket_count_minus_one
80+
for {
81+
if m.table[bucknum].Dealid == id {
82+
deal := m.table[bucknum]
83+
num_probes += 1
84+
bucknum1 := bucknum
85+
bucknum2 := (bucknum + num_probes) & bucket_count_minus_one
86+
for bucknum2 < m.buckets && m.table[bucknum2].Dealid != 0 {
87+
m.table[bucknum1] = m.table[bucknum2]
88+
bucknum1 = bucknum2
89+
num_probes += 1
90+
bucknum2 = (bucknum + num_probes) & bucket_count_minus_one
91+
}
92+
m.table[bucknum1].Dealid = 0
93+
return deal, true
94+
}
95+
if m.table[bucknum].Dealid == 0 {
96+
return m.table[bucknum], false
97+
}
98+
num_probes += 1
99+
bucknum = (bucknum + num_probes) & bucket_count_minus_one
100+
}
101+
}

0 commit comments

Comments
 (0)