Skip to content

Commit 47cfe0f

Browse files
committed
added option for using clock
1 parent 5b89c9f commit 47cfe0f

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ go-generics-cache is an in-memory key:value store/cache that is suitable for app
2424
- **Most recently used (MRU)**
2525
- In contrast to Least Recently Used (LRU), MRU discards the most recently used items first.
2626
- See [examples](https://github.com/Code-Hex/go-generics-cache/blob/main/mru/example_test.go)
27+
- **Clock**
28+
- Clock is a more efficient version of FIFO than Second-chance cache algorithm.
29+
- See [examples](https://github.com/Code-Hex/go-generics-cache/blob/main/clock/example_test.go)
2730

2831
## Requirements
2932

cache.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"sync"
55
"time"
66

7+
"github.com/Code-Hex/go-generics-cache/clock"
78
"github.com/Code-Hex/go-generics-cache/fifo"
89
"github.com/Code-Hex/go-generics-cache/lfu"
910
"github.com/Code-Hex/go-generics-cache/lru"
@@ -25,6 +26,7 @@ var (
2526
_ Interface[any, any] = (*lfu.Cache[any, any])(nil)
2627
_ Interface[any, any] = (*fifo.Cache[any, any])(nil)
2728
_ Interface[any, any] = (*mru.Cache[any, any])(nil)
29+
_ Interface[any, any] = (*clock.Cache[any, any])(nil)
2830
)
2931

3032
// Item is an item
@@ -113,6 +115,13 @@ func AsMRU[K comparable, V any](opts ...mru.Option) Option[K, V] {
113115
}
114116
}
115117

118+
// AsClock is an option to make a new Cache as clock algorithm.
119+
func AsClock[K comparable, V any](opts ...clock.Option) Option[K, V] {
120+
return func(o *options[K, V]) {
121+
o.cache = clock.NewCache[K, *Item[K, V]](opts...)
122+
}
123+
}
124+
116125
// New creates a new thread safe Cache.
117126
//
118127
// There are several Cache replacement policies available with you specified any options.

example_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,19 @@ func ExampleCache() {
2020
// 0 false
2121
}
2222

23+
func ExampleCacheAsClock() {
24+
// use clock cache algorithm.
25+
c := cache.New(cache.AsClock[string, int]())
26+
c.Set("a", 1)
27+
gota, aok := c.Get("a")
28+
gotb, bok := c.Get("b")
29+
fmt.Println(gota, aok)
30+
fmt.Println(gotb, bok)
31+
// Output:
32+
// 1 true
33+
// 0 false
34+
}
35+
2336
func ExampleCacheWithExpiration() {
2437
c := cache.New(cache.AsFIFO[string, int]())
2538
exp := 250 * time.Millisecond

0 commit comments

Comments
 (0)