Remove BPA from Makefile
[icn.git] / cmd / bpa-operator / vendor / k8s.io / apimachinery / pkg / util / cache / cache.go
1 /*
2 Copyright 2014 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
17 package cache
18
19 import (
20         "sync"
21 )
22
23 const (
24         shardsCount int = 32
25 )
26
27 type Cache []*cacheShard
28
29 func NewCache(maxSize int) Cache {
30         if maxSize < shardsCount {
31                 maxSize = shardsCount
32         }
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,
38                 }
39         }
40         return cache
41 }
42
43 func (c Cache) getShard(index uint64) *cacheShard {
44         return c[index%uint64(shardsCount)]
45 }
46
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)
50 }
51
52 func (c *Cache) Get(index uint64) (obj interface{}, found bool) {
53         return c.getShard(index).get(index)
54 }
55
56 type cacheShard struct {
57         items map[uint64]interface{}
58         sync.RWMutex
59         maxSize int
60 }
61
62 // Returns true if object already existed, false otherwise.
63 func (s *cacheShard) add(index uint64, obj interface{}) bool {
64         s.Lock()
65         defer s.Unlock()
66         _, isOverwrite := s.items[index]
67         if !isOverwrite && len(s.items) >= s.maxSize {
68                 var randomKey uint64
69                 for randomKey = range s.items {
70                         break
71                 }
72                 delete(s.items, randomKey)
73         }
74         s.items[index] = obj
75         return isOverwrite
76 }
77
78 func (s *cacheShard) get(index uint64) (obj interface{}, found bool) {
79         s.RLock()
80         defer s.RUnlock()
81         obj, found = s.items[index]
82         return
83 }