...

Source file src/k8s.io/utils/lru/lru.go

Documentation: k8s.io/utils/lru

     1  /*
     2  Copyright 2021 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  package lru
    17  
    18  import (
    19  	"sync"
    20  
    21  	groupcache "k8s.io/utils/internal/third_party/forked/golang/golang-lru"
    22  )
    23  
    24  type Key = groupcache.Key
    25  type EvictionFunc = func(key Key, value interface{})
    26  
    27  // Cache is a thread-safe fixed size LRU cache.
    28  type Cache struct {
    29  	cache *groupcache.Cache
    30  	lock  sync.RWMutex
    31  }
    32  
    33  // New creates an LRU of the given size.
    34  func New(size int) *Cache {
    35  	return &Cache{
    36  		cache: groupcache.New(size),
    37  	}
    38  }
    39  
    40  // NewWithEvictionFunc creates an LRU of the given size with the given eviction func.
    41  func NewWithEvictionFunc(size int, f EvictionFunc) *Cache {
    42  	c := New(size)
    43  	c.cache.OnEvicted = f
    44  	return c
    45  }
    46  
    47  // Add adds a value to the cache.
    48  func (c *Cache) Add(key Key, value interface{}) {
    49  	c.lock.Lock()
    50  	defer c.lock.Unlock()
    51  	c.cache.Add(key, value)
    52  }
    53  
    54  // Get looks up a key's value from the cache.
    55  func (c *Cache) Get(key Key) (value interface{}, ok bool) {
    56  	c.lock.Lock()
    57  	defer c.lock.Unlock()
    58  	return c.cache.Get(key)
    59  }
    60  
    61  // Remove removes the provided key from the cache.
    62  func (c *Cache) Remove(key Key) {
    63  	c.lock.Lock()
    64  	defer c.lock.Unlock()
    65  	c.cache.Remove(key)
    66  }
    67  
    68  // RemoveOldest removes the oldest item from the cache.
    69  func (c *Cache) RemoveOldest() {
    70  	c.lock.Lock()
    71  	defer c.lock.Unlock()
    72  	c.cache.RemoveOldest()
    73  }
    74  
    75  // Len returns the number of items in the cache.
    76  func (c *Cache) Len() int {
    77  	c.lock.RLock()
    78  	defer c.lock.RUnlock()
    79  	return c.cache.Len()
    80  }
    81  
    82  // Clear purges all stored items from the cache.
    83  func (c *Cache) Clear() {
    84  	c.lock.Lock()
    85  	defer c.lock.Unlock()
    86  	c.cache.Clear()
    87  }
    88  

View as plain text