github.com/phuslu/lru@v1.0.16-0.20240421170520-46288a2fd47c/example_test.go (about)

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