""" A simple mapping between keys and values, but with a limited capacity. When the max. capacity is reached, the first inserted key/value pair is deleted """ # Copyright 2005, 2006 EIAO Consoritum # This program is distributed under the terms of the GNU General # Public License. # # This file is part of the European Internet Accessibility Observatory # (EIAO) # # EIAO is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # EIAO is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with EIAO; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, # MA 02110-1301 USA __author__ = "Christian Thomsen" __maintainer__ = "Christian Thomsen" __version__ = 0.9901 class FIFOCache: """ A simple FIFO-cache mapping between keys and values. When the max. capacity is reached, the first inserted key/value pair is deleted """ def __init__(self, size): """The constructor. The argument size determines the maximum size of the cache.""" if not type(size) == type(0): raise TypeError, "size must be an int" if not size > 0: raise ValueError, "size must be positive" self.__size = size self.__data = {} self.__order = [] self.__first = 0 def add(self, key, val): """Adds a key/value pair to the cache. If the maximum capacity is reached, the oldest kay/value pair is deleted from the cache. The argument key is the key and the argument val is the value.""" if self.__data.get(key) is not None: # May be 0 return elif len(self.__order) < self.__size: self.__order.append(key) self.__data[key] = val else: # We have to delete the oldest item delKey = self.__order[self.__first] del self.__data[delKey] self.__order[self.__first] = key self.__first = (self.__first + 1) % self.__size self.__data[key] = val def lookup(self, key): """Looks for the given key in the cache and returns the associated value if found. If not found, None is returned.""" return self.__data.get(key) def clear(self): """Deletes all key/value pairs from the cache""" self.__data = {} self.__order = [] self.__first = 0