Package translate :: Package misc :: Module lru |
[hide private]
[frames] | no frames]

# Source Code for Module translate.misc.lru

      1  #!/usr/bin/env python
      2  # -*- coding: utf-8 -*-
      3  #
      4  # Copyright 2009 Zuza Software Foundation
      5  #
      6  # This file is part of translate.
      7  #
      8  # This program is free software; you can redistribute it and/or modify
      9  # it under the terms of the GNU General Public License as published by
     10  # the Free Software Foundation; either version 2 of the License, or
     11  # (at your option) any later version.
     12  #
     13  # This program is distributed in the hope that it will be useful,
     14  # but WITHOUT ANY WARRANTY; without even the implied warranty of
     15  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16  # GNU General Public License for more details.
     17  #
     18  # You should have received a copy of the GNU General Public License
     19  # along with this program; if not, see <http://www.gnu.org/licenses/>.
     20
     21  from collections import deque
     22  from weakref import WeakValueDictionary
     23  import gc
     24
     25 -class LRUCachingDict(WeakValueDictionary):
     26      """Caching dictionary like object that discards the least recently
     27      used objects when number of cached items exceeds maxsize.
     28
     29      cullsize is the fraction of items that will be discarded when
     30      maxsize is reached.
     31      """
     32
     33 -    def __init__(self, maxsize, cullsize=2, *args, **kwargs):
     34          self.cullsize = max(2, cullsize)
     35          self.maxsize = max(cullsize, maxsize)
     36          self.queue = deque()
     37          WeakValueDictionary.__init__(self, *args, **kwargs)
     38
     39 -    def __setitem__(self, key, value):
     40          # check boundaries to minimiza duplicate references
     41          while len(self.queue) and self.queue[0][0] == key:
     42              # item at left end of queue pop it since it'll be appended
     43              # to right
     44              self.queue.popleft()
     45
     46          while len(self.queue) and self.queue[-1][0] == key:
     47              # item at right end of queue pop it since it'll be
     48              # appended again
     49              self.queue.pop()
     50
     51          if len(self) >= self.maxsize:
     52              # maximum cache size exceeded, cull old items
     53              #
     54              # note queue is the real cache but its size is boundless
     55              # since it might have duplicate references.
     56              #
     57              # don't bother culling if queue is smaller than weakref,
     58              # this means there are too many references outside the
     59              # cache, culling won't free much memory (if any).
     60              while len(self) >= self.maxsize <= len(self.queue):
     61                  cullsize = max(int(len(self.queue) / self.cullsize), 2)
     62                  try:
     63                      for i in range(cullsize):
     64                          self.queue.popleft()
     65                  except IndexError:
     66                      # queue is empty, bail out.
     67                      break
     68                  finally:
     69                      # call garbage collecter manually since objects
     70                      # with circular references take some time to get
     71                      # collected
     72                      for i in range(5):
     73                          if gc.collect() == 0:
     74                              break
     75          self.queue.append((key, value))
     76          WeakValueDictionary.__setitem__(self, key, value)
     77
     78
     79 -    def __getitem__(self, key):
     80          value = WeakValueDictionary.__getitem__(self, key)
     81          # check boundaries to minimiza duplicate references
     82          while len(self.queue) > 0  and self.queue[0][0] == key:
     83              # item at left end of queue pop it since it'll be appended
     84              # to right
     85              self.queue.popleft()
     86
     87          # only append if item is not at right end of queue
     88          if not (len(self.queue) and self.queue[-1][0] == key):
     89              self.queue.append((key, value))
     90
     91          return value
     92
     93 -    def __delitem__(self, key):
     94          # can't efficiently find item in queue to delete, check
     95          # boundaries. otherwise just wait till next cache purge
     96          while len(self.queue) and self.queue[0][0] == key:
     97              # item at left end of queue pop it since it'll be appended
     98              # to right
     99              self.queue.popleft()
    100
    101          while len(self.queue) and self.queue[-1][0] == key:
    102              # item at right end of queue pop it since it'll be
    103              # appended again
    104              self.queue.pop()
    105
    106          return WeakValueDictionary.__delitem__(self, key)
    107
    108 -    def clear(self):
    109          self.queue.clear()
    110          return WeakValueDictionary.clear(self)
    111
    112 -    def setdefault(self, key, default):
    113          if key not in self:
    114              self[key]=default
    115
    116          return self[key]
    117