You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
lru always calls onEvict once when Remove is called. In a case where the element that I want to remove is already processed, and the processing logic is different from onEvict, I want to simply remove the element RemoveWithoutEvict API, it may be written as follow:
Second this, it would essentially allow for an LRU Pool where values can be removed and added with a capacity limit. I also wanted to offer a temporary solution I found to this annoying issue.
import (
"io"
lru "github.com/hashicorp/golang-lru/v2"
)
typecacherstruct {
cache*lru.Cache[int64, io.ReadCloser]
}
funcNewCache() (*cacher, error) {
cache, err:=lru.NewWithEvict(10, func(keyint64, value io.ReadCloser) {
ifvalue!=nil {
// Do something here. The value has been removed and you// can catch the eviction To have some conditional action.value.Close()
}
})
iferr!=nil {
returnnil, err
}
return&cacher{cache}, nil
}
func (c*cacher) Get(offsetint64) (io.ReadCloser, bool) {
ifv, ok:=c.cache.Peek(offset); ok {
// Update the value to nil so we know that// it has been removed but NOT evicted.c.cache.Add(offset, nil)
// Remove the value which forces an eviction// of the nil value and return the actual value.returnv, c.cache.Remove(offset)
}
returnnil, false
}
func (c*cacher) Add(offsetint64, rc io.ReadCloser) bool {
// Don't allow nil values to be added.ifrc==nil {
returnfalse
}
returnc.cache.Add(offset, rc)
}
Note that this will only work with values comparable to nil, and it works under the assumption that no values in your LRU cache will be nil. When getting a value you can force update an entry to nil, and then conditionally do an action during eviction to do a "fake" eviction while keeping the actual value. This is pretty useful for things like files that may need to be closed during eviction but not when you just want to Get the value.
@bodgit this could be a temporary fix for your PR for sevenzip
lru always calls
onEvict
once whenRemove
is called. In a case where the element that I want to remove is already processed, and the processing logic is different from onEvict, I want to simply remove the elementRemoveWithoutEvict
API, it may be written as follow:The text was updated successfully, but these errors were encountered: