Skip to content

Commit 1b18fcc

Browse files
committed
implement ristretto
1 parent 00d7a47 commit 1b18fcc

File tree

3 files changed

+80
-1
lines changed

3 files changed

+80
-1
lines changed

README.md

+24-1
Original file line numberDiff line numberDiff line change
@@ -124,9 +124,32 @@ var strlen = memoize.NewWithCache(
124124
)
125125
```
126126

127+
### [dgraph-io/ristretto](* https://github.com/dgraph-io/ristretto/v2)
128+
129+
```go
130+
import (
131+
"github.com/dgraph-io/ristretto/v2"
132+
"github.com/emad-elsaid/memoize"
133+
"github.com/emad-elsaid/memoize/cache/adapters/dgraphio"
134+
)
135+
136+
// example from ristretto README.md
137+
var c, _ = ristretto.NewCache(&ristretto.Config[string, int]{
138+
NumCounters: 1e7, // number of keys to track frequency of (10M).
139+
MaxCost: 1 << 30, // maximum cost of cache (1GB).
140+
BufferItems: 64, // number of keys per Get buffer.
141+
})
142+
143+
var strlen = memoize.NewWithCache(
144+
dgraphio.Ristretto(c),
145+
func(s string) int {
146+
return len(s)
147+
},
148+
)
149+
```
150+
127151
### To be implemented
128152

129-
* https://github.com/dgraph-io/ristretto
130153
* https://github.com/bradfitz/gomemcache
131154
* https://github.com/redis/go-redis
132155
* https://github.com/redis/rueidis

cache/adapters/dgraphio/ristretto.go

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package dgraphio
2+
3+
import "github.com/emad-elsaid/memoize/cache"
4+
5+
type RistrettoCache[K comparable, V any] interface {
6+
Get(K) (V, bool)
7+
Set(K, V, int64) bool
8+
}
9+
10+
func Ristretto[K comparable, V any](c RistrettoCache[K, V]) cache.Cacher[K, V] {
11+
return &ristretto[K, V]{c}
12+
}
13+
14+
type ristretto[K comparable, V any] struct {
15+
RistrettoCache[K, V]
16+
}
17+
18+
func (h *ristretto[K, V]) Load(key K) (value V, loaded bool) {
19+
return h.RistrettoCache.Get(key)
20+
}
21+
22+
func (h *ristretto[K, V]) Store(key K, value V) {
23+
h.RistrettoCache.Set(key, value, 0)
24+
}
+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package dgraphio
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) Set(k string, v int, _ int64) bool {
15+
m[k] = v
16+
return true
17+
}
18+
19+
func TestRistretto(t *testing.T) {
20+
m := Mock{}
21+
cacher := Ristretto(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+
}

0 commit comments

Comments
 (0)