优化nftables集合元素过期时间判断

This commit is contained in:
刘祥超
2023-04-19 13:20:31 +08:00
parent 37ddff86f1
commit 7e8c09a684
2 changed files with 13 additions and 2 deletions

View File

@@ -40,7 +40,10 @@ func (this *Expiration) Remove(key []byte) {
func (this *Expiration) Contains(key []byte) bool {
this.locker.RLock()
_, ok := this.m[string(key)]
expires, ok := this.m[string(key)]
if ok && expires.Year() > 2000 && time.Now().After(expires) {
ok = false
}
this.locker.RUnlock()
return ok
}
@@ -55,7 +58,7 @@ func (this *Expiration) gc() {
var now = time.Now().Add(-10 * time.Second) // gc elements expired before 10 seconds ago
for key, expires := range this.m {
if expires.Year() >= 2000 && now.After(expires) {
if expires.Year() > 2000 && now.After(expires) {
delete(this.m, key)
}
}

View File

@@ -17,6 +17,14 @@ func TestExpiration_Add(t *testing.T) {
expiration.Add([]byte{'a', 'b', 'c'}, time.Now())
t.Log(expiration.Contains([]byte{'a', 'b', 'c'}))
}
{
expiration.Add([]byte{'a', 'b', 'c'}, time.Now().Add(1*time.Second))
t.Log(expiration.Contains([]byte{'a', 'b', 'c'}))
}
{
expiration.Add([]byte{'a', 'b', 'c'}, time.Time{})
t.Log(expiration.Contains([]byte{'a', 'b', 'c'}))
}
{
expiration.Add([]byte{'a', 'b', 'c'}, time.Now().Add(-1*time.Second))
t.Log(expiration.Contains([]byte{'a', 'b', 'c'}))