2 Copyright 2014 The Kubernetes Authors.
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
8 http://www.apache.org/licenses/LICENSE-2.0
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.
27 type Cache []*cacheShard
29 func NewCache(maxSize int) Cache {
30 if maxSize < shardsCount {
33 cache := make(Cache, shardsCount)
34 for i := 0; i < shardsCount; i++ {
35 cache[i] = &cacheShard{
36 items: make(map[uint64]interface{}),
37 maxSize: maxSize / shardsCount,
43 func (c Cache) getShard(index uint64) *cacheShard {
44 return c[index%uint64(shardsCount)]
47 // Returns true if object already existed, false otherwise.
48 func (c *Cache) Add(index uint64, obj interface{}) bool {
49 return c.getShard(index).add(index, obj)
52 func (c *Cache) Get(index uint64) (obj interface{}, found bool) {
53 return c.getShard(index).get(index)
56 type cacheShard struct {
57 items map[uint64]interface{}
62 // Returns true if object already existed, false otherwise.
63 func (s *cacheShard) add(index uint64, obj interface{}) bool {
66 _, isOverwrite := s.items[index]
67 if !isOverwrite && len(s.items) >= s.maxSize {
69 for randomKey = range s.items {
72 delete(s.items, randomKey)
78 func (s *cacheShard) get(index uint64) (obj interface{}, found bool) {
81 obj, found = s.items[index]