Python port of ShadowsocksR
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.9 KiB

11 years ago
#!/usr/bin/python
# -*- coding: utf-8 -*-
import collections
import logging
import heapq
import time
class LRUCache(collections.MutableMapping):
"""This class is not thread safe"""
11 years ago
def __init__(self, timeout=60, close_callback=None, *args, **kwargs):
11 years ago
self.timeout = timeout
11 years ago
self.close_callback = close_callback
11 years ago
self._store = {}
self._time_to_keys = collections.defaultdict(list)
self._last_visits = []
11 years ago
self.update(dict(*args, **kwargs)) # use the free update to set keys
def __getitem__(self, key):
11 years ago
# O(logm)
11 years ago
t = time.time()
11 years ago
self._time_to_keys[t].append(key)
heapq.heappush(self._last_visits, t)
return self._store[key]
11 years ago
def __setitem__(self, key, value):
11 years ago
# O(logm)
11 years ago
t = time.time()
11 years ago
self._store[key] = value
self._time_to_keys[t].append(key)
heapq.heappush(self._last_visits, t)
11 years ago
def __delitem__(self, key):
11 years ago
# O(1)
del self._store[key]
11 years ago
def __iter__(self):
11 years ago
return iter(self._store)
11 years ago
def __len__(self):
11 years ago
return len(self._store)
11 years ago
def sweep(self):
11 years ago
# O(m)
11 years ago
now = time.time()
c = 0
11 years ago
while len(self._last_visits) > 0:
least = self._last_visits[0]
11 years ago
if now - least <= self.timeout:
break
if self.close_callback is not None:
for key in self._time_to_keys[least]:
if self._store.__contains__(key):
value = self._store[key]
self.close_callback(value)
11 years ago
for key in self._time_to_keys[least]:
heapq.heappop(self._last_visits)
if self._store.__contains__(key):
del self._store[key]
11 years ago
c += 1
11 years ago
del self._time_to_keys[least]
11 years ago
if c:
logging.debug('%d keys swept' % c)