...

Source file src/go.opencensus.io/trace/lrumap.go

Documentation: go.opencensus.io/trace

     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  
    15  package trace
    16  
    17  import (
    18  	"github.com/golang/groupcache/lru"
    19  )
    20  
    21  // A simple lru.Cache wrapper that tracks the keys of the current contents and
    22  // the cumulative number of evicted items.
    23  type lruMap struct {
    24  	cacheKeys    map[lru.Key]bool
    25  	cache        *lru.Cache
    26  	droppedCount int
    27  }
    28  
    29  func newLruMap(size int) *lruMap {
    30  	lm := &lruMap{
    31  		cacheKeys:    make(map[lru.Key]bool),
    32  		cache:        lru.New(size),
    33  		droppedCount: 0,
    34  	}
    35  	lm.cache.OnEvicted = func(key lru.Key, value interface{}) {
    36  		delete(lm.cacheKeys, key)
    37  		lm.droppedCount++
    38  	}
    39  	return lm
    40  }
    41  
    42  func (lm lruMap) len() int {
    43  	return lm.cache.Len()
    44  }
    45  
    46  func (lm lruMap) keys() []interface{} {
    47  	keys := make([]interface{}, 0, len(lm.cacheKeys))
    48  	for k := range lm.cacheKeys {
    49  		keys = append(keys, k)
    50  	}
    51  	return keys
    52  }
    53  
    54  func (lm *lruMap) add(key, value interface{}) {
    55  	lm.cacheKeys[lru.Key(key)] = true
    56  	lm.cache.Add(lru.Key(key), value)
    57  }
    58  
    59  func (lm *lruMap) get(key interface{}) (interface{}, bool) {
    60  	return lm.cache.Get(key)
    61  }
    62  

View as plain text