Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add separate expirable LRU implementation, with generics #116

Merged
merged 7 commits into from
Aug 7, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 57 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ Documentation

Full docs are available on [Go Packages](https://pkg.go.dev/github.com/hashicorp/golang-lru/v2)

Example
=======

Using the LRU is very simple:
LRU cache example
=================

```go
package main
Expand All @@ -23,12 +21,60 @@ import (
)

func main() {
l, _ := lru.New[int, any](128)
for i := 0; i < 256; i++ {
l.Add(i, nil)
}
if l.Len() != 128 {
panic(fmt.Sprintf("bad len: %v", l.Len()))
}
l, _ := lru.New[int, any](128)
for i := 0; i < 256; i++ {
l.Add(i, nil)
}
if l.Len() != 128 {
panic(fmt.Sprintf("bad len: %v", l.Len()))
}
}
```

Expirable LRU cache example
===========================

```go
package main

import (
"fmt"
"time"

"github.com/hashicorp/golang-lru/v2/expirable"
)

func main() {
// make cache with 10ms TTL and 5 max keys
cache := expirable.NewExpirableLRU[string, string](5, nil, time.Millisecond*10)
// expirable cache need to be closed after used
defer cache.Close()

// set value under key1.
cache.Add("key1", "val1")

// get value under key1
r, ok := cache.Get("key1")

// check for OK value
if ok {
fmt.Printf("value before expiration is found: %v, value: %q\n", ok, r)
}

// wait for cache to expire
time.Sleep(time.Millisecond * 12)

// get value under key1 after key expiration
r, ok = cache.Get("key1")
fmt.Printf("value after expiration is found: %v, value: %q\n", ok, r)

// set value under key2, would evict old entry because it is already expired.
cache.Add("key2", "val2")

fmt.Printf("Cache len: %d\n", cache.Len())
// Output:
// value before expiration is found: true, value: "val1"
// value after expiration is found: false, value: ""
// Cache len: 1
}
```
Loading