File tree 2 files changed +68
-0
lines changed
2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Package hashicorp includes LRU adapter for https://github.com/hashicorp/golang-lru/v2 package
2
+ package hashicorp
3
+
4
+ import (
5
+ "github.com/emad-elsaid/memoize/cache"
6
+ )
7
+
8
+ // Hashicorp LRU cache interface (the part we need)
9
+ type HashicorpLRU [K comparable , V any ] interface {
10
+ Get (K ) (V , bool )
11
+ Add (K , V ) bool
12
+ }
13
+
14
+ // LRU creates a new cacher from the hashicorp cache
15
+ // For example:
16
+ //
17
+ // lru, _ := lru.New[string, int](1000)
18
+ // memoize.NewWithCache(
19
+ // hashicorp.LRU(lru),
20
+ // func(s string) int { return len(s) },
21
+ // )
22
+ func LRU [K comparable , V any ](c HashicorpLRU [K , V ]) cache.Cacher [K , V ] {
23
+ return & lru [K , V ]{c }
24
+ }
25
+
26
+ type lru [K comparable , V any ] struct {
27
+ HashicorpLRU [K , V ]
28
+ }
29
+
30
+ func (h * lru [K , V ]) Load (key K ) (value V , loaded bool ) {
31
+ return h .HashicorpLRU .Get (key )
32
+ }
33
+
34
+ func (h * lru [K , V ]) Store (key K , value V ) {
35
+ h .HashicorpLRU .Add (key , value )
36
+ }
Original file line number Diff line number Diff line change
1
+ package hashicorp
2
+
3
+ import (
4
+ "testing"
5
+ )
6
+
7
+ type Mock map [string ]int
8
+
9
+ func (m Mock ) Get (k string ) (int , bool ) {
10
+ v , ok := m [k ]
11
+ return v , ok
12
+ }
13
+
14
+ func (m Mock ) Add (k string , v int ) bool {
15
+ m [k ] = v
16
+ return true
17
+ }
18
+
19
+ func TestLRU (t * testing.T ) {
20
+ m := Mock {}
21
+ cacher := LRU (m )
22
+ cacher .Store ("k1" , 1 )
23
+
24
+ v , ok := cacher .Load ("k1" )
25
+ if v != 1 {
26
+ t .Error ("Expected" , 1 , "got" , v )
27
+ }
28
+
29
+ if ! ok {
30
+ t .Error ("Expected" , true , "got" , ok )
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments