| 1 |
package sievecache_test |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
|
| 6 |
"github.com/jedisct1/go-sieve-cache/pkg/sievecache" |
| 7 |
) |
| 8 |
|
| 9 |
|
| 10 |
func Example() { |
| 11 |
|
| 12 |
cache, _ := sievecache.New[string, string](100) |
| 13 |
|
| 14 |
|
| 15 |
cache.Insert("key1", "value1") |
| 16 |
cache.Insert("key2", "value2") |
| 17 |
|
| 18 |
|
| 19 |
value, found := cache.Get("key1") |
| 20 |
if found { |
| 21 |
fmt.Println("Found:", value) |
| 22 |
} |
| 23 |
|
| 24 |
|
| 25 |
cache.Remove("key2") |
| 26 |
|
| 27 |
|
| 28 |
fmt.Println("Cache size:", cache.Len()) |
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
} |
| 34 |
|
| 35 |
|
| 36 |
func ExampleSyncSieveCache() { |
| 37 |
|
| 38 |
cache, _ := sievecache.NewSync[string, int](100) |
| 39 |
|
| 40 |
|
| 41 |
cache.Insert("counter", 5) |
| 42 |
|
| 43 |
|
| 44 |
cache.GetMut("counter", func(value *int) { |
| 45 |
*value = *value * 2 |
| 46 |
}) |
| 47 |
|
| 48 |
|
| 49 |
val, _ := cache.Get("counter") |
| 50 |
fmt.Println("Counter:", val) |
| 51 |
|
| 52 |
|
| 53 |
cache.WithLock(func(innerCache *sievecache.SieveCache[string, int]) { |
| 54 |
innerCache.Insert("a", 1) |
| 55 |
innerCache.Insert("b", 2) |
| 56 |
innerCache.Insert("sum", 3) |
| 57 |
}) |
| 58 |
|
| 59 |
fmt.Println("Cache size:", cache.Len()) |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
} |
| 65 |
|
| 66 |
|
| 67 |
func ExampleShardedSieveCache() { |
| 68 |
|
| 69 |
cache, _ := sievecache.NewShardedWithShards[string, int](1000, 8) |
| 70 |
fmt.Printf("Created sharded cache with %d shards\n", cache.NumShards()) |
| 71 |
|
| 72 |
|
| 73 |
cache.Insert("counter", 0) |
| 74 |
|
| 75 |
|
| 76 |
cache.GetMut("counter", func(value *int) { |
| 77 |
*value += 1 |
| 78 |
}) |
| 79 |
|
| 80 |
|
| 81 |
val, _ := cache.Get("counter") |
| 82 |
fmt.Println("Counter:", val) |
| 83 |
|
| 84 |
|
| 85 |
cache.Insert("counter", 5) |
| 86 |
val, _ = cache.Get("counter") |
| 87 |
fmt.Println("Counter:", val) |
| 88 |
|
| 89 |
|
| 90 |
cache.Insert("related", 10) |
| 91 |
relatedVal, _ := cache.Get("related") |
| 92 |
fmt.Println("Related:", relatedVal) |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
} |
| 100 |
|
| 101 |
|
| 102 |
func ExampleSieveCache_RecommendedCapacity() { |
| 103 |
cache, _ := sievecache.New[string, int](100) |
| 104 |
|
| 105 |
|
| 106 |
for i := 0; i < 80; i++ { |
| 107 |
cache.Insert(fmt.Sprintf("key%d", i), i) |
| 108 |
|
| 109 |
|
| 110 |
if i%2 == 0 { |
| 111 |
cache.Get(fmt.Sprintf("key%d", i)) |
| 112 |
} |
| 113 |
} |
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
newCapacity := cache.RecommendedCapacity(0.5, 2.0, 0.3, 0.7) |
| 121 |
fmt.Printf("Recommended capacity for a cache with %d/%d items: %d\n", |
| 122 |
cache.Len(), cache.Capacity(), newCapacity) |
| 123 |
|
| 124 |
|
| 125 |
} |