
    .Ph]                         d Z ddlmZmZmZmZ ddlZddlmZ g dZ	 G d d          Z
 G d	 d
          Z G d de          ZdS )zlModule containing a memory memory manager which provides a sliding window on a number of memory mapped files   )	MapWindow	MapRegionMapRegionList	is_64_bit    N)reduce)StaticWindowMapManagerSlidingWindowMapManagerWindowCursorc                       e Zd ZdZdZddZd Zd Zd Zd Z	d	 Z
d
 Zd ZddZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZdS )r   a  
    Pointer into the mapped region of the memory manager, keeping the map
    alive until it is destroyed and no other client uses it.

    Cursors should not be created manually, but are instead returned by the SlidingWindowMapManager

    **Note:**: The current implementation is suited for static and sliding window managers, but it also means
    that it must be suited for the somewhat quite different sliding manager. It could be improved, but
    I see no real need to do so._manager_rlist_region_ofs_sizeNc                 L    || _         || _        d | _        d| _        d| _        d S )Nr   r   )selfmanagerregionss      J/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/smmap/mman.py__init__zWindowCursor.__init__%   s)    	


    c                 .    |                                   d S N_destroyr   s    r   __del__zWindowCursor.__del__,       r   c                     | S r    r   s    r   	__enter__zWindowCursor.__enter__/   s    r   c                 .    |                                   d S r   r   )r   exc_type	exc_value	tracebacks       r   __exit__zWindowCursor.__exit__2   r    r   c                    |                                   | j        k	 t          | j                  dk    r8| j        j                            | j                                                   dS dS # t          t          f$ r Y dS w xY wdS )z&Destruction code to decrement countersNr   )	unuse_regionr   lenr   _fdictpop
path_or_fd	TypeErrorKeyErrorr   s    r   r   zWindowCursor._destroy5   s    ;"
t{##q((M(,,T[-C-C-E-EFFFFF )( x(   
  #"s   AA/ /BBc                 4   |j         | _          t          |j                  |j                  | _        |j        | _        |j        | _        |j        | _        | j        D ]}|                                 | j        | j                                         dS dS )z>Copy all data from rhs into this instance, handles usage countN)r   typer   r   r   r   increment_client_count)r   rhsregions      r   
_copy_fromzWindowCursor._copy_fromJ   s    &d3:&&sz22{H	Y
k 	, 	,F))++++<#L//11111 $#r   c                 ^     t          |                       }|                    |            |S )zcopy module interface)r2   r6   )r   cpys     r   __copy__zWindowCursor.__copy__Y   s*    d4jjllt
r   c                 X    |                                   |                     |           dS )zAssign rhs to this instance. This is required in order to get a real copy.
        Alternatively, you can copy an existing instance using the copy moduleN)r   r6   )r   r4   s     r   assignzWindowCursor.assign`   s)     	r   r   c                    d}| j         }| j                                        }t          |p||                                p|          }| j        1| j                            |          rd}n|                                  ||k    r| S |r<|                    | j        |||d          | _        | j        	                                 || j        j
        z
  | _        t          || j                                        |z
            | _        | S )a$  Assure we point to a window which allows access to the given offset into the file

        :param offset: absolute offset in bytes into the file
        :param size: amount of bytes to map. If 0, all available bytes will be mapped
        :param flags: additional flags to be given to os.open in case a file handle is initially opened
            for mapping. Has no effect if a region can actually be reused.
        :return: this instance - it should be queried for whether it points to a valid memory region.
            This is not the case if the mapping failed because we reached the end of the file

        **Note:**: The size actually mapped may be smaller than the given size. If that is the case,
        either the file has reached its end, or the map was created between two existing regionsTNF)r   r   	file_sizeminwindow_sizer   includes_ofsr*   _obtain_regionr3   _br   ofs_endr   )r   offsetsizeflagsneed_regionmanfsizes          r   
use_regionzWindowCursor.use_regionf   s    m%%''4=5#//"3"3"<u==<#|((00 $#!!###
 U??K  	2--dk64PUVVDLL//111 T\_,	t|3355>??
r   c                 V    | j         | j                             d           d| _         dS )a/  Unuse the current region. Does nothing if we have no current region

        **Note:** the cursor unuses the region automatically upon destruction. It is recommended
        to un-use the region once you are done reading from it in persistent cursors as it
        helps to free up resource more quicklyN)r   r3   r   s    r   r*   zWindowCursor.unuse_region   s-     <#L//333r   c                     t          | j                                                  | j        | j        | j        z            S )a  Return a buffer object which allows access to our memory region from our offset
        to the window size. Please note that it might be smaller than you requested when calling use_region()

        **Note:** You can only obtain a buffer if this instance is_valid() !

        **Note:** buffers should not be cached passed the duration of your access as it will
        prevent resources from being freed even though they might not be accounted for anymore !)
memoryviewr   bufferr   r   r   s    r   rO   zWindowCursor.buffer   s5     $,--//0049TZ;O1OPPr   c                 4    | j                                         S )a  
        :return: the underlying raw memory map. Please not that the offset and size is likely to be different
            to what you set as offset and size. Use it only if you are sure about the region it maps, which is the whole
            file in case of StaticWindowMapManager)r   mapr   s    r   rQ   zWindowCursor.map   s    
 |!!!r   c                     | j         duS )z2:return: True if we have a valid and usable regionNr   r   s    r   is_validzWindowCursor.is_valid   s    |4''r   c                     | j         duS )z?:return: True if we are associated with a specific file alreadyN)r   r   s    r   is_associatedzWindowCursor.is_associated   s    {$&&r   c                 *    | j         j        | j        z   S )zh:return: offset to the first byte pointed to by our cursor

        **Note:** only if is_valid() is True)r   rB   r   r   s    r   	ofs_beginzWindowCursor.ofs_begin   s     |**r   c                 :    | j         j        | j        z   | j        z   S )z3:return: offset to one past the last available byter   rB   r   r   r   s    r   rC   zWindowCursor.ofs_end   s     |*TZ77r   c                     | j         S )z$:return: amount of bytes we point to)r   r   s    r   rE   zWindowCursor.size   s
    zr   c                     | j         S )z:return: our mapped region, or None if nothing is mapped yet
        :raise AssertionError: if we have no current region. This is only useful for debuggingrS   r   s    r   r5   zWindowCursor.region   s     |r   c                 z    | j         j        | j        z   |cxk    o| j         j        | j        z   | j        z   k     nc S )z:return: True if the given absolute offset is contained in the cursors
            current region

        **Note:** cursor must be valid for this to workrZ   )r   ofss     r   r@   zWindowCursor.includes_ofs   sE     $)+````t|7RUYU_7_`````r   c                 4    | j                                         S )z$:return: size of the underlying file)r   r=   r   s    r   r=   zWindowCursor.file_size   s    {$$&&&r   c                 4    | j                                         S )z>:return: path or file descriptor of the underlying mapped file)r   r.   r   s    r   r.   zWindowCursor.path_or_fd   s    {%%'''r   c                     t          | j                                        t                    rt	          d          | j                                        S )ze:return: path of the underlying mapped file
        :raise ValueError: if attached path is not a pathz>Path queried although mapping was applied to a file descriptor)
isinstancer   r.   int
ValueErrorr   s    r   pathzWindowCursor.path   sH     dk,,..44 	_]^^^{%%'''r   c                     t          | j                                        t                    rt	          d          | j                                        S )z:return: file descriptor used to create the underlying mapping.

        **Note:** it is not required to be valid anymore
        :raise ValueError: if the mapping was not created by a file descriptorz@File descriptor queried although mapping was generated from path)rb   r   r.   strrd   r   s    r   fdzWindowCursor.fd   sH    
 dk,,..44 	a_```{%%'''r   )NN)r   r   r   )__name__
__module____qualname____doc__	__slots__r   r   r#   r(   r   r6   r9   r;   rJ   r*   rO   rQ   rT   rV   rX   rC   rE   r5   r@   r=   r.   re   rh   r"   r   r   r   r      s       $ $I           *2 2 2    & & & &P  Q Q Q" " "( ( (' ' '+ + +8 8 8
    
a a a' ' '( ( (( ( (( ( ( ( (r   r   c                       e Zd ZdZg dZeZeZe	Z
eZdZddej        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dS )r	   a  Provides a manager which will produce single size cursors that are allowed
    to always map the whole file.

    Clients must be written to specifically know that they are accessing their data
    through a StaticWindowMapManager, as they otherwise have to deal with their window size.

    These clients would have to use a SlidingWindowMapBuffer to hide this fact.

    This type will always use a maximum window size, and optimize certain methods to
    accommodate this fact)r,   _window_size_max_memory_size_max_handle_count_memory_size_handle_counti   r   c                    t                      | _        || _        || _        || _        d| _        d| _        |dk     r!d}t                      rd}|| j        z  | _        |dk    r#d}t                      rd}|| j        z  | _        dS dS )a  initialize the manager with the given parameters.
        :param window_size: if -1, a default window size will be chosen depending on
            the operating system's architecture. It will internally be quantified to a multiple of the page size
            If 0, the window may have any size, which basically results in mapping the whole file at one
        :param max_memory_size: maximum amount of memory we may map at once before releasing mapped regions.
            If 0, a viable default will be set depending on the system's architecture.
            It is a soft limit that is tried to be kept, but nothing bad happens if we have to over-allocate
        :param max_open_handles: if not maxint, limit the amount of open file handles to the given number.
            Otherwise the amount is only limited by the system itself. If a system or soft limit is hit,
            the manager will free as many handles as possibler   @   i   i    N)	dictr,   ro   rp   rq   rr   rs   r   _MB_in_bytes)r   r?   max_memory_sizemax_open_handlescoeffs        r   r   zStaticWindowMapManager.__init__  s     ff' /!1??E{{  %(9 9D aE{{ $)D,=$=D!!!  r   c                    d}|dk    s| j         |z   | j        k    rd}d}| j                                        D ]5}|D ]0}|                                dk    r||j        |j        k     r|}|}16|n{|dz  }||                    |          = |                    d           | xj         |                                z  c_         | xj	        dz  c_	        |dk    | j         |z   | j        k    |S )am  Unmap the region which was least-recently used and has no client
        :param size: size of the region we want to map next (assuming its not already mapped partially or full
            if 0, we try to free any available region
        :return: Amount of freed regions

        .. Note::
            We don't raise exceptions anymore, in order to keep the system working, allowing temporary overallocation.
            If the system runs out of memory, it will tell.

        .. TODO::
            implement a case where all unusued regions are discarded efficiently.
            Currently its only brute force
        r   Nr   rL   )
rr   rp   r,   valuesclient_count_ucindexr3   rE   rs   )r   rE   	num_found
lru_regionlru_listr   r5   s          r   _collect_lru_regionz*StaticWindowMapManager._collect_lru_region/  s0    	qyyd/$69NNNJH;--// + +% + +F++--22'/6:
3N3N%+
#*+ ! NI
334--b111!2!22!#- qyyd/$69NNN0 r   c                 D   | j         |z   | j        k    r|                     |           d}|rt          |          dk    sJ |d         }n	 |                     |                                dt          j        |          }nA# t          $ r4 |r |                     d           | 	                    ||||d          cY S w xY w| xj
        dz  c_
        | xj         |                                z  c_         |                    |           |                    |          sJ |S )zUtility to create a new region - for more information on the parameters,
        see MapCursor.use_region.
        :param a: A regions (a)rray
        :return: The newly created regionNr   r   T)rr   rp   r   r+   MapRegionClsr.   sysmaxsize	ExceptionrA   rs   rE   appendr@   )r   arD   rE   rF   is_recursivers          r   rA   z%StaticWindowMapManager._obtain_regionX  sJ   
 t#d&;;;$$T***  	q66Q;;;;!AAI%%allnnaeLL I I I
    ((+++**1fdE4HHHHHI !#)HHQKKK ~~f%%%%%s   4B ;B?>B?c                     | j                             |          }||                     |          }|| j         |<   |                     | |          S )a  
        :return: a cursor pointing to the given path or file descriptor.
            It can be used to map new regions of the file into memory

        **Note:** if a file descriptor is given, it is assumed to be open and valid,
        but may be closed afterwards. To refer to the same file, you may reuse
        your existing file descriptor, but keep in mind that new windows can only
        be mapped as long as it stays valid. This is why the using actual file paths
        are preferred unless you plan to keep the file descriptor open.

        **Note:** file descriptors are problematic as they are not necessarily unique, as two
        different files opened and closed in succession might have the same file descriptor id.

        **Note:** Using file descriptors directly is faster once new windows are mapped as it
        prevents the file to be opened again just for the purpose of mapping it.)r,   getMapRegionListClsWindowCursorCls)r   r.   r   s      r   make_cursorz"StaticWindowMapManager.make_cursor  sQ      +//*--?++J77G&-DK
###D'222r   c                 ,    |                      d          S )z]Collect all available free-to-collect mapped regions
        :return: Amount of freed handlesr   )r   r   s    r   collectzStaticWindowMapManager.collect  s     ''***r   c                     | j         S )zO:return: amount of file handles in use. Each mapped region uses one file handle)rs   r   s    r   num_file_handlesz'StaticWindowMapManager.num_file_handles  s    !!r   c                 h    t          d d | j                                        D             d          S )z$Amount of opened files in the systemc                     | |z   S r   r"   )xys     r   <lambda>z7StaticWindowMapManager.num_open_files.<locals>.<lambda>  s
    1q5 r   c              3   @   K   | ]}t          |          d k    dV  dS )r   r   N)r+   ).0rlists     r   	<genexpr>z8StaticWindowMapManager.num_open_files.<locals>.<genexpr>  s7      *a*aRUV[R\R\_`R`R`1R`R`R`R`*a*ar   r   )r   r,   r|   r   s    r   num_open_filesz%StaticWindowMapManager.num_open_files  s6    ((*a*a$+:L:L:N:N*a*a*acdeeer   c                     | j         S )z8:return: size of each window when allocating new regions)ro   r   s    r   r?   z"StaticWindowMapManager.window_size        r   c                     | j         S )z2:return: amount of bytes currently mapped in total)rr   r   s    r   mapped_memory_sizez)StaticWindowMapManager.mapped_memory_size  r   r   c                     | j         S )z5:return: maximum amount of handles we may have opened)rq   r   s    r   max_file_handlesz'StaticWindowMapManager.max_file_handles  s    %%r   c                     | j         S )z1:return: maximum amount of memory we may allocate)rp   r   s    r   max_mapped_memory_sizez-StaticWindowMapManager.max_mapped_memory_size  s    $$r   c                     t           j        dk    rdS d}| j                                        D ]8\  }}|                    |          r|D ]}|                                 |dz  }9|S )a  ONLY AVAILABLE ON WINDOWS
        On windows removing files is not allowed if anybody still has it opened.
        If this process is ourselves, and if the whole process uses this memory
        manager (as far as the parent framework is concerned) we can enforce
        closing all memory maps whose path matches the given base path to
        allow the respective operation after all.
        The respective system must NOT access the closed memory regions anymore !
        This really may only be used if you know that the items which keep
        the cursors alive will not be using it anymore. They need to be recreated !
        :return: Amount of closed handles

        **Note:** does nothing on non-windows platformswin32Nr   r   )r   platformr,   items
startswithrelease)r   	base_path
num_closedre   r   r5   s         r   force_map_handle_removal_winz3StaticWindowMapManager.force_map_handle_removal_win  s     <7""F 
;,,.. 	$ 	$KD%y)) $# $ $FNN$$$!OJJ r   N)ri   rj   rk   rl   rm   r   r   r   MapWindowClsr   r   r   r   rw   r   r   r   r   rA   r   r   r   r   r?   r   r   r   r   r"   r   r   r	   r	      s       	 	  I %LL"O L#$a#+ > > > >H' ' 'R$ $ $R3 3 3.+ + +
" " "f f f! ! !! ! !& & &% % %    r   r	   c                   N     e Zd ZdZ e            Zddej        f fd	Zd Z	 xZ
S )r
   a  Maintains a list of ranges of mapped memory regions in one or more files and allows to easily
    obtain additional regions assuring there is no overlap.
    Once a certain memory limit is reached globally, or if there cannot be more open file handles
    which result from each mmap call, the least recently used, and currently unused mapped regions
    are unloaded automatically.

    **Note:** currently not thread-safe !

    **Note:** in the current implementation, we will automatically unload windows if we either cannot
        create more memory maps (as the open file handles limit is hit) or if we have allocated more than
        a safe amount of memory already, which would possibly cause memory allocations to fail as our address
        space is full.rL   r   c                 N    t                                          |||           dS )z%Adjusts the default window size to -1N)superr   )r   r?   rx   ry   	__class__s       r   r   z SlidingWindowMapManager.__init__  s&    o7GHHHHHr   c                    d }d}t          |          }||k     rM||z   dz  }	||	         j        }
|
|k    r*||	                             |          r	||	         }n|	dz   }n|	}||k     M|| j        }|                     dd          }|                     ||          }	|                     |                                d          }| j        |z   | j        k    r|                     |           d}t          |          }|dk    r|d         j        |k    rd}n&|}t          |          D ]\  }}|j        |k    r|} n|dk    r#|r | j        
                    ||                   }nI||k    r | j        
                    ||                   }| j        
                    ||dz
                     }|	                    ||           |	                    ||           |	                                 |	                                |j        k    r|j        |	j        z
  |	_        	 | j        | j        k    rt&          |                     |                                |	j        |	j        |          }nA# t&          $ r4 |r |                     d           |                     ||||d          cY S w xY w| xj        dz  c_        | xj        |                                z  c_        |                    ||           |S )Nr      r   T)r+   rB   r@   ro   r   r=   rr   rp   r   	enumeratefrom_regionextend_left_toextend_right_toalignrC   r^   rE   rs   rq   r   r   r.   rA   insert)r   r   rD   rE   rF   r   r   lohimidr^   r?   leftright
insert_poslen_regionsir5   s                     r   rA   z&SlidingWindowMapManager._obtain_region  s?    VV2gg7q.CC&)Cf}}S6&&v.. #A1W 2gg 9+K$$Q**D##FD11C%%akkmmQ77E
  ;.1FFF((555 Ja&&KaQ47f$$!"J )
!*1  IAvy6))%&
 * Q I -99!J-HHE ,, -99!J-HHE(44QzA~5FGG t[111{333IIKKK {{}}uy(( 9sw.I%)???#O%%allnncgsxOO I I I
    ((+++**1fdE4HHHHHI !#)HHZ###s   "AI. .;J,+J,)ri   rj   rk   rl   tuplerm   r   r   r   rA   __classcell__)r   s   @r   r
   r
     sy          I#%q3; I I I I I Ia a a a a a ar   r
   )rl   utilr   r   r   r   r   	functoolsr   __all__r   r	   r
   r"   r   r   <module>r      s   r r            


      
O
O
OU( U( U( U( U( U( U( U(tf f f f f f f fTv v v v v4 v v v v vr   