Skip to content

Commit

Permalink
fix: runtime error index out of range caused by nextCleanupBucket
Browse files Browse the repository at this point in the history
- 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
  • Loading branch information
Laisky authored and scalalang2 committed Apr 3, 2024
1 parent 75f0941 commit ef5cb24
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
8 changes: 6 additions & 2 deletions sieve/sieve.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions sieve/sieve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down

0 comments on commit ef5cb24

Please sign in to comment.