From 8b0507f850895b74caa3685c56a7919f34963dde Mon Sep 17 00:00:00 2001 From: Michael Dresner Date: Fri, 18 Mar 2022 22:17:13 +0300 Subject: [PATCH 1/6] Introduce go.mod file --- go.mod | 5 +++++ go.sum | 2 ++ 2 files changed, 7 insertions(+) create mode 100644 go.mod create mode 100644 go.sum diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a5d349c --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/patrickmn/go-cache + +go 1.18 + +require golang.org/x/exp v0.0.0-20220318154914-8dddf5d87bd8 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..0507dff --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +golang.org/x/exp v0.0.0-20220318154914-8dddf5d87bd8 h1:s/+U+w0teGzcoH2mdIlFQ6KfVKGaYpgyGdUefZrn9TU= +golang.org/x/exp v0.0.0-20220318154914-8dddf5d87bd8/go.mod h1:lgLbSvA5ygNOMpwM/9anMpWVlVJ7Z+cHWq/eFuinpGE= From 80b989573cb53d65343568dd217f0aa9de2292fb Mon Sep 17 00:00:00 2001 From: Michael Dresner Date: Fri, 18 Mar 2022 22:17:47 +0300 Subject: [PATCH 2/6] Rewrite cache to generic one --- cache.go | 842 +++--------------------------------- cache_test.go | 1139 +++---------------------------------------------- 2 files changed, 112 insertions(+), 1869 deletions(-) diff --git a/cache.go b/cache.go index db88d2f..a6d8f01 100644 --- a/cache.go +++ b/cache.go @@ -10,13 +10,13 @@ import ( "time" ) -type Item struct { - Object interface{} +type Item[V any] struct { + Object V Expiration int64 } // Returns true if the item has expired. -func (item Item) Expired() bool { +func (item Item[V]) Expired() bool { if item.Expiration == 0 { return false } @@ -32,23 +32,23 @@ const ( DefaultExpiration time.Duration = 0 ) -type Cache struct { - *cache +type Cache[K comparable, V any] struct { + *cache[K, V] // If this is confusing, see the comment at the bottom of New() } -type cache struct { +type cache[K comparable, V any] struct { defaultExpiration time.Duration - items map[string]Item + items map[K]Item[V] mu sync.RWMutex - onEvicted func(string, interface{}) - janitor *janitor + onEvicted func(K, V) + janitor *janitor[K, V] } // Add an item to the cache, replacing any existing item. If the duration is 0 // (DefaultExpiration), the cache's default expiration time is used. If it is -1 // (NoExpiration), the item never expires. -func (c *cache) Set(k string, x interface{}, d time.Duration) { +func (c *cache[K, V]) Set(k K, x V, d time.Duration) { // "Inlining" of set var e int64 if d == DefaultExpiration { @@ -58,7 +58,7 @@ func (c *cache) Set(k string, x interface{}, d time.Duration) { e = time.Now().Add(d).UnixNano() } c.mu.Lock() - c.items[k] = Item{ + c.items[k] = Item[V]{ Object: x, Expiration: e, } @@ -67,7 +67,7 @@ func (c *cache) Set(k string, x interface{}, d time.Duration) { c.mu.Unlock() } -func (c *cache) set(k string, x interface{}, d time.Duration) { +func (c *cache[K, V]) set(k K, x V, d time.Duration) { var e int64 if d == DefaultExpiration { d = c.defaultExpiration @@ -75,7 +75,7 @@ func (c *cache) set(k string, x interface{}, d time.Duration) { if d > 0 { e = time.Now().Add(d).UnixNano() } - c.items[k] = Item{ + c.items[k] = Item[V]{ Object: x, Expiration: e, } @@ -83,18 +83,18 @@ func (c *cache) set(k string, x interface{}, d time.Duration) { // Add an item to the cache, replacing any existing item, using the default // expiration. -func (c *cache) SetDefault(k string, x interface{}) { +func (c *cache[K, V]) SetDefault(k K, x V) { c.Set(k, x, DefaultExpiration) } // Add an item to the cache only if an item doesn't already exist for the given // key, or if the existing item has expired. Returns an error otherwise. -func (c *cache) Add(k string, x interface{}, d time.Duration) error { +func (c *cache[K, V]) Add(k K, x V, d time.Duration) error { c.mu.Lock() _, found := c.get(k) if found { c.mu.Unlock() - return fmt.Errorf("Item %s already exists", k) + return fmt.Errorf("Item %v already exists", k) } c.set(k, x, d) c.mu.Unlock() @@ -103,12 +103,12 @@ func (c *cache) Add(k string, x interface{}, d time.Duration) error { // Set a new value for the cache key only if it already exists, and the existing // item hasn't expired. Returns an error otherwise. -func (c *cache) Replace(k string, x interface{}, d time.Duration) error { +func (c *cache[K, V]) Replace(k K, x V, d time.Duration) error { c.mu.Lock() _, found := c.get(k) if !found { c.mu.Unlock() - return fmt.Errorf("Item %s doesn't exist", k) + return fmt.Errorf("Item %v doesn't exist", k) } c.set(k, x, d) c.mu.Unlock() @@ -117,7 +117,7 @@ func (c *cache) Replace(k string, x interface{}, d time.Duration) error { // Get an item from the cache. Returns the item or nil, and a bool indicating // whether the key was found. -func (c *cache) Get(k string) (interface{}, bool) { +func (c *cache[K, V]) Get(k K) (*V, bool) { c.mu.RLock() // "Inlining" of get and Expired item, found := c.items[k] @@ -132,14 +132,14 @@ func (c *cache) Get(k string) (interface{}, bool) { } } c.mu.RUnlock() - return item.Object, true + return &item.Object, true } // GetWithExpiration returns an item and its expiration time from the cache. // It returns the item or nil, the expiration time if one is set (if the item // never expires a zero value for time.Time is returned), and a bool indicating // whether the key was found. -func (c *cache) GetWithExpiration(k string) (interface{}, time.Time, bool) { +func (c *cache[K, V]) GetWithExpiration(k K) (*V, time.Time, bool) { c.mu.RLock() // "Inlining" of get and Expired item, found := c.items[k] @@ -156,16 +156,16 @@ func (c *cache) GetWithExpiration(k string) (interface{}, time.Time, bool) { // Return the item and the expiration time c.mu.RUnlock() - return item.Object, time.Unix(0, item.Expiration), true + return &item.Object, time.Unix(0, item.Expiration), true } // If expiration <= 0 (i.e. no expiration time set) then return the item // and a zeroed time.Time c.mu.RUnlock() - return item.Object, time.Time{}, true + return &item.Object, time.Time{}, true } -func (c *cache) get(k string) (interface{}, bool) { +func (c *cache[K, V]) get(k K) (*V, bool) { item, found := c.items[k] if !found { return nil, false @@ -176,760 +176,38 @@ func (c *cache) get(k string) (interface{}, bool) { return nil, false } } - return item.Object, true -} - -// Increment an item of type int, int8, int16, int32, int64, uintptr, uint, -// uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the -// item's value is not an integer, if it was not found, or if it is not -// possible to increment it by n. To retrieve the incremented value, use one -// of the specialized methods, e.g. IncrementInt64. -func (c *cache) Increment(k string, n int64) error { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item %s not found", k) - } - switch v.Object.(type) { - case int: - v.Object = v.Object.(int) + int(n) - case int8: - v.Object = v.Object.(int8) + int8(n) - case int16: - v.Object = v.Object.(int16) + int16(n) - case int32: - v.Object = v.Object.(int32) + int32(n) - case int64: - v.Object = v.Object.(int64) + n - case uint: - v.Object = v.Object.(uint) + uint(n) - case uintptr: - v.Object = v.Object.(uintptr) + uintptr(n) - case uint8: - v.Object = v.Object.(uint8) + uint8(n) - case uint16: - v.Object = v.Object.(uint16) + uint16(n) - case uint32: - v.Object = v.Object.(uint32) + uint32(n) - case uint64: - v.Object = v.Object.(uint64) + uint64(n) - case float32: - v.Object = v.Object.(float32) + float32(n) - case float64: - v.Object = v.Object.(float64) + float64(n) - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s is not an integer", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Increment an item of type float32 or float64 by n. Returns an error if the -// item's value is not floating point, if it was not found, or if it is not -// possible to increment it by n. Pass a negative number to decrement the -// value. To retrieve the incremented value, use one of the specialized methods, -// e.g. IncrementFloat64. -func (c *cache) IncrementFloat(k string, n float64) error { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item %s not found", k) - } - switch v.Object.(type) { - case float32: - v.Object = v.Object.(float32) + float32(n) - case float64: - v.Object = v.Object.(float64) + n - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s does not have type float32 or float64", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Increment an item of type int by n. Returns an error if the item's value is -// not an int, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt(k string, n int) (int, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int8 by n. Returns an error if the item's value is -// not an int8, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt8(k string, n int8) (int8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int8", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int16 by n. Returns an error if the item's value is -// not an int16, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt16(k string, n int16) (int16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int16", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int32 by n. Returns an error if the item's value is -// not an int32, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt32(k string, n int32) (int32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int32", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type int64 by n. Returns an error if the item's value is -// not an int64, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementInt64(k string, n int64) (int64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int64", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint by n. Returns an error if the item's value is -// not an uint, or if it was not found. If there is no error, the incremented -// value is returned. -func (c *cache) IncrementUint(k string, n uint) (uint, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uintptr by n. Returns an error if the item's value -// is not an uintptr, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUintptr(k string, n uintptr) (uintptr, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uintptr) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uintptr", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint8 by n. Returns an error if the item's value -// is not an uint8, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint8(k string, n uint8) (uint8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint8", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint16 by n. Returns an error if the item's value -// is not an uint16, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint16(k string, n uint16) (uint16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint16", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint32 by n. Returns an error if the item's value -// is not an uint32, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint32(k string, n uint32) (uint32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint32", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type uint64 by n. Returns an error if the item's value -// is not an uint64, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementUint64(k string, n uint64) (uint64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint64", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type float32 by n. Returns an error if the item's value -// is not an float32, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementFloat32(k string, n float32) (float32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float32", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Increment an item of type float64 by n. Returns an error if the item's value -// is not an float64, or if it was not found. If there is no error, the -// incremented value is returned. -func (c *cache) IncrementFloat64(k string, n float64) (float64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float64", k) - } - nv := rv + n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int, int8, int16, int32, int64, uintptr, uint, -// uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the -// item's value is not an integer, if it was not found, or if it is not -// possible to decrement it by n. To retrieve the decremented value, use one -// of the specialized methods, e.g. DecrementInt64. -func (c *cache) Decrement(k string, n int64) error { - // TODO: Implement Increment and Decrement more cleanly. - // (Cannot do Increment(k, n*-1) for uints.) - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item not found") - } - switch v.Object.(type) { - case int: - v.Object = v.Object.(int) - int(n) - case int8: - v.Object = v.Object.(int8) - int8(n) - case int16: - v.Object = v.Object.(int16) - int16(n) - case int32: - v.Object = v.Object.(int32) - int32(n) - case int64: - v.Object = v.Object.(int64) - n - case uint: - v.Object = v.Object.(uint) - uint(n) - case uintptr: - v.Object = v.Object.(uintptr) - uintptr(n) - case uint8: - v.Object = v.Object.(uint8) - uint8(n) - case uint16: - v.Object = v.Object.(uint16) - uint16(n) - case uint32: - v.Object = v.Object.(uint32) - uint32(n) - case uint64: - v.Object = v.Object.(uint64) - uint64(n) - case float32: - v.Object = v.Object.(float32) - float32(n) - case float64: - v.Object = v.Object.(float64) - float64(n) - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s is not an integer", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Decrement an item of type float32 or float64 by n. Returns an error if the -// item's value is not floating point, if it was not found, or if it is not -// possible to decrement it by n. Pass a negative number to decrement the -// value. To retrieve the decremented value, use one of the specialized methods, -// e.g. DecrementFloat64. -func (c *cache) DecrementFloat(k string, n float64) error { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return fmt.Errorf("Item %s not found", k) - } - switch v.Object.(type) { - case float32: - v.Object = v.Object.(float32) - float32(n) - case float64: - v.Object = v.Object.(float64) - n - default: - c.mu.Unlock() - return fmt.Errorf("The value for %s does not have type float32 or float64", k) - } - c.items[k] = v - c.mu.Unlock() - return nil -} - -// Decrement an item of type int by n. Returns an error if the item's value is -// not an int, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt(k string, n int) (int, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int8 by n. Returns an error if the item's value is -// not an int8, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt8(k string, n int8) (int8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int8", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int16 by n. Returns an error if the item's value is -// not an int16, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt16(k string, n int16) (int16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int16", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int32 by n. Returns an error if the item's value is -// not an int32, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt32(k string, n int32) (int32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int32", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type int64 by n. Returns an error if the item's value is -// not an int64, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementInt64(k string, n int64) (int64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(int64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an int64", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint by n. Returns an error if the item's value is -// not an uint, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementUint(k string, n uint) (uint, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uintptr by n. Returns an error if the item's value -// is not an uintptr, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUintptr(k string, n uintptr) (uintptr, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uintptr) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uintptr", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint8 by n. Returns an error if the item's value is -// not an uint8, or if it was not found. If there is no error, the decremented -// value is returned. -func (c *cache) DecrementUint8(k string, n uint8) (uint8, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint8) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint8", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint16 by n. Returns an error if the item's value -// is not an uint16, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUint16(k string, n uint16) (uint16, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint16) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint16", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint32 by n. Returns an error if the item's value -// is not an uint32, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUint32(k string, n uint32) (uint32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint32", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type uint64 by n. Returns an error if the item's value -// is not an uint64, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementUint64(k string, n uint64) (uint64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(uint64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an uint64", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type float32 by n. Returns an error if the item's value -// is not an float32, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementFloat32(k string, n float32) (float32, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float32) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float32", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil -} - -// Decrement an item of type float64 by n. Returns an error if the item's value -// is not an float64, or if it was not found. If there is no error, the -// decremented value is returned. -func (c *cache) DecrementFloat64(k string, n float64) (float64, error) { - c.mu.Lock() - v, found := c.items[k] - if !found || v.Expired() { - c.mu.Unlock() - return 0, fmt.Errorf("Item %s not found", k) - } - rv, ok := v.Object.(float64) - if !ok { - c.mu.Unlock() - return 0, fmt.Errorf("The value for %s is not an float64", k) - } - nv := rv - n - v.Object = nv - c.items[k] = v - c.mu.Unlock() - return nv, nil + return &item.Object, true } // Delete an item from the cache. Does nothing if the key is not in the cache. -func (c *cache) Delete(k string) { +func (c *cache[K, V]) Delete(k K) { c.mu.Lock() v, evicted := c.delete(k) c.mu.Unlock() if evicted { - c.onEvicted(k, v) + c.onEvicted(k, *v) } } -func (c *cache) delete(k string) (interface{}, bool) { +func (c *cache[K, V]) delete(k K) (*V, bool) { if c.onEvicted != nil { if v, found := c.items[k]; found { delete(c.items, k) - return v.Object, true + return &v.Object, true } } delete(c.items, k) return nil, false } -type keyAndValue struct { - key string - value interface{} +type keyAndValue[K comparable, V any] struct { + key K + value V } // Delete all expired items from the cache. -func (c *cache) DeleteExpired() { - var evictedItems []keyAndValue +func (c *cache[K, V]) DeleteExpired() { + var evictedItems []keyAndValue[K, V] now := time.Now().UnixNano() c.mu.Lock() for k, v := range c.items { @@ -937,7 +215,7 @@ func (c *cache) DeleteExpired() { if v.Expiration > 0 && now > v.Expiration { ov, evicted := c.delete(k) if evicted { - evictedItems = append(evictedItems, keyAndValue{k, ov}) + evictedItems = append(evictedItems, keyAndValue[K, V]{k, *ov}) } } } @@ -950,7 +228,7 @@ func (c *cache) DeleteExpired() { // Sets an (optional) function that is called with the key and value when an // item is evicted from the cache. (Including when it is deleted manually, but // not when it is overwritten.) Set to nil to disable. -func (c *cache) OnEvicted(f func(string, interface{})) { +func (c *cache[K, V]) OnEvicted(f func(K, V)) { c.mu.Lock() c.onEvicted = f c.mu.Unlock() @@ -960,7 +238,7 @@ func (c *cache) OnEvicted(f func(string, interface{})) { // // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the // documentation for NewFrom().) -func (c *cache) Save(w io.Writer) (err error) { +func (c *cache[K, V]) Save(w io.Writer) (err error) { enc := gob.NewEncoder(w) defer func() { if x := recover(); x != nil { @@ -981,7 +259,7 @@ func (c *cache) Save(w io.Writer) (err error) { // // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the // documentation for NewFrom().) -func (c *cache) SaveFile(fname string) error { +func (c *cache[K, V]) SaveFile(fname string) error { fp, err := os.Create(fname) if err != nil { return err @@ -999,9 +277,9 @@ func (c *cache) SaveFile(fname string) error { // // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the // documentation for NewFrom().) -func (c *cache) Load(r io.Reader) error { +func (c *cache[K, V]) Load(r io.Reader) error { dec := gob.NewDecoder(r) - items := map[string]Item{} + items := map[K]Item[V]{} err := dec.Decode(&items) if err == nil { c.mu.Lock() @@ -1021,7 +299,7 @@ func (c *cache) Load(r io.Reader) error { // // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the // documentation for NewFrom().) -func (c *cache) LoadFile(fname string) error { +func (c *cache[K, V]) LoadFile(fname string) error { fp, err := os.Open(fname) if err != nil { return err @@ -1035,10 +313,10 @@ func (c *cache) LoadFile(fname string) error { } // Copies all unexpired items in the cache into a new map and returns it. -func (c *cache) Items() map[string]Item { +func (c *cache[K, V]) Items() map[K]Item[V] { c.mu.RLock() defer c.mu.RUnlock() - m := make(map[string]Item, len(c.items)) + m := make(map[K]Item[V], len(c.items)) now := time.Now().UnixNano() for k, v := range c.items { // "Inlining" of Expired @@ -1054,7 +332,7 @@ func (c *cache) Items() map[string]Item { // Returns the number of items in the cache. This may include items that have // expired, but have not yet been cleaned up. -func (c *cache) ItemCount() int { +func (c *cache[K, V]) ItemCount() int { c.mu.RLock() n := len(c.items) c.mu.RUnlock() @@ -1062,18 +340,18 @@ func (c *cache) ItemCount() int { } // Delete all items from the cache. -func (c *cache) Flush() { +func (c *cache[K, V]) Flush() { c.mu.Lock() - c.items = map[string]Item{} + c.items = map[K]Item[V]{} c.mu.Unlock() } -type janitor struct { +type janitor[K comparable, V any] struct { Interval time.Duration stop chan bool } -func (j *janitor) Run(c *cache) { +func (j *janitor[K, V]) Run(c *cache[K, V]) { ticker := time.NewTicker(j.Interval) for { select { @@ -1086,12 +364,12 @@ func (j *janitor) Run(c *cache) { } } -func stopJanitor(c *Cache) { +func stopJanitor[K comparable, V any](c *Cache[K, V]) { c.janitor.stop <- true } -func runJanitor(c *cache, ci time.Duration) { - j := &janitor{ +func runJanitor[K comparable, V any](c *cache[K, V], ci time.Duration) { + j := &janitor[K, V]{ Interval: ci, stop: make(chan bool), } @@ -1099,28 +377,28 @@ func runJanitor(c *cache, ci time.Duration) { go j.Run(c) } -func newCache(de time.Duration, m map[string]Item) *cache { +func newCache[K comparable, V any](de time.Duration, m map[K]Item[V]) *cache[K, V] { if de == 0 { de = -1 } - c := &cache{ + c := &cache[K, V]{ defaultExpiration: de, items: m, } return c } -func newCacheWithJanitor(de time.Duration, ci time.Duration, m map[string]Item) *Cache { +func newCacheWithJanitor[K comparable, V any](de time.Duration, ci time.Duration, m map[K]Item[V]) *Cache[K, V] { c := newCache(de, m) // This trick ensures that the janitor goroutine (which--granted it // was enabled--is running DeleteExpired on c forever) does not keep // the returned C object from being garbage collected. When it is // garbage collected, the finalizer stops the janitor goroutine, after // which c can be collected. - C := &Cache{c} + C := &Cache[K, V]{c} if ci > 0 { runJanitor(c, ci) - runtime.SetFinalizer(C, stopJanitor) + runtime.SetFinalizer(C, stopJanitor[K, V]) } return C } @@ -1130,8 +408,8 @@ func newCacheWithJanitor(de time.Duration, ci time.Duration, m map[string]Item) // the items in the cache never expire (by default), and must be deleted // manually. If the cleanup interval is less than one, expired items are not // deleted from the cache before calling c.DeleteExpired(). -func New(defaultExpiration, cleanupInterval time.Duration) *Cache { - items := make(map[string]Item) +func New[K comparable, V any](defaultExpiration, cleanupInterval time.Duration) *Cache[K, V] { + items := make(map[K]Item[V]) return newCacheWithJanitor(defaultExpiration, cleanupInterval, items) } @@ -1144,7 +422,7 @@ func New(defaultExpiration, cleanupInterval time.Duration) *Cache { // NewFrom() also accepts an items map which will serve as the underlying map // for the cache. This is useful for starting from a deserialized cache // (serialized using e.g. gob.Encode() on c.Items()), or passing in e.g. -// make(map[string]Item, 500) to improve startup performance when the cache +// make(map[string]Item[int], 500) to improve startup performance when the cache // is expected to reach a certain minimum size. // // Only the cache's methods synchronize access to this map, so it is not @@ -1156,6 +434,6 @@ func New(defaultExpiration, cleanupInterval time.Duration) *Cache { // gob.Register() the individual types stored in the cache before encoding a // map retrieved with c.Items(), and to register those same types before // decoding a blob containing an items map. -func NewFrom(defaultExpiration, cleanupInterval time.Duration, items map[string]Item) *Cache { +func NewFrom[K comparable, V any](defaultExpiration, cleanupInterval time.Duration, items map[K]Item[V]) *Cache[K, V] { return newCacheWithJanitor(defaultExpiration, cleanupInterval, items) } diff --git a/cache_test.go b/cache_test.go index de3e9d6..84ebefa 100644 --- a/cache_test.go +++ b/cache_test.go @@ -16,7 +16,7 @@ type TestStruct struct { } func TestCache(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, int](DefaultExpiration, 0) a, found := tc.Get("a") if found || a != nil { @@ -34,8 +34,6 @@ func TestCache(t *testing.T) { } tc.Set("a", 1, DefaultExpiration) - tc.Set("b", "b", DefaultExpiration) - tc.Set("c", 3.5, DefaultExpiration) x, found := tc.Get("a") if !found { @@ -43,35 +41,15 @@ func TestCache(t *testing.T) { } if x == nil { t.Error("x for a is nil") - } else if a2 := x.(int); a2+2 != 3 { + } else if a2 := *x; a2+2 != 3 { t.Error("a2 (which should be 1) plus 2 does not equal 3; value:", a2) } - - x, found = tc.Get("b") - if !found { - t.Error("b was not found while getting b2") - } - if x == nil { - t.Error("x for b is nil") - } else if b2 := x.(string); b2+"B" != "bB" { - t.Error("b2 (which should be b) plus B does not equal bB; value:", b2) - } - - x, found = tc.Get("c") - if !found { - t.Error("c was not found while getting c2") - } - if x == nil { - t.Error("x for c is nil") - } else if c2 := x.(float64); c2+1.2 != 4.7 { - t.Error("c2 (which should be 3.5) plus 1.2 does not equal 4.7; value:", c2) - } } func TestCacheTimes(t *testing.T) { var found bool - tc := New(50*time.Millisecond, 1*time.Millisecond) + tc := New[string, int](50*time.Millisecond, 1*time.Millisecond) tc.Set("a", 1, DefaultExpiration) tc.Set("b", 2, NoExpiration) tc.Set("c", 3, 20*time.Millisecond) @@ -107,12 +85,12 @@ func TestCacheTimes(t *testing.T) { } func TestNewFrom(t *testing.T) { - m := map[string]Item{ - "a": Item{ + m := map[string]Item[int]{ + "a": { Object: 1, Expiration: 0, }, - "b": Item{ + "b": { Object: 2, Expiration: 0, }, @@ -122,998 +100,38 @@ func TestNewFrom(t *testing.T) { if !found { t.Fatal("Did not find a") } - if a.(int) != 1 { + if *a != 1 { t.Fatal("a is not 1") } b, found := tc.Get("b") if !found { t.Fatal("Did not find b") } - if b.(int) != 2 { + if *b != 2 { t.Fatal("b is not 2") } } func TestStorePointerToStruct(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, *TestStruct](DefaultExpiration, 0) tc.Set("foo", &TestStruct{Num: 1}, DefaultExpiration) x, found := tc.Get("foo") if !found { t.Fatal("*TestStruct was not found for foo") } - foo := x.(*TestStruct) - foo.Num++ + (*x).Num++ y, found := tc.Get("foo") if !found { t.Fatal("*TestStruct was not found for foo (second time)") } - bar := y.(*TestStruct) - if bar.Num != 2 { + if (*y).Num != 2 { t.Fatal("TestStruct.Num is not 2") } } -func TestIncrementWithInt(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tint", 1, DefaultExpiration) - err := tc.Increment("tint", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - x, found := tc.Get("tint") - if !found { - t.Error("tint was not found") - } - if x.(int) != 3 { - t.Error("tint is not 3:", x) - } -} - -func TestIncrementWithInt8(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tint8", int8(1), DefaultExpiration) - err := tc.Increment("tint8", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - x, found := tc.Get("tint8") - if !found { - t.Error("tint8 was not found") - } - if x.(int8) != 3 { - t.Error("tint8 is not 3:", x) - } -} - -func TestIncrementWithInt16(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tint16", int16(1), DefaultExpiration) - err := tc.Increment("tint16", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - x, found := tc.Get("tint16") - if !found { - t.Error("tint16 was not found") - } - if x.(int16) != 3 { - t.Error("tint16 is not 3:", x) - } -} - -func TestIncrementWithInt32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tint32", int32(1), DefaultExpiration) - err := tc.Increment("tint32", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - x, found := tc.Get("tint32") - if !found { - t.Error("tint32 was not found") - } - if x.(int32) != 3 { - t.Error("tint32 is not 3:", x) - } -} - -func TestIncrementWithInt64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tint64", int64(1), DefaultExpiration) - err := tc.Increment("tint64", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - x, found := tc.Get("tint64") - if !found { - t.Error("tint64 was not found") - } - if x.(int64) != 3 { - t.Error("tint64 is not 3:", x) - } -} - -func TestIncrementWithUint(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuint", uint(1), DefaultExpiration) - err := tc.Increment("tuint", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - x, found := tc.Get("tuint") - if !found { - t.Error("tuint was not found") - } - if x.(uint) != 3 { - t.Error("tuint is not 3:", x) - } -} - -func TestIncrementWithUintptr(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuintptr", uintptr(1), DefaultExpiration) - err := tc.Increment("tuintptr", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - - x, found := tc.Get("tuintptr") - if !found { - t.Error("tuintptr was not found") - } - if x.(uintptr) != 3 { - t.Error("tuintptr is not 3:", x) - } -} - -func TestIncrementWithUint8(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuint8", uint8(1), DefaultExpiration) - err := tc.Increment("tuint8", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - x, found := tc.Get("tuint8") - if !found { - t.Error("tuint8 was not found") - } - if x.(uint8) != 3 { - t.Error("tuint8 is not 3:", x) - } -} - -func TestIncrementWithUint16(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuint16", uint16(1), DefaultExpiration) - err := tc.Increment("tuint16", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - - x, found := tc.Get("tuint16") - if !found { - t.Error("tuint16 was not found") - } - if x.(uint16) != 3 { - t.Error("tuint16 is not 3:", x) - } -} - -func TestIncrementWithUint32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuint32", uint32(1), DefaultExpiration) - err := tc.Increment("tuint32", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - x, found := tc.Get("tuint32") - if !found { - t.Error("tuint32 was not found") - } - if x.(uint32) != 3 { - t.Error("tuint32 is not 3:", x) - } -} - -func TestIncrementWithUint64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuint64", uint64(1), DefaultExpiration) - err := tc.Increment("tuint64", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - - x, found := tc.Get("tuint64") - if !found { - t.Error("tuint64 was not found") - } - if x.(uint64) != 3 { - t.Error("tuint64 is not 3:", x) - } -} - -func TestIncrementWithFloat32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float32", float32(1.5), DefaultExpiration) - err := tc.Increment("float32", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - x, found := tc.Get("float32") - if !found { - t.Error("float32 was not found") - } - if x.(float32) != 3.5 { - t.Error("float32 is not 3.5:", x) - } -} - -func TestIncrementWithFloat64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float64", float64(1.5), DefaultExpiration) - err := tc.Increment("float64", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - x, found := tc.Get("float64") - if !found { - t.Error("float64 was not found") - } - if x.(float64) != 3.5 { - t.Error("float64 is not 3.5:", x) - } -} - -func TestIncrementFloatWithFloat32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float32", float32(1.5), DefaultExpiration) - err := tc.IncrementFloat("float32", 2) - if err != nil { - t.Error("Error incrementfloating:", err) - } - x, found := tc.Get("float32") - if !found { - t.Error("float32 was not found") - } - if x.(float32) != 3.5 { - t.Error("float32 is not 3.5:", x) - } -} - -func TestIncrementFloatWithFloat64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float64", float64(1.5), DefaultExpiration) - err := tc.IncrementFloat("float64", 2) - if err != nil { - t.Error("Error incrementfloating:", err) - } - x, found := tc.Get("float64") - if !found { - t.Error("float64 was not found") - } - if x.(float64) != 3.5 { - t.Error("float64 is not 3.5:", x) - } -} - -func TestDecrementWithInt(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("int", int(5), DefaultExpiration) - err := tc.Decrement("int", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("int") - if !found { - t.Error("int was not found") - } - if x.(int) != 3 { - t.Error("int is not 3:", x) - } -} - -func TestDecrementWithInt8(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("int8", int8(5), DefaultExpiration) - err := tc.Decrement("int8", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("int8") - if !found { - t.Error("int8 was not found") - } - if x.(int8) != 3 { - t.Error("int8 is not 3:", x) - } -} - -func TestDecrementWithInt16(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("int16", int16(5), DefaultExpiration) - err := tc.Decrement("int16", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("int16") - if !found { - t.Error("int16 was not found") - } - if x.(int16) != 3 { - t.Error("int16 is not 3:", x) - } -} - -func TestDecrementWithInt32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("int32", int32(5), DefaultExpiration) - err := tc.Decrement("int32", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("int32") - if !found { - t.Error("int32 was not found") - } - if x.(int32) != 3 { - t.Error("int32 is not 3:", x) - } -} - -func TestDecrementWithInt64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("int64", int64(5), DefaultExpiration) - err := tc.Decrement("int64", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("int64") - if !found { - t.Error("int64 was not found") - } - if x.(int64) != 3 { - t.Error("int64 is not 3:", x) - } -} - -func TestDecrementWithUint(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint", uint(5), DefaultExpiration) - err := tc.Decrement("uint", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("uint") - if !found { - t.Error("uint was not found") - } - if x.(uint) != 3 { - t.Error("uint is not 3:", x) - } -} - -func TestDecrementWithUintptr(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uintptr", uintptr(5), DefaultExpiration) - err := tc.Decrement("uintptr", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("uintptr") - if !found { - t.Error("uintptr was not found") - } - if x.(uintptr) != 3 { - t.Error("uintptr is not 3:", x) - } -} - -func TestDecrementWithUint8(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint8", uint8(5), DefaultExpiration) - err := tc.Decrement("uint8", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("uint8") - if !found { - t.Error("uint8 was not found") - } - if x.(uint8) != 3 { - t.Error("uint8 is not 3:", x) - } -} - -func TestDecrementWithUint16(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint16", uint16(5), DefaultExpiration) - err := tc.Decrement("uint16", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("uint16") - if !found { - t.Error("uint16 was not found") - } - if x.(uint16) != 3 { - t.Error("uint16 is not 3:", x) - } -} - -func TestDecrementWithUint32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint32", uint32(5), DefaultExpiration) - err := tc.Decrement("uint32", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("uint32") - if !found { - t.Error("uint32 was not found") - } - if x.(uint32) != 3 { - t.Error("uint32 is not 3:", x) - } -} - -func TestDecrementWithUint64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint64", uint64(5), DefaultExpiration) - err := tc.Decrement("uint64", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("uint64") - if !found { - t.Error("uint64 was not found") - } - if x.(uint64) != 3 { - t.Error("uint64 is not 3:", x) - } -} - -func TestDecrementWithFloat32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float32", float32(5.5), DefaultExpiration) - err := tc.Decrement("float32", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("float32") - if !found { - t.Error("float32 was not found") - } - if x.(float32) != 3.5 { - t.Error("float32 is not 3:", x) - } -} - -func TestDecrementWithFloat64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float64", float64(5.5), DefaultExpiration) - err := tc.Decrement("float64", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("float64") - if !found { - t.Error("float64 was not found") - } - if x.(float64) != 3.5 { - t.Error("float64 is not 3:", x) - } -} - -func TestDecrementFloatWithFloat32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float32", float32(5.5), DefaultExpiration) - err := tc.DecrementFloat("float32", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("float32") - if !found { - t.Error("float32 was not found") - } - if x.(float32) != 3.5 { - t.Error("float32 is not 3:", x) - } -} - -func TestDecrementFloatWithFloat64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float64", float64(5.5), DefaultExpiration) - err := tc.DecrementFloat("float64", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - x, found := tc.Get("float64") - if !found { - t.Error("float64 was not found") - } - if x.(float64) != 3.5 { - t.Error("float64 is not 3:", x) - } -} - -func TestIncrementInt(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tint", 1, DefaultExpiration) - n, err := tc.IncrementInt("tint", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tint") - if !found { - t.Error("tint was not found") - } - if x.(int) != 3 { - t.Error("tint is not 3:", x) - } -} - -func TestIncrementInt8(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tint8", int8(1), DefaultExpiration) - n, err := tc.IncrementInt8("tint8", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tint8") - if !found { - t.Error("tint8 was not found") - } - if x.(int8) != 3 { - t.Error("tint8 is not 3:", x) - } -} - -func TestIncrementInt16(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tint16", int16(1), DefaultExpiration) - n, err := tc.IncrementInt16("tint16", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tint16") - if !found { - t.Error("tint16 was not found") - } - if x.(int16) != 3 { - t.Error("tint16 is not 3:", x) - } -} - -func TestIncrementInt32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tint32", int32(1), DefaultExpiration) - n, err := tc.IncrementInt32("tint32", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tint32") - if !found { - t.Error("tint32 was not found") - } - if x.(int32) != 3 { - t.Error("tint32 is not 3:", x) - } -} - -func TestIncrementInt64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tint64", int64(1), DefaultExpiration) - n, err := tc.IncrementInt64("tint64", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tint64") - if !found { - t.Error("tint64 was not found") - } - if x.(int64) != 3 { - t.Error("tint64 is not 3:", x) - } -} - -func TestIncrementUint(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuint", uint(1), DefaultExpiration) - n, err := tc.IncrementUint("tuint", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tuint") - if !found { - t.Error("tuint was not found") - } - if x.(uint) != 3 { - t.Error("tuint is not 3:", x) - } -} - -func TestIncrementUintptr(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuintptr", uintptr(1), DefaultExpiration) - n, err := tc.IncrementUintptr("tuintptr", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tuintptr") - if !found { - t.Error("tuintptr was not found") - } - if x.(uintptr) != 3 { - t.Error("tuintptr is not 3:", x) - } -} - -func TestIncrementUint8(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuint8", uint8(1), DefaultExpiration) - n, err := tc.IncrementUint8("tuint8", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tuint8") - if !found { - t.Error("tuint8 was not found") - } - if x.(uint8) != 3 { - t.Error("tuint8 is not 3:", x) - } -} - -func TestIncrementUint16(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuint16", uint16(1), DefaultExpiration) - n, err := tc.IncrementUint16("tuint16", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tuint16") - if !found { - t.Error("tuint16 was not found") - } - if x.(uint16) != 3 { - t.Error("tuint16 is not 3:", x) - } -} - -func TestIncrementUint32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuint32", uint32(1), DefaultExpiration) - n, err := tc.IncrementUint32("tuint32", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tuint32") - if !found { - t.Error("tuint32 was not found") - } - if x.(uint32) != 3 { - t.Error("tuint32 is not 3:", x) - } -} - -func TestIncrementUint64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("tuint64", uint64(1), DefaultExpiration) - n, err := tc.IncrementUint64("tuint64", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("tuint64") - if !found { - t.Error("tuint64 was not found") - } - if x.(uint64) != 3 { - t.Error("tuint64 is not 3:", x) - } -} - -func TestIncrementFloat32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float32", float32(1.5), DefaultExpiration) - n, err := tc.IncrementFloat32("float32", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3.5 { - t.Error("Returned number is not 3.5:", n) - } - x, found := tc.Get("float32") - if !found { - t.Error("float32 was not found") - } - if x.(float32) != 3.5 { - t.Error("float32 is not 3.5:", x) - } -} - -func TestIncrementFloat64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float64", float64(1.5), DefaultExpiration) - n, err := tc.IncrementFloat64("float64", 2) - if err != nil { - t.Error("Error incrementing:", err) - } - if n != 3.5 { - t.Error("Returned number is not 3.5:", n) - } - x, found := tc.Get("float64") - if !found { - t.Error("float64 was not found") - } - if x.(float64) != 3.5 { - t.Error("float64 is not 3.5:", x) - } -} - -func TestDecrementInt8(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("int8", int8(5), DefaultExpiration) - n, err := tc.DecrementInt8("int8", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("int8") - if !found { - t.Error("int8 was not found") - } - if x.(int8) != 3 { - t.Error("int8 is not 3:", x) - } -} - -func TestDecrementInt16(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("int16", int16(5), DefaultExpiration) - n, err := tc.DecrementInt16("int16", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("int16") - if !found { - t.Error("int16 was not found") - } - if x.(int16) != 3 { - t.Error("int16 is not 3:", x) - } -} - -func TestDecrementInt32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("int32", int32(5), DefaultExpiration) - n, err := tc.DecrementInt32("int32", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("int32") - if !found { - t.Error("int32 was not found") - } - if x.(int32) != 3 { - t.Error("int32 is not 3:", x) - } -} - -func TestDecrementInt64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("int64", int64(5), DefaultExpiration) - n, err := tc.DecrementInt64("int64", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("int64") - if !found { - t.Error("int64 was not found") - } - if x.(int64) != 3 { - t.Error("int64 is not 3:", x) - } -} - -func TestDecrementUint(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint", uint(5), DefaultExpiration) - n, err := tc.DecrementUint("uint", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("uint") - if !found { - t.Error("uint was not found") - } - if x.(uint) != 3 { - t.Error("uint is not 3:", x) - } -} - -func TestDecrementUintptr(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uintptr", uintptr(5), DefaultExpiration) - n, err := tc.DecrementUintptr("uintptr", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("uintptr") - if !found { - t.Error("uintptr was not found") - } - if x.(uintptr) != 3 { - t.Error("uintptr is not 3:", x) - } -} - -func TestDecrementUint8(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint8", uint8(5), DefaultExpiration) - n, err := tc.DecrementUint8("uint8", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("uint8") - if !found { - t.Error("uint8 was not found") - } - if x.(uint8) != 3 { - t.Error("uint8 is not 3:", x) - } -} - -func TestDecrementUint16(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint16", uint16(5), DefaultExpiration) - n, err := tc.DecrementUint16("uint16", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("uint16") - if !found { - t.Error("uint16 was not found") - } - if x.(uint16) != 3 { - t.Error("uint16 is not 3:", x) - } -} - -func TestDecrementUint32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint32", uint32(5), DefaultExpiration) - n, err := tc.DecrementUint32("uint32", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("uint32") - if !found { - t.Error("uint32 was not found") - } - if x.(uint32) != 3 { - t.Error("uint32 is not 3:", x) - } -} - -func TestDecrementUint64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint64", uint64(5), DefaultExpiration) - n, err := tc.DecrementUint64("uint64", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("uint64") - if !found { - t.Error("uint64 was not found") - } - if x.(uint64) != 3 { - t.Error("uint64 is not 3:", x) - } -} - -func TestDecrementFloat32(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float32", float32(5), DefaultExpiration) - n, err := tc.DecrementFloat32("float32", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("float32") - if !found { - t.Error("float32 was not found") - } - if x.(float32) != 3 { - t.Error("float32 is not 3:", x) - } -} - -func TestDecrementFloat64(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("float64", float64(5), DefaultExpiration) - n, err := tc.DecrementFloat64("float64", 2) - if err != nil { - t.Error("Error decrementing:", err) - } - if n != 3 { - t.Error("Returned number is not 3:", n) - } - x, found := tc.Get("float64") - if !found { - t.Error("float64 was not found") - } - if x.(float64) != 3 { - t.Error("float64 is not 3:", x) - } -} - func TestAdd(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, string](DefaultExpiration, 0) err := tc.Add("foo", "bar", DefaultExpiration) if err != nil { t.Error("Couldn't add foo even though it shouldn't exist") @@ -1125,7 +143,7 @@ func TestAdd(t *testing.T) { } func TestReplace(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, string](DefaultExpiration, 0) err := tc.Replace("foo", "bar", DefaultExpiration) if err == nil { t.Error("Replaced foo when it shouldn't exist") @@ -1138,7 +156,7 @@ func TestReplace(t *testing.T) { } func TestDelete(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, string](DefaultExpiration, 0) tc.Set("foo", "bar", DefaultExpiration) tc.Delete("foo") x, found := tc.Get("foo") @@ -1151,7 +169,7 @@ func TestDelete(t *testing.T) { } func TestItemCount(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, string](DefaultExpiration, 0) tc.Set("foo", "1", DefaultExpiration) tc.Set("bar", "2", DefaultExpiration) tc.Set("baz", "3", DefaultExpiration) @@ -1161,7 +179,7 @@ func TestItemCount(t *testing.T) { } func TestFlush(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, string](DefaultExpiration, 0) tc.Set("foo", "bar", DefaultExpiration) tc.Set("baz", "yes", DefaultExpiration) tc.Flush() @@ -1181,58 +199,15 @@ func TestFlush(t *testing.T) { } } -func TestIncrementOverflowInt(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("int8", int8(127), DefaultExpiration) - err := tc.Increment("int8", 1) - if err != nil { - t.Error("Error incrementing int8:", err) - } - x, _ := tc.Get("int8") - int8 := x.(int8) - if int8 != -128 { - t.Error("int8 did not overflow as expected; value:", int8) - } - -} - -func TestIncrementOverflowUint(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint8", uint8(255), DefaultExpiration) - err := tc.Increment("uint8", 1) - if err != nil { - t.Error("Error incrementing int8:", err) - } - x, _ := tc.Get("uint8") - uint8 := x.(uint8) - if uint8 != 0 { - t.Error("uint8 did not overflow as expected; value:", uint8) - } -} - -func TestDecrementUnderflowUint(t *testing.T) { - tc := New(DefaultExpiration, 0) - tc.Set("uint8", uint8(0), DefaultExpiration) - err := tc.Decrement("uint8", 1) - if err != nil { - t.Error("Error decrementing int8:", err) - } - x, _ := tc.Get("uint8") - uint8 := x.(uint8) - if uint8 != 255 { - t.Error("uint8 did not underflow as expected; value:", uint8) - } -} - func TestOnEvicted(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, int](DefaultExpiration, 0) tc.Set("foo", 3, DefaultExpiration) if tc.onEvicted != nil { t.Fatal("tc.onEvicted is not nil") } works := false - tc.OnEvicted(func(k string, v interface{}) { - if k == "foo" && v.(int) == 3 { + tc.OnEvicted(func(k string, v int) { + if k == "foo" && v == 3 { works = true } tc.Set("bar", 4, DefaultExpiration) @@ -1242,13 +217,13 @@ func TestOnEvicted(t *testing.T) { if !works { t.Error("works bool not true") } - if x.(int) != 4 { + if *x != 4 { t.Error("bar was not 4") } } func TestCacheSerialization(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, any](DefaultExpiration, 0) testFillAndSerialize(t, tc) // Check if gob.Register behaves properly even after multiple gob.Register @@ -1256,7 +231,7 @@ func TestCacheSerialization(t *testing.T) { testFillAndSerialize(t, tc) } -func testFillAndSerialize(t *testing.T, tc *Cache) { +func testFillAndSerialize(t *testing.T, tc *Cache[string, any]) { tc.Set("a", "a", DefaultExpiration) tc.Set("b", "b", DefaultExpiration) tc.Set("c", "c", DefaultExpiration) @@ -1267,14 +242,14 @@ func testFillAndSerialize(t *testing.T, tc *Cache) { {Num: 3}, }, DefaultExpiration) tc.Set("[]*struct", []*TestStruct{ - &TestStruct{Num: 4}, - &TestStruct{Num: 5}, + {Num: 4}, + {Num: 5}, }, DefaultExpiration) tc.Set("structception", &TestStruct{ Num: 42, Children: []*TestStruct{ - &TestStruct{Num: 6174}, - &TestStruct{Num: 4716}, + {Num: 6174}, + {Num: 4716}, }, }, DefaultExpiration) @@ -1284,7 +259,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache) { t.Fatal("Couldn't save cache to fp:", err) } - oc := New(DefaultExpiration, 0) + oc := New[string, any](DefaultExpiration, 0) err = oc.Load(fp) if err != nil { t.Fatal("Couldn't load cache from fp:", err) @@ -1294,7 +269,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache) { if !found { t.Error("a was not found") } - if a.(string) != "a" { + if (*a).(string) != "a" { t.Error("a is not a") } @@ -1302,7 +277,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache) { if !found { t.Error("b was not found") } - if b.(string) != "b" { + if (*b).(string) != "b" { t.Error("b is not b") } @@ -1310,7 +285,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache) { if !found { t.Error("c was not found") } - if c.(string) != "c" { + if (*c).(string) != "c" { t.Error("c is not c") } @@ -1324,7 +299,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache) { if !found { t.Error("*struct was not found") } - if s1.(*TestStruct).Num != 1 { + if (*s1).(*TestStruct).Num != 1 { t.Error("*struct.Num is not 1") } @@ -1332,7 +307,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache) { if !found { t.Error("[]struct was not found") } - s2r := s2.([]TestStruct) + s2r := (*s2).([]TestStruct) if len(s2r) != 2 { t.Error("Length of s2r is not 2") } @@ -1347,7 +322,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache) { if !found { t.Error("[]*struct was not found") } - s3r := s3.([]*TestStruct) + s3r := (*s3).([]*TestStruct) if len(s3r) != 2 { t.Error("Length of s3r is not 2") } @@ -1362,7 +337,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache) { if !found { t.Error("structception was not found") } - s4r := s4.(*TestStruct) + s4r := (*s4).(*TestStruct) if len(s4r.Children) != 2 { t.Error("Length of s4r.Children is not 2") } @@ -1375,7 +350,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache) { } func TestFileSerialization(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, string](DefaultExpiration, 0) tc.Add("a", "a", DefaultExpiration) tc.Add("b", "b", DefaultExpiration) f, err := ioutil.TempFile("", "go-cache-cache.dat") @@ -1386,7 +361,7 @@ func TestFileSerialization(t *testing.T) { f.Close() tc.SaveFile(fname) - oc := New(DefaultExpiration, 0) + oc := New[string, string](DefaultExpiration, 0) oc.Add("a", "aa", 0) // this should not be overwritten err = oc.LoadFile(fname) if err != nil { @@ -1396,7 +371,7 @@ func TestFileSerialization(t *testing.T) { if !found { t.Error("a was not found") } - astr := a.(string) + astr := *a if astr != "aa" { if astr == "a" { t.Error("a was overwritten") @@ -1408,13 +383,13 @@ func TestFileSerialization(t *testing.T) { if !found { t.Error("b was not found") } - if b.(string) != "b" { + if *b != "b" { t.Error("b is not b") } } func TestSerializeUnserializable(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, any](DefaultExpiration, 0) ch := make(chan bool, 1) ch <- true tc.Set("chan", ch, DefaultExpiration) @@ -1435,7 +410,7 @@ func BenchmarkCacheGetNotExpiring(b *testing.B) { func benchmarkCacheGet(b *testing.B, exp time.Duration) { b.StopTimer() - tc := New(exp, 0) + tc := New[string, string](exp, 0) tc.Set("foo", "bar", DefaultExpiration) b.StartTimer() for i := 0; i < b.N; i++ { @@ -1496,7 +471,7 @@ func BenchmarkCacheGetConcurrentNotExpiring(b *testing.B) { func benchmarkCacheGetConcurrent(b *testing.B, exp time.Duration) { b.StopTimer() - tc := New(exp, 0) + tc := New[string, string](exp, 0) tc.Set("foo", "bar", DefaultExpiration) wg := new(sync.WaitGroup) workers := runtime.NumCPU() @@ -1552,7 +527,7 @@ func benchmarkCacheGetManyConcurrent(b *testing.B, exp time.Duration) { // in sharded_test.go. b.StopTimer() n := 10000 - tc := New(exp, 0) + tc := New[string, string](exp, 0) keys := make([]string, n) for i := 0; i < n; i++ { k := "foo" + strconv.Itoa(i) @@ -1584,7 +559,7 @@ func BenchmarkCacheSetNotExpiring(b *testing.B) { func benchmarkCacheSet(b *testing.B, exp time.Duration) { b.StopTimer() - tc := New(exp, 0) + tc := New[string, string](exp, 0) b.StartTimer() for i := 0; i < b.N; i++ { tc.Set("foo", "bar", DefaultExpiration) @@ -1605,7 +580,7 @@ func BenchmarkRWMutexMapSet(b *testing.B) { func BenchmarkCacheSetDelete(b *testing.B) { b.StopTimer() - tc := New(DefaultExpiration, 0) + tc := New[string, string](DefaultExpiration, 0) b.StartTimer() for i := 0; i < b.N; i++ { tc.Set("foo", "bar", DefaultExpiration) @@ -1630,7 +605,7 @@ func BenchmarkRWMutexMapSetDelete(b *testing.B) { func BenchmarkCacheSetDeleteSingleLock(b *testing.B) { b.StopTimer() - tc := New(DefaultExpiration, 0) + tc := New[string, string](DefaultExpiration, 0) b.StartTimer() for i := 0; i < b.N; i++ { tc.mu.Lock() @@ -1653,19 +628,9 @@ func BenchmarkRWMutexMapSetDeleteSingleLock(b *testing.B) { } } -func BenchmarkIncrementInt(b *testing.B) { - b.StopTimer() - tc := New(DefaultExpiration, 0) - tc.Set("foo", 0, DefaultExpiration) - b.StartTimer() - for i := 0; i < b.N; i++ { - tc.IncrementInt("foo", 1) - } -} - func BenchmarkDeleteExpiredLoop(b *testing.B) { b.StopTimer() - tc := New(5*time.Minute, 0) + tc := New[string, string](5*time.Minute, 0) tc.mu.Lock() for i := 0; i < 100000; i++ { tc.set(strconv.Itoa(i), "bar", DefaultExpiration) @@ -1678,7 +643,7 @@ func BenchmarkDeleteExpiredLoop(b *testing.B) { } func TestGetWithExpiration(t *testing.T) { - tc := New(DefaultExpiration, 0) + tc := New[string, any](DefaultExpiration, 0) a, expiration, found := tc.GetWithExpiration("a") if found || a != nil || !expiration.IsZero() { @@ -1707,7 +672,7 @@ func TestGetWithExpiration(t *testing.T) { } if x == nil { t.Error("x for a is nil") - } else if a2 := x.(int); a2+2 != 3 { + } else if a2 := (*x).(int); a2+2 != 3 { t.Error("a2 (which should be 1) plus 2 does not equal 3; value:", a2) } if !expiration.IsZero() { @@ -1720,7 +685,7 @@ func TestGetWithExpiration(t *testing.T) { } if x == nil { t.Error("x for b is nil") - } else if b2 := x.(string); b2+"B" != "bB" { + } else if b2 := (*x).(string); b2+"B" != "bB" { t.Error("b2 (which should be b) plus B does not equal bB; value:", b2) } if !expiration.IsZero() { @@ -1733,7 +698,7 @@ func TestGetWithExpiration(t *testing.T) { } if x == nil { t.Error("x for c is nil") - } else if c2 := x.(float64); c2+1.2 != 4.7 { + } else if c2 := (*x).(float64); c2+1.2 != 4.7 { t.Error("c2 (which should be 3.5) plus 1.2 does not equal 4.7; value:", c2) } if !expiration.IsZero() { @@ -1746,7 +711,7 @@ func TestGetWithExpiration(t *testing.T) { } if x == nil { t.Error("x for d is nil") - } else if d2 := x.(int); d2+2 != 3 { + } else if d2 := (*x).(int); d2+2 != 3 { t.Error("d (which should be 1) plus 2 does not equal 3; value:", d2) } if !expiration.IsZero() { @@ -1759,7 +724,7 @@ func TestGetWithExpiration(t *testing.T) { } if x == nil { t.Error("x for e is nil") - } else if e2 := x.(int); e2+2 != 3 { + } else if e2 := (*x).(int); e2+2 != 3 { t.Error("e (which should be 1) plus 2 does not equal 3; value:", e2) } if expiration.UnixNano() != tc.items["e"].Expiration { From 9192b384abdd9f57d0d2373968bbe0b7ed0eebdb Mon Sep 17 00:00:00 2001 From: Michael Dresner Date: Fri, 18 Mar 2022 22:18:52 +0300 Subject: [PATCH 3/6] Introduce generic ordered cache --- ordered.go | 74 ++++++++++++++++++++++++++++++++++++++++++ ordered_test.go | 86 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 160 insertions(+) create mode 100644 ordered.go create mode 100644 ordered_test.go diff --git a/ordered.go b/ordered.go new file mode 100644 index 0000000..ff304b3 --- /dev/null +++ b/ordered.go @@ -0,0 +1,74 @@ +package cache + +import ( + "fmt" + "time" + + "golang.org/x/exp/constraints" +) + +type OrderedCache[K comparable, V constraints.Ordered] struct { + *orderedCache[K, V] +} + +type orderedCache[K comparable, V constraints.Ordered] struct { + *Cache[K, V] +} + +// Increment an item of type by n. +// Returns incremented item or an error if it was not found. +func (c *orderedCache[K, V]) Increment(k K, n V) (*V, error) { + c.mu.Lock() + v, found := c.items[k] + if !found || v.Expired() { + c.mu.Unlock() + return nil, fmt.Errorf("Item %v not found", k) + } + res := v.Object + n + v.Object = res + c.items[k] = v + c.mu.Unlock() + return &res, nil +} + +// Return a new ordered cache with a given default expiration duration and cleanup +// interval. If the expiration duration is less than one (or NoExpiration), +// the items in the cache never expire (by default), and must be deleted +// manually. If the cleanup interval is less than one, expired items are not +// deleted from the cache before calling c.DeleteExpired(). +func NewOrderedCache[K comparable, V constraints.Ordered](defaultExpiration, cleanupInterval time.Duration) *OrderedCache[K, V] { + return &OrderedCache[K, V]{ + orderedCache: &orderedCache[K, V]{ + Cache: New[K, V](defaultExpiration, cleanupInterval), + }, + } +} + +// Return a new ordered cache with a given default expiration duration and cleanup +// interval. If the expiration duration is less than one (or NoExpiration), +// the items in the cache never expire (by default), and must be deleted +// manually. If the cleanup interval is less than one, expired items are not +// deleted from the cache before calling c.DeleteExpired(). +// +// NewFrom() also accepts an items map which will serve as the underlying map +// for the cache. This is useful for starting from a deserialized cache +// (serialized using e.g. gob.Encode() on c.Items()), or passing in e.g. +// make(map[string]Item[int], 500) to improve startup performance when the cache +// is expected to reach a certain minimum size. +// +// Only the cache's methods synchronize access to this map, so it is not +// recommended to keep any references to the map around after creating a cache. +// If need be, the map can be accessed at a later point using c.Items() (subject +// to the same caveat.) +// +// Note regarding serialization: When using e.g. gob, make sure to +// gob.Register() the individual types stored in the cache before encoding a +// map retrieved with c.Items(), and to register those same types before +// decoding a blob containing an items map. +func NewOrderedCacheFrom[K comparable, V constraints.Ordered](defaultExpiration, cleanupInterval time.Duration, items map[K]Item[V]) *OrderedCache[K, V] { + return &OrderedCache[K, V]{ + orderedCache: &orderedCache[K, V]{ + Cache: NewFrom(defaultExpiration, cleanupInterval, items), + }, + } +} diff --git a/ordered_test.go b/ordered_test.go new file mode 100644 index 0000000..1784b7c --- /dev/null +++ b/ordered_test.go @@ -0,0 +1,86 @@ +package cache + +import "testing" + +func TestIncrementWithInt(t *testing.T) { + tc := NewOrderedCache[string, int](DefaultExpiration, 0) + tc.Set("tint", 1, DefaultExpiration) + n, err := tc.Increment("tint", 2) + if err != nil { + t.Error("Error incrementing:", err) + } + if *n != 3 { + t.Error("Returned number is not 3:", n) + } + x, found := tc.Get("tint") + if !found { + t.Error("tint was not found") + } + if *x != 3 { + t.Error("tint is not 3:", x) + } +} + +func TestIncrementInt8(t *testing.T) { + tc := NewOrderedCache[string, int8](DefaultExpiration, 0) + tc.Set("int8", 1, DefaultExpiration) + n, err := tc.Increment("int8", 2) + if err != nil { + t.Error("Error decrementing:", err) + } + if *n != 3 { + t.Error("Returned number is not 3:", n) + } + x, found := tc.Get("int8") + if !found { + t.Error("int8 was not found") + } + if *x != 3 { + t.Error("int8 is not 3:", x) + } +} + +func TestIncrementOverflowInt(t *testing.T) { + tc := NewOrderedCache[string, int8](DefaultExpiration, 0) + tc.Set("int8", 127, DefaultExpiration) + n, err := tc.Increment("int8", 1) + if err != nil { + t.Error("Error incrementing int8:", err) + } + if *n != -128 { + t.Error("Returned number is not -128:", n) + } + x, _ := tc.Get("int8") + int8 := *x + if int8 != -128 { + t.Error("int8 did not overflow as expected; value:", int8) + } + +} + +func TestIncrementOverflowUint(t *testing.T) { + tc := NewOrderedCache[string, uint8](DefaultExpiration, 0) + tc.Set("uint8", 255, DefaultExpiration) + n, err := tc.Increment("uint8", 1) + if err != nil { + t.Error("Error incrementing int8:", err) + } + if *n != 0 { + t.Error("Returned number is not 0:", n) + } + x, _ := tc.Get("uint8") + uint8 := *x + if uint8 != 0 { + t.Error("uint8 did not overflow as expected; value:", uint8) + } +} + +func BenchmarkIncrement(b *testing.B) { + b.StopTimer() + tc := NewOrderedCache[string, int](DefaultExpiration, 0) + tc.Set("foo", 0, DefaultExpiration) + b.StartTimer() + for i := 0; i < b.N; i++ { + tc.Increment("foo", 1) + } +} From 0d5b08999a1c2ca31ec229feda66812077b779c1 Mon Sep 17 00:00:00 2001 From: Michael Dresner Date: Fri, 18 Mar 2022 22:19:19 +0300 Subject: [PATCH 4/6] Rewrite sharde cache to generic one --- sharded.go | 79 ++++++++++++++++++++++++------------------------- sharded_test.go | 6 ++-- 2 files changed, 42 insertions(+), 43 deletions(-) diff --git a/sharded.go b/sharded.go index bcc0538..a8f7d8b 100644 --- a/sharded.go +++ b/sharded.go @@ -8,6 +8,8 @@ import ( "os" "runtime" "time" + + "golang.org/x/exp/constraints" ) // This is an experimental and unexported (for now) attempt at making a cache @@ -19,15 +21,15 @@ import ( // // See cache_test.go for a few benchmarks. -type unexportedShardedCache struct { - *shardedCache +type unexportedShardedCache[V constraints.Ordered] struct { + *shardedCache[V] } -type shardedCache struct { +type shardedCache[V constraints.Ordered] struct { seed uint32 m uint32 - cs []*cache - janitor *shardedJanitor + cs []*orderedCache[string, V] + janitor *shardedJanitor[V] } // djb2 with better shuffling. 5x faster than FNV with the hash.Hash overhead. @@ -62,43 +64,36 @@ func djb33(seed uint32, k string) uint32 { return d ^ (d >> 16) } -func (sc *shardedCache) bucket(k string) *cache { +func (sc *shardedCache[V]) bucket(k string) *orderedCache[string, V] { return sc.cs[djb33(sc.seed, k)%sc.m] } -func (sc *shardedCache) Set(k string, x interface{}, d time.Duration) { +func (sc *shardedCache[V]) Set(k string, x V, d time.Duration) { sc.bucket(k).Set(k, x, d) } -func (sc *shardedCache) Add(k string, x interface{}, d time.Duration) error { +func (sc *shardedCache[V]) Add(k string, x V, d time.Duration) error { return sc.bucket(k).Add(k, x, d) } -func (sc *shardedCache) Replace(k string, x interface{}, d time.Duration) error { +func (sc *shardedCache[V]) Replace(k string, x V, d time.Duration) error { return sc.bucket(k).Replace(k, x, d) } -func (sc *shardedCache) Get(k string) (interface{}, bool) { +func (sc *shardedCache[V]) Get(k string) (*V, bool) { return sc.bucket(k).Get(k) } -func (sc *shardedCache) Increment(k string, n int64) error { - return sc.bucket(k).Increment(k, n) +func (sc *shardedCache[V]) Increment(k string, n V) error { + _, err := sc.bucket(k).Increment(k, n) + return err } -func (sc *shardedCache) IncrementFloat(k string, n float64) error { - return sc.bucket(k).IncrementFloat(k, n) -} - -func (sc *shardedCache) Decrement(k string, n int64) error { - return sc.bucket(k).Decrement(k, n) -} - -func (sc *shardedCache) Delete(k string) { +func (sc *shardedCache[V]) Delete(k string) { sc.bucket(k).Delete(k) } -func (sc *shardedCache) DeleteExpired() { +func (sc *shardedCache[V]) DeleteExpired() { for _, v := range sc.cs { v.DeleteExpired() } @@ -109,26 +104,26 @@ func (sc *shardedCache) DeleteExpired() { // fields of the items should be checked. Note that explicit synchronization // is needed to use a cache and its corresponding Items() return values at // the same time, as the maps are shared. -func (sc *shardedCache) Items() []map[string]Item { - res := make([]map[string]Item, len(sc.cs)) +func (sc *shardedCache[V]) Items() []map[string]Item[V] { + res := make([]map[string]Item[V], len(sc.cs)) for i, v := range sc.cs { res[i] = v.Items() } return res } -func (sc *shardedCache) Flush() { +func (sc *shardedCache[V]) Flush() { for _, v := range sc.cs { v.Flush() } } -type shardedJanitor struct { +type shardedJanitor[V constraints.Ordered] struct { Interval time.Duration stop chan bool } -func (j *shardedJanitor) Run(sc *shardedCache) { +func (j *shardedJanitor[V]) Run(sc *shardedCache[V]) { j.stop = make(chan bool) tick := time.Tick(j.Interval) for { @@ -141,19 +136,19 @@ func (j *shardedJanitor) Run(sc *shardedCache) { } } -func stopShardedJanitor(sc *unexportedShardedCache) { +func stopShardedJanitor[V constraints.Ordered](sc *unexportedShardedCache[V]) { sc.janitor.stop <- true } -func runShardedJanitor(sc *shardedCache, ci time.Duration) { - j := &shardedJanitor{ +func runShardedJanitor[V constraints.Ordered](sc *shardedCache[V], ci time.Duration) { + j := &shardedJanitor[V]{ Interval: ci, } sc.janitor = j go j.Run(sc) } -func newShardedCache(n int, de time.Duration) *shardedCache { +func newShardedCache[V constraints.Ordered](n int, de time.Duration) *shardedCache[V] { max := big.NewInt(0).SetUint64(uint64(math.MaxUint32)) rnd, err := rand.Int(rand.Reader, max) var seed uint32 @@ -163,30 +158,34 @@ func newShardedCache(n int, de time.Duration) *shardedCache { } else { seed = uint32(rnd.Uint64()) } - sc := &shardedCache{ + sc := &shardedCache[V]{ seed: seed, m: uint32(n), - cs: make([]*cache, n), + cs: make([]*orderedCache[string, V], n), } for i := 0; i < n; i++ { - c := &cache{ - defaultExpiration: de, - items: map[string]Item{}, + c := &orderedCache[string, V]{ + Cache: &Cache[string, V]{ + cache: &cache[string, V]{ + defaultExpiration: de, + items: map[string]Item[V]{}, + }, + }, } sc.cs[i] = c } return sc } -func unexportedNewSharded(defaultExpiration, cleanupInterval time.Duration, shards int) *unexportedShardedCache { +func unexportedNewSharded[V constraints.Ordered](defaultExpiration, cleanupInterval time.Duration, shards int) *unexportedShardedCache[V] { if defaultExpiration == 0 { defaultExpiration = -1 } - sc := newShardedCache(shards, defaultExpiration) - SC := &unexportedShardedCache{sc} + sc := newShardedCache[V](shards, defaultExpiration) + SC := &unexportedShardedCache[V]{sc} if cleanupInterval > 0 { runShardedJanitor(sc, cleanupInterval) - runtime.SetFinalizer(SC, stopShardedJanitor) + runtime.SetFinalizer(SC, stopShardedJanitor[V]) } return SC } diff --git a/sharded_test.go b/sharded_test.go index 84220ad..0216e2f 100644 --- a/sharded_test.go +++ b/sharded_test.go @@ -27,7 +27,7 @@ var shardedKeys = []string{ } func TestShardedCache(t *testing.T) { - tc := unexportedNewSharded(DefaultExpiration, 0, 13) + tc := unexportedNewSharded[string](DefaultExpiration, 0, 13) for _, v := range shardedKeys { tc.Set(v, "value", DefaultExpiration) } @@ -43,7 +43,7 @@ func BenchmarkShardedCacheGetNotExpiring(b *testing.B) { func benchmarkShardedCacheGet(b *testing.B, exp time.Duration) { b.StopTimer() - tc := unexportedNewSharded(exp, 0, 10) + tc := unexportedNewSharded[string](exp, 0, 10) tc.Set("foobarba", "zquux", DefaultExpiration) b.StartTimer() for i := 0; i < b.N; i++ { @@ -62,7 +62,7 @@ func BenchmarkShardedCacheGetManyConcurrentNotExpiring(b *testing.B) { func benchmarkShardedCacheGetManyConcurrent(b *testing.B, exp time.Duration) { b.StopTimer() n := 10000 - tsc := unexportedNewSharded(exp, 0, 20) + tsc := unexportedNewSharded[string](exp, 0, 20) keys := make([]string, n) for i := 0; i < n; i++ { k := "foo" + strconv.Itoa(i) From 133b774867fab9b2cc19321bce97b9eca332c682 Mon Sep 17 00:00:00 2001 From: Michael Dresner Date: Thu, 24 Mar 2022 23:41:39 +0300 Subject: [PATCH 5/6] Return zero value instead of nil --- cache.go | 47 +++++++++++++++++++++---------------- cache_test.go | 61 ++++++++++++++++++++++++------------------------- ordered.go | 7 +++--- ordered_test.go | 22 ++++++++---------- sharded.go | 2 +- 5 files changed, 72 insertions(+), 67 deletions(-) diff --git a/cache.go b/cache.go index a6d8f01..83d6ed4 100644 --- a/cache.go +++ b/cache.go @@ -115,68 +115,74 @@ func (c *cache[K, V]) Replace(k K, x V, d time.Duration) error { return nil } -// Get an item from the cache. Returns the item or nil, and a bool indicating +// Get an item from the cache. Returns the item or zero value, and a bool indicating // whether the key was found. -func (c *cache[K, V]) Get(k K) (*V, bool) { +func (c *cache[K, V]) Get(k K) (V, bool) { + var zeroValue V + c.mu.RLock() // "Inlining" of get and Expired item, found := c.items[k] if !found { c.mu.RUnlock() - return nil, false + return zeroValue, false } if item.Expiration > 0 { if time.Now().UnixNano() > item.Expiration { c.mu.RUnlock() - return nil, false + return zeroValue, false } } c.mu.RUnlock() - return &item.Object, true + return item.Object, true } // GetWithExpiration returns an item and its expiration time from the cache. -// It returns the item or nil, the expiration time if one is set (if the item +// It returns the item or zero value, the expiration time if one is set (if the item // never expires a zero value for time.Time is returned), and a bool indicating // whether the key was found. -func (c *cache[K, V]) GetWithExpiration(k K) (*V, time.Time, bool) { +func (c *cache[K, V]) GetWithExpiration(k K) (V, time.Time, bool) { + var zeroValue V + c.mu.RLock() // "Inlining" of get and Expired item, found := c.items[k] if !found { c.mu.RUnlock() - return nil, time.Time{}, false + return zeroValue, time.Time{}, false } if item.Expiration > 0 { if time.Now().UnixNano() > item.Expiration { c.mu.RUnlock() - return nil, time.Time{}, false + return zeroValue, time.Time{}, false } // Return the item and the expiration time c.mu.RUnlock() - return &item.Object, time.Unix(0, item.Expiration), true + return item.Object, time.Unix(0, item.Expiration), true } // If expiration <= 0 (i.e. no expiration time set) then return the item // and a zeroed time.Time c.mu.RUnlock() - return &item.Object, time.Time{}, true + return item.Object, time.Time{}, true } -func (c *cache[K, V]) get(k K) (*V, bool) { +func (c *cache[K, V]) get(k K) (V, bool) { + var zeroValue V + item, found := c.items[k] if !found { - return nil, false + return zeroValue, false } // "Inlining" of Expired if item.Expiration > 0 { if time.Now().UnixNano() > item.Expiration { - return nil, false + return zeroValue, false } } - return &item.Object, true + return item.Object, true } // Delete an item from the cache. Does nothing if the key is not in the cache. @@ -185,19 +191,20 @@ func (c *cache[K, V]) Delete(k K) { v, evicted := c.delete(k) c.mu.Unlock() if evicted { - c.onEvicted(k, *v) + c.onEvicted(k, v) } } -func (c *cache[K, V]) delete(k K) (*V, bool) { +func (c *cache[K, V]) delete(k K) (V, bool) { + var zeroValue V if c.onEvicted != nil { if v, found := c.items[k]; found { delete(c.items, k) - return &v.Object, true + return v.Object, true } } delete(c.items, k) - return nil, false + return zeroValue, false } type keyAndValue[K comparable, V any] struct { @@ -215,7 +222,7 @@ func (c *cache[K, V]) DeleteExpired() { if v.Expiration > 0 && now > v.Expiration { ov, evicted := c.delete(k) if evicted { - evictedItems = append(evictedItems, keyAndValue[K, V]{k, *ov}) + evictedItems = append(evictedItems, keyAndValue[K, V]{k, ov}) } } } diff --git a/cache_test.go b/cache_test.go index 84ebefa..3e0b6d3 100644 --- a/cache_test.go +++ b/cache_test.go @@ -19,17 +19,17 @@ func TestCache(t *testing.T) { tc := New[string, int](DefaultExpiration, 0) a, found := tc.Get("a") - if found || a != nil { + if found || a != 0 { t.Error("Getting A found value that shouldn't exist:", a) } b, found := tc.Get("b") - if found || b != nil { + if found || b != 0 { t.Error("Getting B found value that shouldn't exist:", b) } c, found := tc.Get("c") - if found || c != nil { + if found || c != 0 { t.Error("Getting C found value that shouldn't exist:", c) } @@ -39,9 +39,9 @@ func TestCache(t *testing.T) { if !found { t.Error("a was not found while getting a2") } - if x == nil { - t.Error("x for a is nil") - } else if a2 := *x; a2+2 != 3 { + if x == 0 { + t.Error("x for a is zero value") + } else if a2 := x; a2+2 != 3 { t.Error("a2 (which should be 1) plus 2 does not equal 3; value:", a2) } } @@ -100,14 +100,14 @@ func TestNewFrom(t *testing.T) { if !found { t.Fatal("Did not find a") } - if *a != 1 { + if a != 1 { t.Fatal("a is not 1") } b, found := tc.Get("b") if !found { t.Fatal("Did not find b") } - if *b != 2 { + if b != 2 { t.Fatal("b is not 2") } } @@ -163,8 +163,8 @@ func TestDelete(t *testing.T) { if found { t.Error("foo was found, but it should have been deleted") } - if x != nil { - t.Error("x is not nil:", x) + if x != "" { + t.Error("x is not zero value:", x) } } @@ -187,15 +187,15 @@ func TestFlush(t *testing.T) { if found { t.Error("foo was found, but it should have been deleted") } - if x != nil { - t.Error("x is not nil:", x) + if x != "" { + t.Error("x is not zero value:", x) } x, found = tc.Get("baz") if found { t.Error("baz was found, but it should have been deleted") } - if x != nil { - t.Error("x is not nil:", x) + if x != "" { + t.Error("x is not zero value:", x) } } @@ -217,7 +217,7 @@ func TestOnEvicted(t *testing.T) { if !works { t.Error("works bool not true") } - if *x != 4 { + if x != 4 { t.Error("bar was not 4") } } @@ -269,7 +269,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache[string, any]) { if !found { t.Error("a was not found") } - if (*a).(string) != "a" { + if a.(string) != "a" { t.Error("a is not a") } @@ -277,7 +277,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache[string, any]) { if !found { t.Error("b was not found") } - if (*b).(string) != "b" { + if b.(string) != "b" { t.Error("b is not b") } @@ -285,7 +285,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache[string, any]) { if !found { t.Error("c was not found") } - if (*c).(string) != "c" { + if c.(string) != "c" { t.Error("c is not c") } @@ -299,7 +299,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache[string, any]) { if !found { t.Error("*struct was not found") } - if (*s1).(*TestStruct).Num != 1 { + if s1.(*TestStruct).Num != 1 { t.Error("*struct.Num is not 1") } @@ -307,7 +307,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache[string, any]) { if !found { t.Error("[]struct was not found") } - s2r := (*s2).([]TestStruct) + s2r := s2.([]TestStruct) if len(s2r) != 2 { t.Error("Length of s2r is not 2") } @@ -322,7 +322,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache[string, any]) { if !found { t.Error("[]*struct was not found") } - s3r := (*s3).([]*TestStruct) + s3r := s3.([]*TestStruct) if len(s3r) != 2 { t.Error("Length of s3r is not 2") } @@ -337,7 +337,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache[string, any]) { if !found { t.Error("structception was not found") } - s4r := (*s4).(*TestStruct) + s4r := s4.(*TestStruct) if len(s4r.Children) != 2 { t.Error("Length of s4r.Children is not 2") } @@ -371,9 +371,8 @@ func TestFileSerialization(t *testing.T) { if !found { t.Error("a was not found") } - astr := *a - if astr != "aa" { - if astr == "a" { + if a != "aa" { + if a == "a" { t.Error("a was overwritten") } else { t.Error("a is not aa") @@ -383,7 +382,7 @@ func TestFileSerialization(t *testing.T) { if !found { t.Error("b was not found") } - if *b != "b" { + if b != "b" { t.Error("b is not b") } } @@ -672,7 +671,7 @@ func TestGetWithExpiration(t *testing.T) { } if x == nil { t.Error("x for a is nil") - } else if a2 := (*x).(int); a2+2 != 3 { + } else if a2 := x.(int); a2+2 != 3 { t.Error("a2 (which should be 1) plus 2 does not equal 3; value:", a2) } if !expiration.IsZero() { @@ -685,7 +684,7 @@ func TestGetWithExpiration(t *testing.T) { } if x == nil { t.Error("x for b is nil") - } else if b2 := (*x).(string); b2+"B" != "bB" { + } else if b2 := x.(string); b2+"B" != "bB" { t.Error("b2 (which should be b) plus B does not equal bB; value:", b2) } if !expiration.IsZero() { @@ -698,7 +697,7 @@ func TestGetWithExpiration(t *testing.T) { } if x == nil { t.Error("x for c is nil") - } else if c2 := (*x).(float64); c2+1.2 != 4.7 { + } else if c2 := x.(float64); c2+1.2 != 4.7 { t.Error("c2 (which should be 3.5) plus 1.2 does not equal 4.7; value:", c2) } if !expiration.IsZero() { @@ -711,7 +710,7 @@ func TestGetWithExpiration(t *testing.T) { } if x == nil { t.Error("x for d is nil") - } else if d2 := (*x).(int); d2+2 != 3 { + } else if d2 := x.(int); d2+2 != 3 { t.Error("d (which should be 1) plus 2 does not equal 3; value:", d2) } if !expiration.IsZero() { @@ -724,7 +723,7 @@ func TestGetWithExpiration(t *testing.T) { } if x == nil { t.Error("x for e is nil") - } else if e2 := (*x).(int); e2+2 != 3 { + } else if e2 := x.(int); e2+2 != 3 { t.Error("e (which should be 1) plus 2 does not equal 3; value:", e2) } if expiration.UnixNano() != tc.items["e"].Expiration { diff --git a/ordered.go b/ordered.go index ff304b3..ba92683 100644 --- a/ordered.go +++ b/ordered.go @@ -17,18 +17,19 @@ type orderedCache[K comparable, V constraints.Ordered] struct { // Increment an item of type by n. // Returns incremented item or an error if it was not found. -func (c *orderedCache[K, V]) Increment(k K, n V) (*V, error) { +func (c *orderedCache[K, V]) Increment(k K, n V) (V, error) { + var zeroValue V c.mu.Lock() v, found := c.items[k] if !found || v.Expired() { c.mu.Unlock() - return nil, fmt.Errorf("Item %v not found", k) + return zeroValue, fmt.Errorf("Item %v not found", k) } res := v.Object + n v.Object = res c.items[k] = v c.mu.Unlock() - return &res, nil + return res, nil } // Return a new ordered cache with a given default expiration duration and cleanup diff --git a/ordered_test.go b/ordered_test.go index 1784b7c..c77e3fe 100644 --- a/ordered_test.go +++ b/ordered_test.go @@ -9,14 +9,14 @@ func TestIncrementWithInt(t *testing.T) { if err != nil { t.Error("Error incrementing:", err) } - if *n != 3 { + if n != 3 { t.Error("Returned number is not 3:", n) } x, found := tc.Get("tint") if !found { t.Error("tint was not found") } - if *x != 3 { + if x != 3 { t.Error("tint is not 3:", x) } } @@ -28,14 +28,14 @@ func TestIncrementInt8(t *testing.T) { if err != nil { t.Error("Error decrementing:", err) } - if *n != 3 { + if n != 3 { t.Error("Returned number is not 3:", n) } x, found := tc.Get("int8") if !found { t.Error("int8 was not found") } - if *x != 3 { + if x != 3 { t.Error("int8 is not 3:", x) } } @@ -47,13 +47,12 @@ func TestIncrementOverflowInt(t *testing.T) { if err != nil { t.Error("Error incrementing int8:", err) } - if *n != -128 { + if n != -128 { t.Error("Returned number is not -128:", n) } x, _ := tc.Get("int8") - int8 := *x - if int8 != -128 { - t.Error("int8 did not overflow as expected; value:", int8) + if x != -128 { + t.Error("int8 did not overflow as expected; value:", x) } } @@ -65,13 +64,12 @@ func TestIncrementOverflowUint(t *testing.T) { if err != nil { t.Error("Error incrementing int8:", err) } - if *n != 0 { + if n != 0 { t.Error("Returned number is not 0:", n) } x, _ := tc.Get("uint8") - uint8 := *x - if uint8 != 0 { - t.Error("uint8 did not overflow as expected; value:", uint8) + if x != 0 { + t.Error("uint8 did not overflow as expected; value:", x) } } diff --git a/sharded.go b/sharded.go index a8f7d8b..b2758cb 100644 --- a/sharded.go +++ b/sharded.go @@ -80,7 +80,7 @@ func (sc *shardedCache[V]) Replace(k string, x V, d time.Duration) error { return sc.bucket(k).Replace(k, x, d) } -func (sc *shardedCache[V]) Get(k string) (*V, bool) { +func (sc *shardedCache[V]) Get(k string) (V, bool) { return sc.bucket(k).Get(k) } From 05cdbdb6c10f82f9dd52509500963910c37be045 Mon Sep 17 00:00:00 2001 From: Michael Dresner Date: Thu, 24 Mar 2022 23:47:55 +0300 Subject: [PATCH 6/6] Delete irrelevant examples --- README.md | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/README.md b/README.md index c5789cc..481e457 100644 --- a/README.md +++ b/README.md @@ -45,34 +45,10 @@ func main() { fmt.Println(foo) } - // Since Go is statically typed, and cache values can be anything, type - // assertion is needed when values are being passed to functions that don't - // take arbitrary types, (i.e. interface{}). The simplest way to do this for - // values which will only be used once--e.g. for passing to another - // function--is: - foo, found := c.Get("foo") - if found { - MyFunction(foo.(string)) - } - - // This gets tedious if the value is used several times in the same function. - // You might do either of the following instead: - if x, found := c.Get("foo"); found { - foo := x.(string) - // ... - } - // or - var foo string - if x, found := c.Get("foo"); found { - foo = x.(string) - } - // ... - // foo can then be passed around freely as a string - // Want performance? Store pointers! c.Set("foo", &MyStruct, cache.DefaultExpiration) if x, found := c.Get("foo"); found { - foo := x.(*MyStruct) + foo := x // ... } }