Compare commits

..

No commits in common. 'master' and 'v1.0.0' have entirely different histories.

@ -1,5 +0,0 @@
pipeline:
build:
image: golang
commands:
- go test

@ -1,14 +1,10 @@
# go-cache # go-cache
```
[![test-and-lint](https://github.com/num30/go-cache/actions/workflows/test.yaml/badge.svg)](https://github.com/num30/go-cache/actions/workflows/test.yaml) [![test-and-lint](https://github.com/num30/go-cache/actions/workflows/test.yaml/badge.svg)](https://github.com/num30/go-cache/actions/workflows/test.yaml)
[![codecov](https://codecov.io/gh/num30/go-cache/branch/main/graph/badge.svg?token=FMvJ4TbC2r)](https://codecov.io/gh/num30/go-cache) [![codecov](https://codecov.io/gh/num30/go-cache/branch/main/graph/badge.svg?token=FMvJ4TbC2r)](https://codecov.io/gh/num30/go-cache)
[![Go Report Card](https://goreportcard.com/badge/github.com/num30/go-cache)](https://goreportcard.com/report/github.com/num30/go-cache) [![Go Report Card](https://goreportcard.com/badge/github.com/num30/go-cache)](https://goreportcard.com/report/github.com/num30/go-cache)
[![Go Reference](https://pkg.go.dev/badge/github.com/num30/go-cache.svg)](https://pkg.go.dev/github.com/num30/go-cache) [![Go Reference](https://pkg.go.dev/badge/github.com/num30/go-cache.svg)](https://pkg.go.dev/github.com/num30/go-cache)
```
[![status-badge](https://ci.sg.caj.me/api/badges/caj/go-cache/status.svg)](https://ci.sg.caj.me/caj/go-cache)
go-cache is a port of great [go-cache](https://github.com/patrickmn/go-cache) library that was written by @patrickmn. The main defference is that it relies on generics instead of reflection. go-cache is a port of great [go-cache](https://github.com/patrickmn/go-cache) library that was written by @patrickmn. The main defference is that it relies on generics instead of reflection.
go-cache is a in-memory key:value store/cache similar to memcached that is go-cache is a in-memory key:value store/cache similar to memcached that is
@ -74,22 +70,22 @@ Spoiler alert! The difference is insignificant.
| <sub>Test </sub> | <sub> [Non generic](https://github.com/patrickmn/go-cache)</sub> | | <sub>This version</sub> | | | Test | [Non generic](https://github.com/patrickmn/go-cache)| | This version | |
|----------------------------------------------|-----------|-------------|-----------|---------------| |----------------------------------------------|-----------|-------------|-----------|---------------|
| <sub>BenchmarkCacheGetStringExpiring-8 </sub>| <sub>29884011</sub> | <sub>41.45 ns/op</sub> | <sub>28318041</sub> | <sub>43.31 ns/op</sub> | | BenchmarkCacheGetStringExpiring-8 | 29884011 | 41.45 ns/op | 28318041 | 43.31 ns/op |
| <sub>BenchmarkCacheGetStringNotExpiring-8 </sub>| <sub>91891774</sub> | <sub>14.20 ns/op</sub> | <sub>72259294</sub> | <sub>14.02 ns/op</sub> | | BenchmarkCacheGetStringNotExpiring-8 | 91891774 | 14.20 ns/op | 72259294 | 14.02 ns/op |
| <sub>BenchmarkCacheGetConcurrentExpiring-8 </sub>| <sub>26299849</sub> | <sub>42.58 ns/op</sub> | <sub>30129078</sub> | <sub>39.53 ns/op</sub> | | BenchmarkCacheGetConcurrentExpiring-8 | 26299849 | 42.58 ns/op | 30129078 | 39.53 ns/op |
| <sub>BenchmarkCacheGetConcurrentNotExpiring-8 </sub>| <sub>28991383</sub> | <sub>41.25 ns/op</sub> | <sub>30760544</sub> | <sub>38.09 ns/op</sub> | | BenchmarkCacheGetConcurrentNotExpiring-8 | 28991383 | 41.25 ns/op | 30760544 | 38.09 ns/op |
| <sub>BenchmarkCacheGetManyConcurrentExpiring-8 </sub>| <sub>55589712</sub> | <sub>44.90 ns/op</sub> | <sub>56991110</sub> | <sub>38.86 ns/op</sub> | | BenchmarkCacheGetManyConcurrentExpiring-8 | 55589712 | 44.90 ns/op | 56991110 | 38.86 ns/op |
| <sub>BenchmarkCacheGetManyConcurrentNotExpiring-8 </sub>| <sub>30105078</sub> | <sub>43.98 ns/op</sub> | <sub>46270045</sub> | <sub>41.54 ns/op</sub> | | BenchmarkCacheGetManyConcurrentNotExpiring-8 | 30105078 | 43.98 ns/op | 46270045 | 41.54 ns/op |
| <sub>BenchmarkCacheSetStringExpiring-8 </sub>| <sub>18392893</sub> | <sub>63.41 ns/op</sub> | <sub>17788724</sub> | <sub>61.42 ns/op</sub> | | BenchmarkCacheSetStringExpiring-8 | 18392893 | 63.41 ns/op | 17788724 | 61.42 ns/op |
| <sub>BenchmarkCacheSetStringNotExpiring-8 </sub>| <sub>46400654</sub> | <sub>28.45 ns/op</sub> | <sub>40226074</sub> | <sub>27.41 ns/op</sub> | | BenchmarkCacheSetStringNotExpiring-8 | 46400654 | 28.45 ns/op | 40226074 | 27.41 ns/op |
| <sub>BenchmarkCacheSetDelete-8 </sub>| <sub>18703620</sub> | <sub>60.75 ns/op</sub> | <sub>18270448</sub> | <sub>59.90 ns/op</sub> | | BenchmarkCacheSetDelete-8 | 18703620 | 60.75 ns/op | 18270448 | 59.90 ns/op |
| <sub>BenchmarkCacheSetDeleteSingleLock-8 </sub>| <sub>32633755</sub> | <sub>39.34 ns/op</sub> | <sub>32415156</sub> | <sub>36.96 ns/op</sub> | | BenchmarkCacheSetDeleteSingleLock-8 | 32633755 | 39.34 ns/op | 32415156 | 36.96 ns/op |
| <sub>BenchmarkCacheGetStructExpiring-8 </sub>| <sub>30487856</sub> | <sub>41.60 ns/op</sub> | <sub>26925226</sub> | <sub>40.55 ns/op</sub> | | BenchmarkCacheGetStructExpiring-8 | 30487856 | 41.60 ns/op | 26925226 | 40.55 ns/op |
| <sub>BenchmarkCacheGetStructNotExpiring-8 </sub>| <sub>91921044</sub> | <sub>13.94 ns/op</sub> | <sub>96379750</sub> | <sub>13.08 ns/op</sub> | | BenchmarkCacheGetStructNotExpiring-8 | 91921044 | 13.94 ns/op | 96379750 | 13.08 ns/op |
| <sub>BenchmarkCacheSetStructExpiring-8 </sub>| <sub>13977464</sub> | <sub>86.44 ns/op</sub> | <sub>13364509</sub> | <sub>87.69 ns/op</sub> | | BenchmarkCacheSetStructExpiring-8 | 13977464 | 86.44 ns/op | 13364509 | 87.69 ns/op |
| <sub>BenchmarkCacheSetStructNotExpiring-8 </sub>| <sub>22749384</sub> | <sub>54.14 ns/op</sub> | <sub>23207397</sub> | <sub>52.58 ns/op</sub> | | BenchmarkCacheSetStructNotExpiring-8 | 22749384 | 54.14 ns/op | 23207397 | 52.58 ns/op |
| <sub>BenchmarkCacheSetFatStructExpiring-8 </sub>| <sub>11718718</sub> | <sub>103.3 ns/op</sub> | <sub>12051895</sub> | <sub>102.3 ns/op</sub> | | BenchmarkCacheSetFatStructExpiring-8 | 11718718 | 103.3 ns/op | 12051895 | 102.3 ns/op |
| <sub>BenchmarkCacheGetFatStructNotExpiring-8 </sub>| <sub>88695709</sub> | <sub>13.92 ns/op</sub> | <sub>83220014</sub> | <sub>13.76 ns/op</sub> | | BenchmarkCacheGetFatStructNotExpiring-8 | 88695709 | 13.92 ns/op | 83220014 | 13.76 ns/op |

@ -33,23 +33,23 @@ const (
DefaultExpiration time.Duration = 0 DefaultExpiration time.Duration = 0
) )
type Cache[K comparable,T any] struct { type Cache[T any] struct {
*cache[K, T] *cache[T]
// If this is confusing, see the comment at the bottom of New() // If this is confusing, see the comment at the bottom of New()
} }
type cache[K comparable, T any] struct {
type cache[T any] struct {
defaultExpiration time.Duration defaultExpiration time.Duration
items map[K]Item[T] items map[string]Item[T]
mu sync.RWMutex mu sync.RWMutex
onEvicted func(K, T) onEvicted func(string, T)
janitor *janitor[K, T] janitor *janitor[T]
} }
// Add an item to the cache, replacing any existing item. If the duration is 0 // 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 // (DefaultExpiration), the cache's default expiration time is used. If it is -1
// (NoExpiration), the item never expires. // (NoExpiration), the item never expires.
func (c *cache[K, T]) Set(k K, x T, d time.Duration) { func (c *cache[T]) Set(k string, x T, d time.Duration) {
// "Inlining" of set // "Inlining" of set
var e int64 var e int64
if d == DefaultExpiration { if d == DefaultExpiration {
@ -68,7 +68,7 @@ func (c *cache[K, T]) Set(k K, x T, d time.Duration) {
c.mu.Unlock() c.mu.Unlock()
} }
func (c *cache[K, T]) set(k K, x T, d time.Duration) { func (c *cache[T]) set(k string, x T, d time.Duration) {
var e int64 var e int64
if d == DefaultExpiration { if d == DefaultExpiration {
d = c.defaultExpiration d = c.defaultExpiration
@ -84,18 +84,18 @@ func (c *cache[K, T]) set(k K, x T, d time.Duration) {
// Add an item to the cache, replacing any existing item, using the default // Add an item to the cache, replacing any existing item, using the default
// expiration. // expiration.
func (c *cache[K, T]) SetDefault(k K, x T) { func (c *cache[T]) SetDefault(k string, x T) {
c.Set(k, x, DefaultExpiration) c.Set(k, x, DefaultExpiration)
} }
// Add an item to the cache only if an item doesn't already exist for the given // 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. // key, or if the existing item has expired. Returns an error otherwise.
func (c *cache[K, T]) Add(k K, x T, d time.Duration) error { func (c *cache[T]) Add(k string, x T, d time.Duration) error {
c.mu.Lock() c.mu.Lock()
_, found := c.get(k) _, found := c.get(k)
if found { if found {
c.mu.Unlock() c.mu.Unlock()
return fmt.Errorf("Item %s already exists", "key") return fmt.Errorf("Item %s already exists", k)
} }
c.set(k, x, d) c.set(k, x, d)
c.mu.Unlock() c.mu.Unlock()
@ -104,12 +104,12 @@ func (c *cache[K, T]) Add(k K, x T, d time.Duration) error {
// Set a new value for the cache key only if it already exists, and the existing // Set a new value for the cache key only if it already exists, and the existing
// item hasn't expired. Returns an error otherwise. // item hasn't expired. Returns an error otherwise.
func (c *cache[K, T]) Replace(k K, x T, d time.Duration) error { func (c *cache[T]) Replace(k string, x T, d time.Duration) error {
c.mu.Lock() c.mu.Lock()
_, found := c.get(k) _, found := c.get(k)
if !found { if !found {
c.mu.Unlock() c.mu.Unlock()
return fmt.Errorf("Item %s doesn't exist", "key") return fmt.Errorf("Item %s doesn't exist", k)
} }
c.set(k, x, d) c.set(k, x, d)
c.mu.Unlock() c.mu.Unlock()
@ -118,7 +118,7 @@ func (c *cache[K, T]) Replace(k K, x T, d time.Duration) error {
// 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 nil, and a bool indicating
// whether the key was found. // whether the key was found.
func (c *cache[K, T]) Get(k K) (T, bool) { func (c *cache[T]) Get(k string) (T, bool) {
c.mu.RLock() c.mu.RLock()
// "Inlining" of get and Expired // "Inlining" of get and Expired
item, found := c.items[k] item, found := c.items[k]
@ -140,7 +140,7 @@ func (c *cache[K, T]) Get(k K) (T, bool) {
// It returns the item or nil, the expiration time if one is set (if the item // 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 // never expires a zero value for time.Time is returned), and a bool indicating
// whether the key was found. // whether the key was found.
func (c *cache[K, T]) GetWithExpiration(k K) (T, time.Time, bool) { func (c *cache[T]) GetWithExpiration(k string) (T, time.Time, bool) {
c.mu.RLock() c.mu.RLock()
// "Inlining" of get and Expired // "Inlining" of get and Expired
item, found := c.items[k] item, found := c.items[k]
@ -166,7 +166,7 @@ func (c *cache[K, T]) GetWithExpiration(k K) (T, time.Time, bool) {
return item.Object, time.Time{}, true return item.Object, time.Time{}, true
} }
func (c *cache[K, T]) get(k K) (T, bool) { func (c *cache[T]) get(k string) (T, bool) {
item, found := c.items[k] item, found := c.items[k]
if !found { if !found {
return *new(T), false return *new(T), false
@ -181,7 +181,7 @@ func (c *cache[K, T]) get(k K) (T, bool) {
} }
// Delete an item from the cache. Does nothing if the key is not in the cache. // Delete an item from the cache. Does nothing if the key is not in the cache.
func (c *cache[K, T]) Delete(k K) { func (c *cache[T]) Delete(k string) {
c.mu.Lock() c.mu.Lock()
v, evicted := c.delete(k) v, evicted := c.delete(k)
c.mu.Unlock() c.mu.Unlock()
@ -190,7 +190,7 @@ func (c *cache[K, T]) Delete(k K) {
} }
} }
func (c *cache[K, T]) delete(k K) (T, bool) { func (c *cache[T]) delete(k string) (T, bool) {
if c.onEvicted != nil { if c.onEvicted != nil {
if v, found := c.items[k]; found { if v, found := c.items[k]; found {
delete(c.items, k) delete(c.items, k)
@ -201,14 +201,14 @@ func (c *cache[K, T]) delete(k K) (T, bool) {
return *new(T), false return *new(T), false
} }
type keyAndValue[K comparable, T any] struct { type keyAndValue[T any] struct {
key K key string
value T value T
} }
// Delete all expired items from the cache. // Delete all expired items from the cache.
func (c *cache[K, T]) DeleteExpired() { func (c *cache[T]) DeleteExpired() {
var evictedItems []keyAndValue[K, T] var evictedItems []keyAndValue[T]
now := time.Now().UnixNano() now := time.Now().UnixNano()
c.mu.Lock() c.mu.Lock()
for k, v := range c.items { for k, v := range c.items {
@ -216,7 +216,7 @@ func (c *cache[K, T]) DeleteExpired() {
if v.Expiration > 0 && now > v.Expiration { if v.Expiration > 0 && now > v.Expiration {
ov, evicted := c.delete(k) ov, evicted := c.delete(k)
if evicted { if evicted {
evictedItems = append(evictedItems, keyAndValue[K, T]{k, ov}) evictedItems = append(evictedItems, keyAndValue[T]{k, ov})
} }
} }
} }
@ -229,7 +229,7 @@ func (c *cache[K, T]) DeleteExpired() {
// Sets an (optional) function that is called with the key and value when an // 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 // item is evicted from the cache. (Including when it is deleted manually, but
// not when it is overwritten.) Set to nil to disable. // not when it is overwritten.) Set to nil to disable.
func (c *cache[K, T]) OnEvicted(f func(K, T)) { func (c *cache[T]) OnEvicted(f func(string, T)) {
c.mu.Lock() c.mu.Lock()
c.onEvicted = f c.onEvicted = f
c.mu.Unlock() c.mu.Unlock()
@ -239,7 +239,7 @@ func (c *cache[K, T]) OnEvicted(f func(K, T)) {
// //
// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
// documentation for NewFrom().) // documentation for NewFrom().)
func (c *cache[K, T]) Save(w io.Writer) (err error) { func (c *cache[T]) Save(w io.Writer) (err error) {
enc := gob.NewEncoder(w) enc := gob.NewEncoder(w)
c.mu.RLock() c.mu.RLock()
defer c.mu.RUnlock() defer c.mu.RUnlock()
@ -264,7 +264,7 @@ func (c *cache[K, T]) Save(w io.Writer) (err error) {
// //
// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
// documentation for NewFrom().) // documentation for NewFrom().)
func (c *cache[K, T]) SaveFile(fname string) error { func (c *cache[T]) SaveFile(fname string) error {
fp, err := os.Create(fname) fp, err := os.Create(fname)
if err != nil { if err != nil {
return err return err
@ -282,9 +282,9 @@ func (c *cache[K, T]) SaveFile(fname string) error {
// //
// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
// documentation for NewFrom().) // documentation for NewFrom().)
func (c *cache[K, T]) Load(r io.Reader) error { func (c *cache[T]) Load(r io.Reader) error {
dec := gob.NewDecoder(r) dec := gob.NewDecoder(r)
items := map[K]Item[T]{} items := map[string]Item[T]{}
err := dec.Decode(&items) err := dec.Decode(&items)
if err == nil { if err == nil {
c.mu.Lock() c.mu.Lock()
@ -304,7 +304,7 @@ func (c *cache[K, T]) Load(r io.Reader) error {
// //
// NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the // NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the
// documentation for NewFrom().) // documentation for NewFrom().)
func (c *cache[K, T]) LoadFile(fname string) error { func (c *cache[T]) LoadFile(fname string) error {
fp, err := os.Open(fname) fp, err := os.Open(fname)
if err != nil { if err != nil {
return err return err
@ -318,10 +318,10 @@ func (c *cache[K, T]) LoadFile(fname string) error {
} }
// Copies all unexpired items in the cache into a new map and returns it. // Copies all unexpired items in the cache into a new map and returns it.
func (c *cache[K, T]) Items() map[K]Item[T] { func (c *cache[T]) Items() map[string]Item[T] {
c.mu.RLock() c.mu.RLock()
defer c.mu.RUnlock() defer c.mu.RUnlock()
m := make(map[K]Item[T], len(c.items)) m := make(map[string]Item[T], len(c.items))
now := time.Now().UnixNano() now := time.Now().UnixNano()
for k, v := range c.items { for k, v := range c.items {
// "Inlining" of Expired // "Inlining" of Expired
@ -337,7 +337,7 @@ func (c *cache[K, T]) Items() map[K]Item[T] {
// Returns the number of items in the cache. This may include items that have // Returns the number of items in the cache. This may include items that have
// expired, but have not yet been cleaned up. // expired, but have not yet been cleaned up.
func (c *cache[K, T]) ItemCount() int { func (c *cache[T]) ItemCount() int {
c.mu.RLock() c.mu.RLock()
n := len(c.items) n := len(c.items)
c.mu.RUnlock() c.mu.RUnlock()
@ -345,18 +345,18 @@ func (c *cache[K, T]) ItemCount() int {
} }
// Delete all items from the cache. // Delete all items from the cache.
func (c *cache[K, T]) Flush() { func (c *cache[T]) Flush() {
c.mu.Lock() c.mu.Lock()
c.items = map[K]Item[T]{} c.items = map[string]Item[T]{}
c.mu.Unlock() c.mu.Unlock()
} }
type janitor[K comparable, T any] struct { type janitor[T any] struct {
Interval time.Duration Interval time.Duration
stop chan bool stop chan bool
} }
func (j *janitor[K, T]) Run(c *cache[K, T]) { func (j *janitor[T]) Run(c *cache[T]) {
ticker := time.NewTicker(j.Interval) ticker := time.NewTicker(j.Interval)
for { for {
select { select {
@ -369,12 +369,12 @@ func (j *janitor[K, T]) Run(c *cache[K, T]) {
} }
} }
func stopJanitor[K comparable, T any](c *Cache[K, T]) { func stopJanitor[T any](c *Cache[T]) {
c.janitor.stop <- true c.janitor.stop <- true
} }
func runJanitor[K comparable, T any](c *cache[K, T], ci time.Duration) { func runJanitor[T any](c *cache[T], ci time.Duration) {
j := &janitor[K, T]{ j := &janitor[T]{
Interval: ci, Interval: ci,
stop: make(chan bool), stop: make(chan bool),
} }
@ -382,28 +382,28 @@ func runJanitor[K comparable, T any](c *cache[K, T], ci time.Duration) {
go j.Run(c) go j.Run(c)
} }
func newCache[K comparable, T any](de time.Duration, m map[K]Item[T]) *cache[K, T] { func newCache[T any](de time.Duration, m map[string]Item[T]) *cache[T] {
if de == 0 { if de == 0 {
de = -1 de = -1
} }
c := &cache[K, T]{ c := &cache[T]{
defaultExpiration: de, defaultExpiration: de,
items: m, items: m,
} }
return c return c
} }
func newCacheWithJanitor[K comparable, T any](de time.Duration, ci time.Duration, m map[K]Item[T]) *Cache[K, T] { func newCacheWithJanitor[T any](de time.Duration, ci time.Duration, m map[string]Item[T]) *Cache[T] {
c := newCache[K, T](de, m) c := newCache[T](de, m)
// This trick ensures that the janitor goroutine (which--granted it // This trick ensures that the janitor goroutine (which--granted it
// was enabled--is running DeleteExpired on c forever) does not keep // was enabled--is running DeleteExpired on c forever) does not keep
// the returned C object from being garbage collected. When it is // the returned C object from being garbage collected. When it is
// garbage collected, the finalizer stops the janitor goroutine, after // garbage collected, the finalizer stops the janitor goroutine, after
// which c can be collected. // which c can be collected.
C := &Cache[K, T]{c} C := &Cache[T]{c}
if ci > 0 { if ci > 0 {
runJanitor(c, ci) runJanitor(c, ci)
runtime.SetFinalizer(C, stopJanitor[K, T]) runtime.SetFinalizer(C, stopJanitor[T])
} }
return C return C
} }
@ -413,9 +413,9 @@ func newCacheWithJanitor[K comparable, T any](de time.Duration, ci time.Duration
// the items in the cache never expire (by default), and must be deleted // 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 // manually. If the cleanup interval is less than one, expired items are not
// deleted from the cache before calling c.DeleteExpired(). // deleted from the cache before calling c.DeleteExpired().
func New[K comparable, T any](defaultExpiration, cleanupInterval time.Duration) *Cache[K, T] { func New[T any](defaultExpiration, cleanupInterval time.Duration) *Cache[T] {
items := make(map[K]Item[T]) items := make(map[string]Item[T])
return newCacheWithJanitor[K, T](defaultExpiration, cleanupInterval, items) return newCacheWithJanitor[T](defaultExpiration, cleanupInterval, items)
} }
// Return a new cache with a given default expiration duration and cleanup // Return a new cache with a given default expiration duration and cleanup
@ -439,6 +439,6 @@ func New[K comparable, T any](defaultExpiration, cleanupInterval time.Duration)
// gob.Register() the individual types stored in the cache before encoding a // gob.Register() the individual types stored in the cache before encoding a
// map retrieved with c.Items(), and to register those same types before // map retrieved with c.Items(), and to register those same types before
// decoding a blob containing an items map. // decoding a blob containing an items map.
func NewFrom[K comparable, T any](defaultExpiration, cleanupInterval time.Duration, items map[K]Item[T]) *Cache[K, T] { func NewFrom[T any](defaultExpiration, cleanupInterval time.Duration, items map[string]Item[T]) *Cache[T] {
return newCacheWithJanitor(defaultExpiration, cleanupInterval, items) return newCacheWithJanitor(defaultExpiration, cleanupInterval, items)
} }

@ -23,7 +23,7 @@ func NewTestStruct(num int) TestStruct {
} }
func TestCache(t *testing.T) { func TestCache(t *testing.T) {
tc := New[string, TestStruct](DefaultExpiration, 0) tc := New[TestStruct](DefaultExpiration, 0)
a, found := tc.Get("a") a, found := tc.Get("a")
if found { if found {
@ -57,7 +57,7 @@ func TestCache(t *testing.T) {
func TestCacheTimes(t *testing.T) { func TestCacheTimes(t *testing.T) {
var found bool var found bool
tc := New[string, TestStruct](50*time.Millisecond, 1*time.Millisecond) tc := New[TestStruct](50*time.Millisecond, 1*time.Millisecond)
tc.Set("a", NewTestStruct(1), DefaultExpiration) tc.Set("a", NewTestStruct(1), DefaultExpiration)
tc.Set("b", NewTestStruct(2), NoExpiration) tc.Set("b", NewTestStruct(2), NoExpiration)
tc.Set("c", NewTestStruct(3), 20*time.Millisecond) tc.Set("c", NewTestStruct(3), 20*time.Millisecond)
@ -122,7 +122,7 @@ func TestNewFrom(t *testing.T) {
} }
func TestStorePointerToStruct(t *testing.T) { func TestStorePointerToStruct(t *testing.T) {
tc := New[string, *TestStruct](DefaultExpiration, 0) tc := New[*TestStruct](DefaultExpiration, 0)
tc.Set("foo", &TestStruct{Num: 1}, DefaultExpiration) tc.Set("foo", &TestStruct{Num: 1}, DefaultExpiration)
x, found := tc.Get("foo") x, found := tc.Get("foo")
if !found { if !found {
@ -142,7 +142,7 @@ func TestStorePointerToStruct(t *testing.T) {
} }
func TestAdd(t *testing.T) { func TestAdd(t *testing.T) {
tc := New[string, string](DefaultExpiration, 0) tc := New[string](DefaultExpiration, 0)
err := tc.Add("foo", "bar", DefaultExpiration) err := tc.Add("foo", "bar", DefaultExpiration)
if err != nil { if err != nil {
t.Error("Couldn't add foo even though it shouldn't exist") t.Error("Couldn't add foo even though it shouldn't exist")
@ -154,7 +154,7 @@ func TestAdd(t *testing.T) {
} }
func TestReplace(t *testing.T) { func TestReplace(t *testing.T) {
tc := New[string, string](DefaultExpiration, 0) tc := New[string](DefaultExpiration, 0)
err := tc.Replace("foo", "bar", DefaultExpiration) err := tc.Replace("foo", "bar", DefaultExpiration)
if err == nil { if err == nil {
t.Error("Replaced foo when it shouldn't exist") t.Error("Replaced foo when it shouldn't exist")
@ -167,7 +167,7 @@ func TestReplace(t *testing.T) {
} }
func TestDelete(t *testing.T) { func TestDelete(t *testing.T) {
tc := New[string, string](DefaultExpiration, 0) tc := New[string](DefaultExpiration, 0)
tc.Set("foo", "bar", DefaultExpiration) tc.Set("foo", "bar", DefaultExpiration)
tc.Delete("foo") tc.Delete("foo")
_, found := tc.Get("foo") _, found := tc.Get("foo")
@ -177,7 +177,7 @@ func TestDelete(t *testing.T) {
} }
func TestItemCount(t *testing.T) { func TestItemCount(t *testing.T) {
tc := New[string, string](DefaultExpiration, 0) tc := New[string](DefaultExpiration, 0)
tc.Set("foo", "1", DefaultExpiration) tc.Set("foo", "1", DefaultExpiration)
tc.Set("bar", "2", DefaultExpiration) tc.Set("bar", "2", DefaultExpiration)
tc.Set("baz", "3", DefaultExpiration) tc.Set("baz", "3", DefaultExpiration)
@ -187,7 +187,7 @@ func TestItemCount(t *testing.T) {
} }
func TestFlush(t *testing.T) { func TestFlush(t *testing.T) {
tc := New[string, string](DefaultExpiration, 0) tc := New[string](DefaultExpiration, 0)
tc.Set("foo", "bar", DefaultExpiration) tc.Set("foo", "bar", DefaultExpiration)
tc.Set("baz", "yes", DefaultExpiration) tc.Set("baz", "yes", DefaultExpiration)
tc.Flush() tc.Flush()
@ -203,7 +203,7 @@ func TestFlush(t *testing.T) {
} }
func TestOnEvicted(t *testing.T) { func TestOnEvicted(t *testing.T) {
tc := New[string, int](DefaultExpiration, time.Millisecond) tc := New[int](DefaultExpiration, 0)
tc.Set("foo", 3, DefaultExpiration) tc.Set("foo", 3, DefaultExpiration)
if tc.onEvicted != nil { if tc.onEvicted != nil {
t.Fatal("tc.onEvicted is not nil") t.Fatal("tc.onEvicted is not nil")
@ -226,7 +226,7 @@ func TestOnEvicted(t *testing.T) {
} }
func TestCacheSerialization(t *testing.T) { func TestCacheSerialization(t *testing.T) {
tc := New[string, TestStruct](DefaultExpiration, 0) tc := New[TestStruct](DefaultExpiration, 0)
testFillAndSerialize(t, tc) testFillAndSerialize(t, tc)
// Check if gob.Register behaves properly even after multiple gob.Register // Check if gob.Register behaves properly even after multiple gob.Register
@ -234,7 +234,7 @@ func TestCacheSerialization(t *testing.T) {
testFillAndSerialize(t, tc) testFillAndSerialize(t, tc)
} }
func testFillAndSerialize(t *testing.T, tc *Cache[string, TestStruct]) { func testFillAndSerialize(t *testing.T, tc *Cache[TestStruct]) {
tc.Set("*struct", TestStruct{Num: 1}, DefaultExpiration) tc.Set("*struct", TestStruct{Num: 1}, DefaultExpiration)
@ -260,7 +260,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache[string, TestStruct]) {
t.Fatal("Couldn't save cache to fp:", err) t.Fatal("Couldn't save cache to fp:", err)
} }
oc := New[string, TestStruct](DefaultExpiration, 0) oc := New[TestStruct](DefaultExpiration, 0)
err = oc.Load(fp) err = oc.Load(fp)
if err != nil { if err != nil {
t.Fatal("Couldn't load cache from fp:", err) t.Fatal("Couldn't load cache from fp:", err)
@ -297,7 +297,7 @@ func testFillAndSerialize(t *testing.T, tc *Cache[string, TestStruct]) {
} }
func TestFileSerialization(t *testing.T) { func TestFileSerialization(t *testing.T) {
tc := New[string, string](DefaultExpiration, 0) tc := New[string](DefaultExpiration, 0)
tc.Add("a", "a", DefaultExpiration) tc.Add("a", "a", DefaultExpiration)
tc.Add("b", "b", DefaultExpiration) tc.Add("b", "b", DefaultExpiration)
f, err := ioutil.TempFile("", "go-cache-cache.dat") f, err := ioutil.TempFile("", "go-cache-cache.dat")
@ -308,7 +308,7 @@ func TestFileSerialization(t *testing.T) {
f.Close() f.Close()
tc.SaveFile(fname) tc.SaveFile(fname)
oc := New[string, string](DefaultExpiration, 0) oc := New[string](DefaultExpiration, 0)
oc.Add("a", "aa", 0) // this should not be overwritten oc.Add("a", "aa", 0) // this should not be overwritten
err = oc.LoadFile(fname) err = oc.LoadFile(fname)
if err != nil { if err != nil {
@ -336,7 +336,7 @@ func TestFileSerialization(t *testing.T) {
} }
func TestSerializeUnserializable(t *testing.T) { func TestSerializeUnserializable(t *testing.T) {
tc := New[string, chan bool](DefaultExpiration, 0) tc := New[chan bool](DefaultExpiration, 0)
ch := make(chan bool, 1) ch := make(chan bool, 1)
ch <- true ch <- true
tc.Set("chan", ch, DefaultExpiration) tc.Set("chan", ch, DefaultExpiration)
@ -357,7 +357,7 @@ func BenchmarkCacheGetStringNotExpiring(b *testing.B) {
func benchmarkCacheGetString(b *testing.B, exp time.Duration) { func benchmarkCacheGetString(b *testing.B, exp time.Duration) {
b.StopTimer() b.StopTimer()
tc := New[string, string](exp, 0) tc := New[string](exp, 0)
tc.Set("foo", "bar", DefaultExpiration) tc.Set("foo", "bar", DefaultExpiration)
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -418,7 +418,7 @@ func BenchmarkCacheGetConcurrentNotExpiring(b *testing.B) {
func benchmarkCacheGetConcurrent(b *testing.B, exp time.Duration) { func benchmarkCacheGetConcurrent(b *testing.B, exp time.Duration) {
b.StopTimer() b.StopTimer()
tc := New[string, string](exp, 0) tc := New[string](exp, 0)
tc.Set("foo", "bar", DefaultExpiration) tc.Set("foo", "bar", DefaultExpiration)
wg := new(sync.WaitGroup) wg := new(sync.WaitGroup)
workers := runtime.NumCPU() workers := runtime.NumCPU()
@ -474,7 +474,7 @@ func benchmarkCacheGetManyConcurrent(b *testing.B, exp time.Duration) {
// in sharded_test.go. // in sharded_test.go.
b.StopTimer() b.StopTimer()
n := 10000 n := 10000
tc := New[string, string](exp, 0) tc := New[string](exp, 0)
keys := make([]string, n) keys := make([]string, n)
for i := 0; i < n; i++ { for i := 0; i < n; i++ {
k := "foo" + strconv.Itoa(i) k := "foo" + strconv.Itoa(i)
@ -506,7 +506,7 @@ func BenchmarkCacheSetStringNotExpiring(b *testing.B) {
func benchmarkCacheSetString(b *testing.B, exp time.Duration) { func benchmarkCacheSetString(b *testing.B, exp time.Duration) {
b.StopTimer() b.StopTimer()
tc := New[string, string](exp, 0) tc := New[string](exp, 0)
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
tc.Set("foo", "bar", DefaultExpiration) tc.Set("foo", "bar", DefaultExpiration)
@ -527,7 +527,7 @@ func BenchmarkRWMutexMapSet(b *testing.B) {
func BenchmarkCacheSetDelete(b *testing.B) { func BenchmarkCacheSetDelete(b *testing.B) {
b.StopTimer() b.StopTimer()
tc := New[string, string](DefaultExpiration, 0) tc := New[string](DefaultExpiration, 0)
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
tc.Set("foo", "bar", DefaultExpiration) tc.Set("foo", "bar", DefaultExpiration)
@ -552,7 +552,7 @@ func BenchmarkRWMutexMapSetDelete(b *testing.B) {
func BenchmarkCacheSetDeleteSingleLock(b *testing.B) { func BenchmarkCacheSetDeleteSingleLock(b *testing.B) {
b.StopTimer() b.StopTimer()
tc := New[string, string](DefaultExpiration, 0) tc := New[string](DefaultExpiration, 0)
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
tc.mu.Lock() tc.mu.Lock()
@ -577,7 +577,7 @@ func BenchmarkRWMutexMapSetDeleteSingleLock(b *testing.B) {
func BenchmarkDeleteExpiredLoop(b *testing.B) { func BenchmarkDeleteExpiredLoop(b *testing.B) {
b.StopTimer() b.StopTimer()
tc := New[string, string](5*time.Minute, 0) tc := New[string](5*time.Minute, 0)
tc.mu.Lock() tc.mu.Lock()
for i := 0; i < 100000; i++ { for i := 0; i < 100000; i++ {
tc.set(strconv.Itoa(i), "bar", DefaultExpiration) tc.set(strconv.Itoa(i), "bar", DefaultExpiration)
@ -590,7 +590,7 @@ func BenchmarkDeleteExpiredLoop(b *testing.B) {
} }
func TestGetWithExpiration(t *testing.T) { func TestGetWithExpiration(t *testing.T) {
tc := New[string, int](DefaultExpiration, 0) tc := New[int](DefaultExpiration, 0)
a, expiration, found := tc.GetWithExpiration("a") a, expiration, found := tc.GetWithExpiration("a")
if found || !expiration.IsZero() { if found || !expiration.IsZero() {
@ -652,7 +652,7 @@ func BenchmarkCacheGetStructNotExpiring(b *testing.B) {
func benchmarkCacheGetStruct(b *testing.B, exp time.Duration) { func benchmarkCacheGetStruct(b *testing.B, exp time.Duration) {
b.StopTimer() b.StopTimer()
tc := New[string, *TestStruct](exp, 0) tc := New[*TestStruct](exp, 0)
tc.Set("foo", &TestStruct{Num: 1}, DefaultExpiration) tc.Set("foo", &TestStruct{Num: 1}, DefaultExpiration)
b.StartTimer() b.StartTimer()
@ -673,7 +673,7 @@ func BenchmarkCacheSetStructNotExpiring(b *testing.B) {
func benchmarkCacheSetStruct(b *testing.B, exp time.Duration) { func benchmarkCacheSetStruct(b *testing.B, exp time.Duration) {
b.StopTimer() b.StopTimer()
tc := New[string, *TestStruct](exp, 0) tc := New[*TestStruct](exp, 0)
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
tc.Set("foo", &TestStruct{Num: 1}, DefaultExpiration) tc.Set("foo", &TestStruct{Num: 1}, DefaultExpiration)
@ -682,7 +682,7 @@ func benchmarkCacheSetStruct(b *testing.B, exp time.Duration) {
func BenchmarkCacheSetFatStructExpiring(b *testing.B) { func BenchmarkCacheSetFatStructExpiring(b *testing.B) {
b.StopTimer() b.StopTimer()
tc := New[string, *TestStruct](NoExpiration, 0) tc := New[*TestStruct](NoExpiration, 0)
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
tc.Set("foo", &TestStruct{Num: 1, Children: []*TestStruct{ tc.Set("foo", &TestStruct{Num: 1, Children: []*TestStruct{
@ -692,7 +692,7 @@ func BenchmarkCacheSetFatStructExpiring(b *testing.B) {
func BenchmarkCacheGetFatStructNotExpiring(b *testing.B) { func BenchmarkCacheGetFatStructNotExpiring(b *testing.B) {
b.StopTimer() b.StopTimer()
tc := New[string, *TestStruct](NoExpiration, 0) tc := New[*TestStruct](NoExpiration, 0)
tc.Set("foo", &TestStruct{Num: 1, Children: []*TestStruct{ tc.Set("foo", &TestStruct{Num: 1, Children: []*TestStruct{
&TestStruct{Num: 2, Children: []*TestStruct{}}}}, DefaultExpiration) &TestStruct{Num: 2, Children: []*TestStruct{}}}}, DefaultExpiration)

@ -4,14 +4,13 @@ import (
"fmt" "fmt"
"time" "time"
"git.sg.caj.me/caj/go-cache" "github.com/num30/go-cache"
) )
func main() { func main() {
// Create a cache with a default expiration time of 5 minutes, and which // Create a cache with a default expiration time of 5 minutes, and which
// purges expired items every 10 minutes // purges expired items every 10 minutes
c := cache.New[string, string](5*time.Minute, 10*time.Minute) c := cache.New[string](5*time.Minute, 10*time.Minute)
// Set the value of the key "foo" to "bar", with the default expiration time // Set the value of the key "foo" to "bar", with the default expiration time
c.Set("foo", "bar", cache.DefaultExpiration) c.Set("foo", "bar", cache.DefaultExpiration)
@ -28,7 +27,7 @@ func main() {
} }
// Want performance? Store pointers! // Want performance? Store pointers!
structCache := cache.New[string, *time.Time](5*time.Minute, 10*time.Minute) structCache := cache.New[*time.Time](5*time.Minute, 10*time.Minute)
structCache.Set("foo", &time.Time{}, cache.DefaultExpiration) structCache.Set("foo", &time.Time{}, cache.DefaultExpiration)
if x, found := structCache.Get("foo"); found { if x, found := structCache.Get("foo"); found {
fmt.Printf("Cached time %+v\n", x) fmt.Printf("Cached time %+v\n", x)

@ -1,10 +1,10 @@
module git.sg.caj.me/caj/go-cache module github.com/num30/go-cache
go 1.18 go 1.18
require ( require (
github.com/golangci/golangci-lint v1.45.2 github.com/golangci/golangci-lint v1.45.2
honnef.co/go/tools v0.3.1 honnef.co/go/tools v0.3.1 // indirect
) )
require ( require (

Loading…
Cancel
Save