Skip to content

Commit

Permalink
Merge pull request #5 from lxzan/fix
Browse files Browse the repository at this point in the history
v1.1.4
  • Loading branch information
lxzan authored Nov 2, 2023
2 parents 44ef192 + 8a7356c commit d087ce1
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 17 deletions.
3 changes: 2 additions & 1 deletion index.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func (c *MemoryCache) GetWithTTL(key string, exp time.Duration) (any, bool) {

v.ExpireAt = c.getExp(exp)
b.heap.Down(v.index, b.heap.Len())
return v, true
return v.Value, true
}

// Delete
Expand All @@ -161,6 +161,7 @@ func (c *MemoryCache) Delete(key string) (deleted bool) {

b.heap.Delete(v.index)
delete(b.Map, key)
v.cb(v, ReasonDeleted)
return true
}

Expand Down
49 changes: 33 additions & 16 deletions index_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,24 +135,41 @@ func TestMemoryCache_GetAndRefresh(t *testing.T) {
}

func TestMemoryCache_Delete(t *testing.T) {
var count = 10000
var mc = New(WithInterval(100*time.Millisecond, 100*time.Millisecond))
for i := 0; i < count; i++ {
key := string(utils.AlphabetNumeric.Generate(8))
exp := rand.Intn(1000) + 200
mc.Set(key, 1, time.Duration(exp)*time.Millisecond)
}
t.Run("1", func(t *testing.T) {
var count = 10000
var mc = New(WithInterval(100*time.Millisecond, 100*time.Millisecond))
for i := 0; i < count; i++ {
key := string(utils.AlphabetNumeric.Generate(8))
exp := rand.Intn(1000) + 200
mc.Set(key, 1, time.Duration(exp)*time.Millisecond)
}

var keys = mc.Keys("")
for i := 0; i < 100; i++ {
deleted := mc.Delete(keys[i])
assert.True(t, deleted)
var keys = mc.Keys("")
for i := 0; i < 100; i++ {
deleted := mc.Delete(keys[i])
assert.True(t, deleted)

key := string(utils.AlphabetNumeric.Generate(8))
deleted = mc.Delete(key)
assert.False(t, deleted)
}
assert.Equal(t, mc.Len(), count-100)
key := string(utils.AlphabetNumeric.Generate(8))
deleted = mc.Delete(key)
assert.False(t, deleted)
}
assert.Equal(t, mc.Len(), count-100)
})

t.Run("2", func(t *testing.T) {
var mc = New()
var wg = &sync.WaitGroup{}
wg.Add(1)
mc.SetWithCallback("ming", 1, -1, func(ele *Element, reason Reason) {
assert.Equal(t, reason, ReasonDeleted)
wg.Done()
})
mc.SetWithCallback("ting", 2, -1, func(ele *Element, reason Reason) {
wg.Done()
})
go mc.Delete("ming")
wg.Wait()
})
}

func TestMaxCap(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type Reason uint8
const (
ReasonExpired = Reason(0)
ReasonOverflow = Reason(1)
ReasonDeleted = Reason(2)
)

type CallbackFunc func(ele *Element, reason Reason)
Expand Down

0 comments on commit d087ce1

Please sign in to comment.