From 94c42ea784bb2ff1efbed9b0f1f10b5404a0972c Mon Sep 17 00:00:00 2001 From: Juliusz Chroboczek Date: Tue, 9 Jun 2020 15:47:33 +0200 Subject: [PATCH] Be more aggressive about growing the packet cache. Also add a test. --- packetcache/packetcache.go | 10 ++++++---- packetcache/packetcache_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/packetcache/packetcache.go b/packetcache/packetcache.go index a9902e1..7894054 100644 --- a/packetcache/packetcache.go +++ b/packetcache/packetcache.go @@ -204,13 +204,15 @@ func (cache *Cache) ResizeCond(capacity int) bool { current := len(cache.entries) - if current >= capacity/2 && current < capacity*2 { + if current >= capacity*3/4 && current < capacity*2 { return false } - if int(cache.tail) > current/2 && int(cache.tail) > capacity/2 { - // bad time to resize, this would invalidate too many indices - return false + if capacity < current { + if int(cache.tail) > capacity { + // this would invalidate too many indices + return false + } } cache.resize(capacity) diff --git a/packetcache/packetcache_test.go b/packetcache/packetcache_test.go index 51968ab..a4509d4 100644 --- a/packetcache/packetcache_test.go +++ b/packetcache/packetcache_test.go @@ -128,6 +128,33 @@ func TestCacheShrink(t *testing.T) { } } +func TestCacheGrowCond(t *testing.T) { + cache := New(16) + if len(cache.entries) != 16 { + t.Errorf("Expected 16, got %v", len(cache.entries)) + } + + done := cache.ResizeCond(17) + if done || len(cache.entries) != 16 { + t.Errorf("Grew cache by 1") + } + + done = cache.ResizeCond(15) + if done || len(cache.entries) != 16 { + t.Errorf("Shrunk cache by 1") + } + + done = cache.ResizeCond(32) + if !done || len(cache.entries) != 32 { + t.Errorf("Didn't grow cache") + } + + done = cache.ResizeCond(16) + if !done || len(cache.entries) != 16 { + t.Errorf("Didn't shrink cache") + } +} + func TestBitmap(t *testing.T) { value := uint64(0xcdd58f1e035379c0) packet := make([]byte, 1)