From 49319aac5156cf18db80c08c2f26a4571c1e91b8 Mon Sep 17 00:00:00 2001 From: "Laisky.Cai" Date: Wed, 3 Apr 2024 08:55:29 +0000 Subject: [PATCH] fix: runtime error index out of range caused by nextCleanupBucket - Adjusted cache size and TTL in `sieve_test.go` for more comprehensive testing - Implemented a constant `numberOfBuckets` and utilized it in `sieve.go` for cache storage - Updated `addToBucket` function to incorporate the new `numberOfBuckets` constant and `int8` `bucketID` type - Modified `bucketId` calculation in `addToBucket` function using `s.nextCleanupBucket` of type `float64` - Enhanced workload for testing in `sieve_test.go` from 256 to 10240 for rigorous testing --- sieve/sieve.go | 8 ++++++-- sieve/sieve_test.go | 4 ++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/sieve/sieve.go b/sieve/sieve.go index 083e3de..f3036b0 100644 --- a/sieve/sieve.go +++ b/sieve/sieve.go @@ -9,6 +9,10 @@ import ( "github.com/scalalang2/golang-fifo/types" ) +// numberOfBuckets is the number of buckets to store the cache entries +// +// Notice: if this number exceeds 256, the type of nextCleanupBucket +// in the Sieve struct should be changed to int16 const numberOfBuckets = 100 // entry holds the key and value of a cache entry. @@ -249,8 +253,8 @@ func (s *Sieve[K, V]) addToBucket(e *entry[K, V]) { if s.ttl == 0 { return } - bucketId := (numberOfBuckets + s.nextCleanupBucket - 1) % numberOfBuckets - e.bucketID = bucketId + bucketId := (numberOfBuckets + int(s.nextCleanupBucket) - 1) % numberOfBuckets + e.bucketID = int8(bucketId) s.buckets[bucketId].entries[e.key] = e if s.buckets[bucketId].newestEntry.Before(e.expiredAt) { s.buckets[bucketId].newestEntry = e.expiredAt diff --git a/sieve/sieve_test.go b/sieve/sieve_test.go index c87e25f..a26741f 100644 --- a/sieve/sieve_test.go +++ b/sieve/sieve_test.go @@ -205,8 +205,8 @@ func TestLargerWorkloadsThanCacheSize(t *testing.T) { bytes []byte } - cache := New[int32, value](128, 0) - workload := int32(256) + cache := New[int32, value](512, time.Millisecond) + workload := int32(10240) for i := int32(0); i < workload; i++ { val := value{ bytes: make([]byte, 10),