Added basic CacheDict with simple test.

This commit is contained in:
Jeremy Fincher 2009-04-02 11:28:57 -05:00
parent 187620dddc
commit 757991afc9
3 changed files with 42 additions and 4 deletions

View File

@ -1,5 +1,5 @@
###
# Copyright (c) 2005, Jeremiah Fincher
# Copyright (c) 2005-2009, Jeremiah Fincher
# Copyright (c) 2009, James Vega
# All rights reserved.
#
@ -30,6 +30,7 @@
import sys
import types
import UserDict
import threading
def universalImport(*names):
@ -101,6 +102,6 @@ class Synchronized(type):
dict['__init__'] = __init__
newclass = super(Synchronized, cls).__new__(cls, name, bases, dict)
return newclass
# vim:set shiftwidth=4 softtabstop=8 expandtab textwidth=78:

View File

@ -1,5 +1,5 @@
###
# Copyright (c) 2002-2005, Jeremiah Fincher
# Copyright (c) 2002-2009, Jeremiah Fincher
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@ -33,6 +33,7 @@ Data structures for Python.
import time
import types
import UserDict
from itertools import imap
class RingBuffer(object):
@ -417,5 +418,30 @@ class MultiSet(object):
return elt in self.d
class CacheDict(UserDict.DictMixin):
def __init__(self, max, **kwargs):
self.d = dict(**kwargs)
self.max = max
def __getitem__(self, key):
return self.d[key]
def __setitem__(self, key, value):
if len(self.d) >= self.max:
self.d.clear()
self.d[key] = value
def __delitem__(self, key):
del self.d[key]
def keys(self):
return self.d.keys()
def iteritems(self):
return self.d.iteritems()
def __iter__(self):
return iter(self.d)
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:

View File

@ -1123,5 +1123,16 @@ class TestTimeoutQueue(SupyTestCase):
q.reset()
self.failIf(1 in q)
class TestCacheDict(SupyTestCase):
def testMaxNeverExceeded(self):
max = 10
d = CacheDict(10)
for i in xrange(max**2):
d[i] = i
self.failUnless(len(d) <= max)
self.failUnless(i in d)
self.failUnless(d[i] == i)
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: