Skip to content

Commit 66a3e96

Browse files
committed
simplify
1 parent 9ae04f0 commit 66a3e96

File tree

2 files changed

+13
-16
lines changed

2 files changed

+13
-16
lines changed

cache.go

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -167,15 +167,9 @@ func (c *MemoryCache) SetWithCallback(key string, value any, exp time.Duration,
167167
var expireAt = c.getExp(exp)
168168
v, ok := c.fetch(b, key)
169169
if ok {
170-
var down = expireAt > v.ExpireAt
171170
v.Value = value
172-
v.ExpireAt = expireAt
173171
v.cb = cb
174-
if down {
175-
b.Heap.Down(v.index, b.Heap.Len())
176-
} else {
177-
b.Heap.Up(v.index)
178-
}
172+
b.Heap.UpdateTTL(v, expireAt)
179173
return true
180174
}
181175

@@ -210,14 +204,7 @@ func (c *MemoryCache) GetWithTTL(key string, exp time.Duration) (v any, exist bo
210204
return nil, false
211205
}
212206

213-
var expireAt = c.getExp(exp)
214-
var down = expireAt > result.ExpireAt
215-
result.ExpireAt = expireAt
216-
if down {
217-
b.Heap.Down(result.index, b.Heap.Len())
218-
} else {
219-
b.Heap.Up(result.index)
220-
}
207+
b.Heap.UpdateTTL(result, c.getExp(exp))
221208
return result.Value, true
222209
}
223210

heap.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,16 @@ type heap struct {
1212

1313
func (c *heap) Less(i, j int) bool { return c.Data[i].ExpireAt < c.Data[j].ExpireAt }
1414

15+
func (c *heap) UpdateTTL(ele *Element, exp int64) {
16+
var down = exp > ele.ExpireAt
17+
ele.ExpireAt = exp
18+
if down {
19+
c.Down(ele.index, c.Len())
20+
} else {
21+
c.Up(ele.index)
22+
}
23+
}
24+
1525
func (c *heap) min(i, j int) int {
1626
if c.Data[i].ExpireAt < c.Data[j].ExpireAt {
1727
return i
@@ -64,7 +74,7 @@ func (c *heap) Delete(i int) {
6474
case 1:
6575
c.Data = c.Data[:0]
6676
default:
67-
var down = c.Data[n-1].ExpireAt > c.Data[i].ExpireAt
77+
var down = c.Less(i, n-1)
6878
c.Swap(i, n-1)
6979
c.Data = c.Data[:n-1]
7080
if i < n-1 {

0 commit comments

Comments
 (0)