-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdict.go
More file actions
144 lines (111 loc) · 2.49 KB
/
dict.go
File metadata and controls
144 lines (111 loc) · 2.49 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
package adt
// 类型特定函数
type dicType string
// 私有数据 暂时不实现
type privateData struct{}
type Dict struct {
types dicType
privateData privateData
ht [2]DictHt
treHashIdx int64
}
func NewDict() *Dict {
return &Dict{
treHashIdx: -1,
ht: [2]DictHt{
*NewDictHt().InitHtBySize(2),
*NewDictHt(),
}}
}
// key 暂时只支持 string 吧
func (d *Dict) Hset(key *RedisObject, value *RedisObject) *Dict {
// 正在 rehash 插入只插入 ht[1],其他情况只插入 ht[0]
dictHt := d.GetWriteHt()
dictHt.AddDictValue(key, value)
// 插入完如果需要 rehash 则开始 rehash
if dictHt.ShouldReHash() {
d.BeginReHash()
}
return d
}
func (d *Dict) Hget(key *RedisObject) *RedisObject {
dictHt := &d.ht[0]
value := dictHt.findValue(key)
if value != nil {
return value
}
// 如果正在 rehash 需要分别查询 ht0 ht1 是否存在
if !d.IsReHashing() {
return nil
}
dictHt = &d.ht[1]
return dictHt.findValue(key)
}
func (d *Dict) Hdel(key *RedisObject) int {
dictHt := &d.ht[0]
status := dictHt.delValue(key)
// 如果正在 rehash 需要分别查询 ht0 ht1 是否存在
if status == 0 && d.IsReHashing() {
dictHt = &d.ht[1]
status = dictHt.delValue(key)
}
return status
}
func (d *Dict) FinishedAllReHash() {
d.ResetTreHashIdx()
d.SwapHt()
d.DestroyHt1()
}
func (d *Dict) BeginReHash() {
if !d.IsReHashing() {
d.treHashIdx++
}
writeHt := d.GetWriteHt()
readHt := d.GetReadHt()
// 如果 ht[1] 没有申请空间
if writeHt.IsEmpty() {
writeHt.InitHtBySize(readHt.size * 2)
}
i := readHt.MoveTableToNewByIndex(d.treHashIdx, writeHt)
d.FinishedCurrentIndexReHash(i)
if readHt.FinishedReHash(d.treHashIdx) {
d.FinishedAllReHash()
}
}
func (d *Dict) IsReHashing() bool {
return d.treHashIdx != -1
}
func (d *Dict) ResetTreHashIdx() {
d.treHashIdx = -1
}
func (d *Dict) FinishedCurrentIndexReHash(i int) {
d.treHashIdx += int64(i)
}
func (d *Dict) SwapHt() {
d.ht[0] = d.ht[1]
}
func (d *Dict) DestroyHt1() {
d.ht[1] = *NewDictHt()
d.ht[1].used = 0
d.ht[1].size = 0
d.ht[1].sizeMask = 0
}
func (d *Dict) GetWriteHt() *DictHt {
if d.IsReHashing() {
return &d.ht[1]
}
return &d.ht[0]
}
func (d *Dict) GetReadHt() *DictHt {
return &d.ht[0]
}
// 复制键函数
func (d *Dict) CopyKey() {}
// 复制值函数
func (d *Dict) CopyValue() {}
// 对比键函数
func (d *Dict) Compare() {}
// 销毁键函数
func (d *Dict) DestroyKey() {}
// 销毁键函数
func (d *Dict) DestroyValue() {}