-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathexample_test.go
61 lines (46 loc) · 1.44 KB
/
example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package lru_test
import (
"context"
"time"
"unsafe"
"github.com/phuslu/lru"
)
func ExampleWithHasher() {
hasher := func(key unsafe.Pointer, seed uintptr) (hash uintptr) {
hash = 5381
for _, c := range []byte(*(*string)(key)) {
hash = hash*33 + uintptr(c)
}
return
}
cache := lru.NewTTLCache[string, int](4096, lru.WithHasher[string, int](hasher))
cache.Set("foobar", 42, 3*time.Second)
println(cache.Get("foobar"))
}
func ExampleWithLoader() {
loader := func(ctx context.Context, key string) (int, time.Duration, error) {
return 42, time.Hour, nil
}
cache := lru.NewTTLCache[string, int](4096, lru.WithLoader[string, int](loader))
println(cache.Get("a"))
println(cache.Get("b"))
println(cache.GetOrLoad(context.Background(), "a", nil))
println(cache.GetOrLoad(context.Background(), "b", func(context.Context, string) (int, time.Duration, error) { return 100, 0, nil }))
println(cache.Get("a"))
println(cache.Get("b"))
}
func ExampleWithShards() {
cache := lru.NewTTLCache[string, int](4096, lru.WithShards[string, int](1))
cache.Set("foobar", 42, 3*time.Second)
println(cache.Get("foobar"))
}
func ExampleWithSliding() {
cache := lru.NewTTLCache[string, int](4096, lru.WithSliding[string, int](true))
cache.Set("foobar", 42, 3*time.Second)
time.Sleep(2 * time.Second)
println(cache.Get("foobar"))
time.Sleep(2 * time.Second)
println(cache.Get("foobar"))
time.Sleep(2 * time.Second)
println(cache.Get("foobar"))
}