github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-core-master/utility/ias_proxy/sawtooth_ias_proxy/utils.py (about) 1 # Copyright 2017 Intel Corporation 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 16 from collections import deque 17 from threading import Lock 18 19 20 class LruCache(object): 21 """ 22 A simple thread-safe lru cache. 23 """ 24 25 def __init__(self, max_size=100): 26 self.max_size = max_size 27 self.order = deque(maxlen=self.max_size) 28 self.values = {} 29 self.lock = Lock() 30 31 def __setitem__(self, key, value): 32 with self.lock: 33 if key not in self.values: 34 while len(self.order) >= self.max_size: 35 v = self.order.pop() 36 del self.values[v] 37 self.values[key] = value 38 self.order.appendleft(key) 39 40 def __getitem__(self, key): 41 return self.get(key) 42 43 def get(self, key, default=None): 44 with self.lock: 45 result = self.values.get(key, default) 46 if result is not default: 47 self.order.remove(key) 48 self.order.appendleft(key) 49 return result