U
    /e|                     @  sl   d dl mZ d dlZd dlZd dlZd dlmZ d dlmZm	Z	 d dl
mZmZ G dd deeef ZdS )    )annotationsN)Iterator)quoteunquote)ZictBaselockedc                      s   e Zd ZU dZded< ded< ded< ded	< d)ddd fddZdddddZedddddZddddZ	e	Z
edddddZeddddddZdddd d!Zd"dd#d$Zedddd%d&Zddd'd(Z  ZS )*Filea  Mutable Mapping interface to a directory

    Keys must be strings, values must be buffers

    Note this shouldn't be used for interprocess persistence, as keys
    are cached in memory.

    Parameters
    ----------
    directory: str
        Directory to write to. If it already exists, existing files will be imported as
        mapping elements. If it doesn't exists, it will be created.
    memmap: bool (optional)
        If True, use `mmap` for reading. Defaults to False.

    Notes
    -----
    If you call methods of this class from multiple threads, access will be fast as long
    as atomic disk access such as ``open``, ``os.fstat``, and ``os.remove`` is fast.
    This is not always the case, e.g. in case of slow network mounts or spun-down
    magnetic drives.
    Bytes read/write in the files is not protected by locks; this could cause failures
    on Windows, NFS, and in general whenever it's not OK to delete a file while there
    are file descriptors open on it.

    Examples
    --------
    >>> z = File('myfile')  # doctest: +SKIP
    >>> z['x'] = b'123'  # doctest: +SKIP
    >>> z['x']  # doctest: +SKIP
    b'123'

    Also supports writing lists of bytes objects

    >>> z['y'] = [b'123', b'4567']  # doctest: +SKIP
    >>> z['y']  # doctest: +SKIP
    b'1234567'

    Or anything that can be used with file.write, like a memoryview

    >>> z['data'] = np.ones(5).data  # doctest: +SKIP
    str	directoryboolmemmapzdict[str, str]	filenamesint_incFzstr | pathlib.Path)r
   r   c                   sz   t    t|| _|| _i | _d| _tj	| jsFtj
| jdd n0t| jD ]"}|| j| |< |  jd7  _qRd S )Nr   T)exist_ok   )super__init__r	   r
   r   r   r   ospathexistsmakedirslistdir_unsafe_key)selfr
   r   fn	__class__ -/tmp/pip-unpacked-wheel-z3s6s24u/zict/file.pyr   =   s    

zFile.__init__)keyreturnc                 C  s*   t |ddd| j  }|  jd7  _|S )a8  Escape key so that it is usable on all filesystems.

        Append to the filenames a unique suffix that changes every time this method is
        called. This prevents race conditions when another thread accesses the same
        key, e.g. ``__setitem__`` on one thread and ``__getitem__`` on another.
         )safe#r   )r   r   r   r    r   r   r   	_safe_keyK   s    zFile._safe_keyc                 C  s   |  dd } t| S )z%Undo the escaping done by _safe_key()r$   r   )splitr   )r    r   r   r   r   W   s    zFile._unsafe_key)r!   c                 C  s   d| j  dt|  dS )Nz<File: z, z
 elements>)r
   lenr   r   r   r   __str__]   s    zFile.__str__zbytearray | memoryviewc              
   C  s   t j| j| j| }| jrPt|d"}tt|	 dW  5 Q R  S Q R X ndt|dT}t 
|	 j}t|}|   ||}W 5 Q R X ||kst|W  5 Q R  S Q R X d S )Nzr+br   rb)r   r   joinr
   r   r   open
memoryviewmmapfilenofstatst_size	bytearrayunlockreadintoAssertionError)r   r    r   fhsizebufZnreadr   r   r   __getitem__b   s    	(
zFile.__getitem__zrbytes | bytearray | memoryview | list[bytes | bytearray | memoryview] | tuple[bytes | bytearray | memoryview, ...]None)r    valuer!   c              
   C  s   |  | | |}ttj| j|d>}|  * t|t	t
frP|| n
|| W 5 Q R X W 5 Q R X || jkrttj| j| n
|| j|< d S )Nwb)discardr&   r-   r   r   r,   r
   r4   
isinstancetuplelist
writelineswriter   remove)r   r    r<   r   r7   r   r   r   __setitem__y   s    


"
zFile.__setitem__objectc                 C  s
   || j kS N)r   r%   r   r   r   __contains__   s    zFile.__contains__zIterator[str]c                 C  s
   t | jS rG   )iterr   r)   r   r   r   __iter__   s    zFile.__iter__c                 C  s&   | j |}ttj| j| d S rG   )r   popr   rD   r   r,   r
   )r   r    r   r   r   r   __delitem__   s    zFile.__delitem__c                 C  s
   t | jS rG   )r(   r   r)   r   r   r   __len__   s    zFile.__len__)F)__name__
__module____qualname____doc____annotations__r   r&   staticmethodr   r*   __repr__r   r:   rE   rH   rJ   rL   rM   __classcell__r   r   r   r   r      s(   
+r   )
__future__r   r/   r   pathlibcollections.abcr   urllib.parser   r   Zzict.commonr   r   r	   bytesr   r   r   r   r   <module>   s   