lrumap.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2019, OpenCensus Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package trace
  15. import (
  16. "github.com/golang/groupcache/lru"
  17. )
  18. // A simple lru.Cache wrapper that tracks the keys of the current contents and
  19. // the cumulative number of evicted items.
  20. type lruMap struct {
  21. cacheKeys map[lru.Key]bool
  22. cache *lru.Cache
  23. droppedCount int
  24. }
  25. func newLruMap(size int) *lruMap {
  26. lm := &lruMap{
  27. cacheKeys: make(map[lru.Key]bool),
  28. cache: lru.New(size),
  29. droppedCount: 0,
  30. }
  31. lm.cache.OnEvicted = func(key lru.Key, value interface{}) {
  32. delete(lm.cacheKeys, key)
  33. lm.droppedCount++
  34. }
  35. return lm
  36. }
  37. func (lm lruMap) len() int {
  38. return lm.cache.Len()
  39. }
  40. func (lm lruMap) keys() []interface{} {
  41. keys := []interface{}{}
  42. for k := range lm.cacheKeys {
  43. keys = append(keys, k)
  44. }
  45. return keys
  46. }
  47. func (lm *lruMap) add(key, value interface{}) {
  48. lm.cacheKeys[lru.Key(key)] = true
  49. lm.cache.Add(lru.Key(key), value)
  50. }
  51. func (lm *lruMap) get(key interface{}) (interface{}, bool) {
  52. return lm.cache.Get(key)
  53. }