-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathexample_test.go
More file actions
81 lines (62 loc) · 1.68 KB
/
Copy pathexample_test.go
File metadata and controls
81 lines (62 loc) · 1.68 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package lru_test
import (
"context"
"fmt"
"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)
fmt.Println(cache.Get("foobar"))
// Output:
// 42 true
}
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))
fmt.Println(cache.Get("a"))
fmt.Println(cache.Get("b"))
fmt.Println(cache.GetOrLoad(context.Background(), "a", nil))
fmt.Println(cache.GetOrLoad(context.Background(), "b", func(context.Context, string) (int, time.Duration, error) { return 100, 0, nil }))
fmt.Println(cache.Get("a"))
fmt.Println(cache.Get("b"))
// Output:
// 0 false
// 0 false
// 42 <nil> false
// 100 <nil> false
// 42 true
// 100 true
}
func ExampleWithShards() {
cache := lru.NewTTLCache[string, int](4096, lru.WithShards[string, int](1))
cache.Set("foobar", 42, 3*time.Second)
fmt.Println(cache.Get("foobar"))
// Output:
// 42 true
}
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)
fmt.Println(cache.Get("foobar"))
time.Sleep(2 * time.Second)
fmt.Println(cache.Get("foobar"))
time.Sleep(2 * time.Second)
fmt.Println(cache.Get("foobar"))
// Output:
// 42 true
// 42 true
// 42 true
}