
    O|b&                        d Z ddlZdZg dZdZdZ G d de      Z G d	 d
      Ze	dk(  r ed      Z
 ee
        ed      D ]  Z ee      e
e<     ee
       de
v re
d=  ee
       de
_         ee
       de
d<    ee
        e ee
             e
D ]
  Z ee         ee
        ee
j%                  d             e
D ]
  Z ee        yy)a/  a simple LRU (Least-Recently-Used) cache module

This module provides very simple LRU (Least-Recently-Used) cache
functionality.

An *in-memory cache* is useful for storing the results of an
'expensive' process (one that takes a lot of time or resources) for
later re-use. Typical examples are accessing data from the filesystem,
a database, or a network location. If you know you'll need to re-read
the data again, it can help to keep it in a cache.

You *can* use a Python dictionary as a cache for some purposes.
However, if the results you're caching are large, or you have a lot of
possible results, this can be impractical memory-wise.

An *LRU cache*, on the other hand, only keeps _some_ of the results in
memory, which keeps you from overusing resources. The cache is bounded
by a maximum size; if you try to add more values to the cache, it will
automatically discard the values that you haven't read or written to
in the longest time. In other words, the least-recently-used items are
discarded. [1]_

.. [1]: 'Discarded' here means 'removed from the cache'.

    Nz0.2-15)CacheKeyErrorLRUCacheDEFAULT_SIZEzreStructuredText en   c                       e Zd ZdZy)r   zError raised when cache requests fail.

    When a cache record is accessed which no longer exists (or never did),
    this error is raised. To avoid it, you may want to check for the existence
    of a cache record before reading or deleting it.
    N)__name__
__module____qualname____doc__     0lib/python3.12/site-packages/ftputil/lrucache.pyr   r   :   s     	r   r   c                   p    e Zd ZdZ G d d      ZefdZd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Zy)r   a  Least-Recently-Used (LRU) cache.

    Instances of this class provide a least-recently-used (LRU) cache. They
    emulate a Python mapping type. You can use an LRU cache more or less like
    a Python dictionary, with the exception that objects you put into the
    cache may be discarded before you take them out.

    Some example usage::

    cache = LRUCache(32) # new cache
    cache['foo'] = get_file_contents('foo') # or whatever

    if 'foo' in cache: # if it's still in cache...
        # use cached version
        contents = cache['foo']
    else:
        # recalculate
        contents = get_file_contents('foo')
        # store in cache for next time
        cache['foo'] = contents

    print(cache.size) # Maximum size

    print(len(cache)) # 0 <= len(cache) <= cache.size

    cache.size = 10 # Auto-shrink on size assignment

    for i in range(50): # note: larger than cache size
        cache[i] = i

    if 0 not in cache: print('Zero was discarded.')

    if 42 in cache:
        del cache[42] # Manual deletion

    for j in cache:   # iterate (in LRU order)
        print(j, cache[j]) # iterator produces keys, not values
    c                   "    e Zd ZdZd Zd Zd Zy)LRUCache._Nodez5Record of a cached value. Not for public consumption.c                     t         j                  |        || _        || _        || _        | j                  | _        || _        y N)object__init__keyobjatimemtime	_sort_key)selfr   r   	timestampsort_keys        r   r   zLRUCache._Node.__init__p   s5    OOD!DHDH"DJDJ%DNr   c                 4    | j                   |j                   k  S r   )r   )r   others     r   __lt__zLRUCache._Node.__lt__x   s    
 >>EOO33r   c                     d| j                   d| j                  d| j                  dt        j                  t        j
                  | j                              d	S )N< z => z (z)>)	__class__r   r   timeasctime	localtimer   r   s    r   __repr__zLRUCache._Node.__repr__   s:    T^^DJJ78	 r   N)r   r	   r
   r   r   r    r)   r   r   r   _Noder   m   s    C	&	4	r   r*   c                 2    | j                          || _        y)zInit the `LRUCache` object. `size` is the initial
        _maximum_ size of the cache. The size can be changed by
        setting the `size` attribute.
        N)clearsize)r   r-   s     r   r   zLRUCache.__init__   s    
 	

 	r   c                 .    g | _         i | _        d| _        y)zkClear the cache, removing all elements.

        The `size` attribute of the cache isn't modified.
        r   N)_LRUCache__heap_LRUCache__dict_LRUCache__counterr(   s    r   r,   zLRUCache.clear   s     r   c                 D    | xj                   dz  c_         | j                   S )a%  Return a new integer value upon every call.

        Cache nodes need a monotonically increasing time indicator.
        `time.time()` and `time.clock()` don't guarantee this in a
        platform-independent way.

        See http://ftputil.sschwarzer.net/trac/ticket/32 for details.
           )r1   r(   s    r   r   zLRUCache._sort_key   s     	!~~r   c                 ,    t        | j                        S )zReturn _current_ number of cache entries.

        This may be different from the value of the `size`
        attribute.
        )lenr/   r(   s    r   __len__zLRUCache.__len__   s     4;;r   c                     || j                   v S )z;Return `True` if the item denoted by `key` is in the cache.)r0   )r   r   s     r   __contains__zLRUCache.__contains__   s    dkk!!r   c                    | j                   }| j                  }||v rL||   }||_        t        j                         |_        |j                  |_        | j                         |_        yt        |      | j                  k(  r)t        |      }|j                  |       ||j                  = | j                  ||t        j                         | j                               }|||<   |j                  |       y)zStore item `obj` in the cache under the key `key`.

        If the number of elements after the addition of a new key
        would exceed the maximum cache size, the least recently
        used item in the cache is "forgotten".
        N)r/   r0   r   r%   r   r   r   r5   r-   minremover   r*   append)r   r   r   heapdict_nodelru_nodes          r   __setitem__zLRUCache.__setitem__   s     {{%<:DDHDJDJ!^^-DN 4yDII%t9H%(,,'::c3		T^^5EFDE#JKKr   c                     || j                   vrt        |      | j                   |   }t        j                         |_        | j	                         |_        |j
                  S )zReturn the item stored under `key` key.

        If no such key is present in the cache, raise a
        `CacheKeyError`.
        )r0   r   r%   r   r   r   r   r   r?   s      r   __getitem__zLRUCache.__getitem__   sM     dkk!$$;;s#DDJ!^^-DN88Or   c                     || j                   vrt        |      | j                   |   }| j                  j                  |       | j                   |= |j                  S )zDelete the item stored under `key` key.

        If no such key is present in the cache, raise a
        `CacheKeyError`.
        )r0   r   r/   r;   r   rC   s      r   __delitem__zLRUCache.__delitem__   sP     dkk!$$;;s#DKKt$C 88Or   c              #   ~   K   | j                   j                          | j                   D ]  }|j                    yw)z[Iterate over the cache, from the least to the most
        recently accessed item.
        N)r/   sortr   )r   r?   s     r   __iter__zLRUCache.__iter__   s4      	KK 	D((N	s   ;=c                    t         j                  | ||       |dk(  r|}t        |t              st	        d|z        |dk  rt        d|z        | j                  }| j                  }t        |      | j                  k  ry|j                          t        |      | j                  z
  }|d| D ]  }||j                  =  |d|= yy)zsIf the name of the attribute is "size", set the
        _maximum_ size of the cache to the supplied value.
        r-   z"cache size (%r) must be an integerr   z cache size (%d) must be positiveN)r   __setattr__
isinstanceint	TypeError
ValueErrorr/   r0   r5   r-   rH   r   )r   namevaluer-   r=   r>   node_count_to_remover?   s           r   rK   zLRUCache.__setattr__   s     	4u-6>DdC( Dt KLLqy !Cd!JKK;;DKKE4yDII%IIK#&t9tyy#8 223 $$((O$***+! r   c                 \    dt        | j                        t        | j                        fz  S )Nz<%s (%d elements)>)strr$   r5   r/   r(   s    r   r)   zLRUCache.__repr__  s$    #s4>>':C<L&MMMr   c                 j    || j                   vrt        |      | j                   |   }|j                  S )zReturn the last modification time for the cache record with key.

        May be useful for cache instances where the stored values can get
        "stale", such as caching file or network resource contents.
        )r0   r   r   rC   s      r   r   zLRUCache.mtime  s3     dkk!$$;;s#D::r   N)r   r	   r
   r   r*   r   r   r,   r   r6   r8   rA   rD   rF   rI   rK   r)   r   r   r   r   r   r   E   sT    %N 4 ) 	
 "< ,0N
r   r   __main__   2   .   
   46)r   r%   __version____all____docformat__r   KeyErrorr   r   r   cacheprintrangeirT   r-   r5   cr   r   r   r   <module>re      s  &4 
 
7% 	H 	X Xv zRLE	%L2Y q6a	%L	U{"I	%LEJ	%LE"I	%L	#e* a	%L	%++b/ a% r   