a
    =_?l                     @   s   d Z ddlmZ ddlZddlZddlZddlZddlZddl	Z	dZ
ddgZG dd dejZG d	d
 d
eZG dd deeZG dd deeZdd ZdddZdddZdddZdS )a  A file interface to nodes for PyTables databases.

The FileNode module provides a file interface for using inside of
PyTables database files.  Use the new_node() function to create a brand
new file node which can be read and written as any ordinary Python
file.  Use the open_node() function to open an existing (i.e. created
with new_node()) node for read-only or read-write access.  Read acces
is always available.  Write access (enabled on new files and files
opened with mode 'a+') only allows appending data to a file node.

Currently only binary I/O is supported.

See :ref:`filenode_usersguide` for instructions on use.

.. versionchanged:: 3.0
   In version 3.0 the module as been completely rewritten to be fully
   compliant with the interfaces defined in the :mod:`io` module.

    )absolute_importNfile      c                       s   e Zd ZdZddd dd gZd0 fdd	Zedd	 Zd
d Zd1ddZ	dd Z
dd Z fddZdd Zd2ddZdd Zdd Zdd Zd3d d!Zd"d# Z fd$d%Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Z  ZS )4RawPyTablesIOz;Base class for raw binary I/O on HDF5 files using PyTables.Nc                 C   s   | dfS )Nr    lr   r   4lib/python3.9/site-packages/tables/nodes/filenode.py<lambda>9       zRawPyTablesIO.<lambda>c                 C   s   | fS Nr   r   r   r   r
   r   :   r   c                    s   t t|   | | | | |d u r4|jj}n| | | ||jj || _	|| _
d| _t|jj| _| j| j | _|jjjj| _d S )Nr   )superr   __init___check_node_check_attributes_v_filemode_check_mode_cross_check_mode_node_mode_posintattrsNODE_TYPE_VERSION_version_size_to_shape_vshapeatomdtypebasetype_vtype)selfnoder   	__class__r   r
   r   =   s    



zRawPyTablesIO.__init__c                 C   s   | j S )z
File mode.r   r$   r   r   r
   r   Q   s    zRawPyTablesIO.modec                 C   s   |    | jS )zReturn current stream position.)_checkClosedr   r)   r   r   r
   tellX   s    zRawPyTablesIO.tellr   c                 C   s   |    z| }W n ty.   tdY n0 |dkrV|dk rNtd|f || _nB|dkrrtd| j| | _n&|dkrtd| jj| | _ntd| jS )a  Change stream position.

        Change the stream position to byte offset offset. offset is
        interpreted relative to the position indicated by whence.  Values
        for whence are:

        * 0 -- start of stream (the default); offset should be zero or positive
        * 1 -- current stream position; offset may be negative
        * 2 -- end of stream; offset is usually negative

        Return the new absolute position.

        zan integer is requiredr   znegative seek position %rr   r   zinvalid whence value)	r*   	__index__AttributeError	TypeError
ValueErrorr   maxr   nrows)r$   poswhencer   r   r
   seek_   s    zRawPyTablesIO.seekc                 C   s   dS )zReturn whether object supports random access.

        If False, seek(), tell() and truncate() will raise IOError. This
        method may need to do a test seek().

        Tr   r)   r   r   r
   seekable   s    zRawPyTablesIO.seekablec                 C   s   |    | jj  dS )zReturns underlying file descriptor if one exists.

        An IOError is raised if the IO object does not use a file
        descriptor.

        N)r*   r   r   filenor)   r   r   r
   r6      s    zRawPyTablesIO.filenoc                    sH   | j s"t| jdddu r"td ztt|   W d| _nd| _0 dS )zjFlush and close the IO object.

        This method has no effect if the file is already closed.

        r   N%host PyTables file is already closed!)closedgetattrr   warningswarnr   r   closer)   r&   r   r
   r<      s    
zRawPyTablesIO.closec                 C   s   |    | j  dS )zvFlush write buffers, if applicable.

        This is not implemented for read-only and non-blocking streams.

        N)r*   r   flushr)   r   r   r
   r=      s    zRawPyTablesIO.flushc                 C   sf   |    |   |du r | j}n|dk r6td|f || jjk rJtd| || jj  | |S )a	  Truncate file to size bytes.

        Size defaults to the current IO position as reported by tell().
        Return the new size.

        Currently, this method only makes sense to grow the file node,
        since data can not be rewritten nor deleted.

        Nr   znegative truncate position %rz-truncating is only allowed for growing a file)	r*   _checkWritabler   r/   r   r1   IOError_append_zerosr4   )r$   r2   r   r   r
   truncate   s    zRawPyTablesIO.truncatec                 C   s   | j }d|v pd|v S )zeReturn whether object was opened for reading.

        If False, read() will raise IOError.

        r+r(   r$   r   r   r   r
   readable   s    zRawPyTablesIO.readablec                 C   s   | j }d|v pd|v pd|v S )zuReturn whether object was opened for writing.

        If False, write() and truncate() will raise IOError.

        warC   r(   rD   r   r   r
   writable   s    zRawPyTablesIO.writablec                 C   s   |    |   | j| jjkr"dS t|}| j}| j| }|| jjkrV| jj}|| }| j|| |d|< |  j|7  _|S )zRead up to len(b) bytes into b.

        Returns number of bytes read (0 for EOF), or None if the object
        is set not to block as has no data to read.

        r   N)r*   _checkReadabler   r   r1   lenreadZtostring)r$   bnstartstopr   r   r
   readinto   s    
zRawPyTablesIO.readintoc                 C   sx  |    |   | jjr$| jjd nd}d}t|}|}g }d}|sn|dkrZ| |}n| t||}t|}	||	8 }|	|kr||}
n |	dkrd}q@n|| d}q@|
dkr|	| |
 }|dkr|d|  }| 	| d ||7 }n|}d}nT|dkrJ|dks|dkrJ|d| d  }| 	| d d ||d 7 }n|}|| |dkr@|dkr@d}q@d
|S )	a*  Read and return a line from the stream.

        If limit is specified, at most limit bytes will be read.

        The line terminator is always ``\n`` for binary files; for text
        files, the newlines argument to open can be used to select the line
        terminator(s) recognized.

        r   rQ      
FTNr   r   )r*   rI   r   Z
chunkshaperJ   rK   minfindappendr4   join)r$   limitZ	chunksizeZlsepZlseplenZremsizepartialZfinishedZibuffZibufflenZeolindexZtrailingZobuffr   r   r
   readline	  sN    


zRawPyTablesIO.readlinec                 C   s   |    |   t|tr"tdt|}|dkr6dS | j}|| jj }|dkrZ| 	| | j
tj|| j| |d |  j|7  _|S )zWrite the given buffer to the IO stream.

        Returns the number of bytes written, which may be less than
        len(b).

        z can't write str to binary streamr   )bufferr    shape)r*   r>   
isinstancestrr.   rJ   r   r   r1   r@   rU   npZndarrayr#   r   )r$   rL   rM   r2   Zend2offr   r   r
   writeZ  s     

zRawPyTablesIO.writec                    s,   t t|   t| jdddu r(tddS )zChecks if file node is open.

        Checks whether the file node is open or has been closed. In the
        second case, a ValueError is raised. If the host PyTables has
        been closed, ValueError is also raised.

        r   Nr7   )r   r   r*   r9   r   r/   r)   r&   r   r
   r*   |  s    	zRawPyTablesIO._checkClosedc                 C   s.   t |tjstdt |jtjs*tdd S )Nz.the "node" parameter should be a tables.EArrayz,only nodes with atom "UInt8Atom" are allowed)r\   tablesEArrayr.   r   	UInt8Atomr$   r%   r   r   r
   r     s    zRawPyTablesIO._check_nodec                 C   s   t |tstd| t|}|td s:t|t|krFtd| d|v }d|v }d|v }d|v }d|v }d|v r|s~|rtd	d
}|r|rtd|| | dkrtd|s|s|stdd S )Nzinvalid mode: %rzarwb+tUrB   rF   rG   trL   Uz$can't use U and writing mode at onceTz'can't have text and binary mode at oncer   z)can't have read/write/append mode at oncez/must have exactly one of read/write/append mode)r\   r]   r.   setrJ   r/   )r$   r   ZmodesZreadingZwritingZ	appendingtextZbinaryr   r   r
   r     s(    
zRawPyTablesIO._check_modec                 C   sL   t d|v pd|v pd|v }t d|v p4d|v p4d|v }|rH|sHtdd S )NrF   rG   rC   zURawPyTablesIO can't be open in write mode if the underlying hdf5 file is not writable)boolr/   )r$   r   Z
h5filemoderH   Z
h5writabler   r   r
   r     s    	zRawPyTablesIO._cross_check_modec                 C   sN   |j }t|dd}t|dd}|tkr4td|f |tvrJtd|f dS )a  Checks file node-specific attributes.

        Checks for the presence and validity
        of the system attributes 'NODE_TYPE' and 'NODE_TYPE_VERSION'
        in the specified PyTables node (leaf).
        ValueError is raised if an attribute is missing or incorrect.

        	NODE_TYPENr   zinvalid type of node object: %sz+unsupported type version of node object: %s)r   r9   NodeTyper/   NodeTypeVersions)r$   r%   r   ZltypeZltypeverr   r   r
   r     s    
zRawPyTablesIO._check_attributesc                 C   s.   |dkrdS | j tj| j| |d dS )z_append_zeros(size) -> None.  Appends a string of zeros.

        Appends a string of 'size' zeros to the array,
        without moving the file pointer.

        r   N)r    r[   )r   rU   r^   Zzerosr#   r   )r$   sizer   r   r
   r@     s
    	zRawPyTablesIO._append_zeros)N)r   )N)rQ   )__name__
__module____qualname____doc__r   r   propertyr   r+   r4   r5   r6   r<   r=   rA   rE   rH   rP   rY   r_   r*   r   r   r   r   r@   __classcell__r   r   r&   r
   r   3   s4   

#
$
Q"r   c                   @   s6   e Zd ZdZdd Zdd Zdd ZeeeedZd	S )
FileNodeMixina+  Mixin class for FileNode objects.

    It provides access to the attribute set of the node that becomes
    available via the attrs property. You can add attributes there, but
    try to avoid attribute names in all caps or starting with '_', since
    they may clash with internal attributes.

    c                 C   s   | j jS )z+Returns the attribute set of the file node.)r   r   r)   r   r   r
   
_get_attrs  s    zFileNodeMixin._get_attrsc                 C   s   t ddS )z.set_attrs(string) -> None.  Raises ValueError.z/changing the whole attribute set is not allowedNr/   )r$   valuer   r   r
   
_set_attrs  s    zFileNodeMixin._set_attrsc                 C   s   t ddS )z(del_attrs() -> None.  Raises ValueError.z/deleting the whole attribute set is not allowedNru   r)   r   r   r
   
_del_attrs  s    zFileNodeMixin._del_attrsz:A property pointing to the attribute set of the file node.N)	rm   rn   ro   rp   rt   rw   rx   rq   r   r   r   r   r
   rs     s   
rs   c                   @   s$   e Zd ZdZdd Zedd ZdS )
ROFileNodea  Creates a new read-only file node.

    Creates a new read-only file node associated with the specified
    PyTables node, providing a standard Python file interface to it.
    The node has to have been created on a previous occasion
    using the new_node() function.

    The node used as storage is also made available via the read-only
    attribute node.  Please do not tamper with this object if it's
    avoidable, since you may break the operation of the file node object.

    The constructor is not intended to be used directly.
    Use the open_node() function in read-only mode ('r') instead.

    :Version 1:
        implements the file storage as a UInt8 uni-dimensional EArray.
    :Version 2:
        uses an UInt8 N vector EArray.

    .. versionchanged:: 3.0
       The offset attribute is no more available, please use seek/tell
       methods instead.

    .. versionchanged:: 3.0
       The line_separator property is no more available.
       The only line separator used for binary I/O is ``\n``.

    c                 C   s   t | |d |   d S )NrB   )r   r   rI   rc   r   r   r
   r   %  s    zROFileNode.__init__c                 C   s   | j S r   r   r)   r   r   r
   r%   )  s    zROFileNode.nodeN)rm   rn   ro   rp   r   rq   r%   r   r   r   r
   ry     s   ry   c                   @   s<   e Zd ZdZg dZg dZdd Zedd Zdd	 Z	d
S )
RAFileNodea*  Creates a new read-write file node.

    The first syntax opens the specified PyTables node, while the
    second one creates a new node in the specified PyTables file.
    In the second case, additional named arguments 'where' and 'name'
    must be passed to specify where the file node is to be created.
    Other named arguments such as 'title' and 'filters' may also be
    passed.  The special named argument 'expectedsize', indicating an
    estimate of the file size in bytes, may also be passed.

    Write access means reading as well as appending data is allowed.

    The node used as storage is also made available via the read-only
    attribute node.  Please do not tamper with this object if it's
    avoidable, since you may break the operation of the file node object.

    The constructor is not intended to be used directly.
    Use the new_node() or open_node() functions instead.

    :Version 1:
        implements the file storage as a UInt8 uni-dimensional EArray.
    :Version 2:
        uses an UInt8 N vector EArray.

    .. versionchanged:: 3.0
       The offset attribute is no more available, please use seek/tell
       methods instead.

    .. versionchanged:: 3.0
       The line_separator property is no more available.
       The only line separator used for binary I/O is ``\n``.

    )N)r   r   )r   )wherenametitlefiltersexpectedsizec                 K   s   |d ur|  | |jj| _n|d ur|D ]}|| jvr*tdt| q*d|v rp|d }| }|d= ||d< td | _| j	| j }|j
f t |d|}z| | W n( ty   ||d |d   Y n0 t| |d |   |   d S )	Nz"%s keyword argument is not allowedr   expectedrowsrQ   )r   r[   r|   r}   a+)r   r   r   r    _RAFileNode__allowed_init_kwargsr.   reprcopyrk   _byte_shapeZcreate_earrayr`   rb   _set_attributesRuntimeErrorremove_noder   r   rI   r>   )r$   r%   h5filekwargskwargr   r[   r   r   r
   r   [  s:    



zRAFileNode.__init__c                 C   s   | j S r   rz   r)   r   r   r
   r%     s    zRAFileNode.nodec                 C   s   |j }t|_td |_dS )z_set_attributes(node) -> None.  Adds file node-specific attributes.

        Sets the system attributes 'NODE_TYPE' and 'NODE_TYPE_VERSION'
        in the specified PyTables node (leaf).

        rQ   N)r   rj   ri   rk   r   )r$   r%   r   r   r   r
   r     s    zRAFileNode._set_attributesN)
rm   rn   ro   rp   r   r   r   rq   r%   r   r   r   r   r
   r{   .  s   #&
r{   c                 K   s   t d| fi |S )a  Creates a new file node object in the specified PyTables file object.

    Additional named arguments where and name must be passed to specify where
    the file node is to be created. Other named arguments such as title and
    filters may also be passed.

    The special named argument expectedsize, indicating an estimate of the
    file size in bytes, may also be passed. It returns the file node object.

    N)r{   )r   r   r   r   r
   new_node  s    r   rB   c                 C   s4   |dkrt | S |dkr"t| dS td|f dS )ae  Opens an existing file node.

    Returns a file node object from the existing specified PyTables
    node. If mode is not specified or it is 'r', the file can only be
    read, and the pointer is positioned at the beginning of the file. If
    mode is 'a+', the file can be read and appended, and the pointer is
    positioned at the end of the file.

    rB   r   Nzinvalid mode: %s)ry   r{   r?   )r%   r   r   r   r
   	open_node  s
    
r   F c              	   C   s  t |t jstd| t| tjjr@| jdkr@td| j	 |du rt|tj
jrft j|d }t|tr|drt j|d }n(|d}dd|dd  }|d }tjj|stdd	td
d	|}t| tjj }|rt| dn| }	z4|	j||d}
|s0|r"|	  td|	j	 W n tjyH   Y n0 t|d}| }W d   n1 st0    Y  z|	j||d W n tjy   Y n0 t|	||||d}|| t j|d |j_|  |r|	  dS )a  Save a file's contents to a filenode inside a PyTables file.

    .. versionadded:: 3.2

    Parameters
    ----------
    h5file
      The PyTables file to be written to; can be either a string
      giving the file's location or a :class:`File` object.  If a file
      with name *h5file* already exists, it will be opened in
      mode ``a``.

    filename
      Path of the file which shall be stored within the PyTables file.

    where, name
      Location of the filenode where the data shall be stored.  If
      *name* is not given, and *where* is either a :class:`Group`
      object or a string ending on ``/``, the leaf name will be set to
      the file name of *filename*.  The *name* will be modified to
      adhere to Python's natural naming convention; the original
      filename will be preserved in the filenode's *_filename*
      attribute.

    overwrite
      Whether or not a possibly existing filenode of the specified
      name shall be overwritten.

    title
       A description for this node (it sets the ``TITLE`` HDF5
       attribute on disk).

    filters
       An instance of the :class:`Filters` class that provides
       information about the desired I/O filters to be applied
       during the life of this object.

    zThe file '%s' could not be readrB   z!The file '%s' is opened read-onlyNr   /rQ   z(?![a-zA-Z0-9_])._z^(?![a-zA-Z_]).rG   r|   r}   z*Specified node already exists in file '%s'rb)r|   r}   r~   r   )osaccessR_OKr?   r\   r`   r   Filer   filenamegroupZGrouppathsplitr]   endswithrV   Z_python_id_rematchresubget_noder<   NoSuchNodeErroropenrK   r   r   r_   r   	_filename)r   r   r|   r}   	overwriter~   r   Znodepath
new_h5filefrM   fddatafnoder   r   r
   save_to_filenode  sR    )



(
r   c                 C   s  t | tjj }|r t| dn| }zt|j||d}W nf tjy   d}|j|ddD ]}	|	jj	|kr\t|	} qzq\|du r|
  td||f Y n0 tj|s|tjjrztj||jjj	}W n$ ty   tj||jj}Y n0 t|tjr*|s*|r|
  td| |r`tjtj|d s`ttj|d  ttj|d tjs|r|
  td	| | }
|
  t|d
}||
 W d   n1 s0    Y  ~
|r|
  dS )a  Read a filenode from a PyTables file and write its contents to a file.

    .. versionadded:: 3.2

    Parameters
    ----------
    h5file
      The PyTables file to be read from; can be either a string
      giving the file's location or a :class:`File` object.

    filename
      Path of the file where the contents of the filenode shall be
      written to.  If *filename* points to a directory or ends with
      ``/`` (``\`` on Windows), the filename will be set to the
      *_filename* (if present; otherwise the *name*) attribute of the
      read filenode.

    where, name
      Location of the filenode where the data shall be read from.  If
      no node *name* can be found at *where*, the first node at
      *where* whose *_filename* attribute matches *name* will be read.

    overwrite
      Whether or not a possibly existing file of the specified
      *filename* shall be overwritten.

    create_target
      Whether or not the folder hierarchy needed to accomodate the
      given target ``filename`` will be created.

    rB   r   Nra   )r|   Z	classnamez'A filenode '%s' cannot be found at '%s'zThe file '%s' already existsr   z"The file '%s' cannot be written towb)r\   r`   r   r   r   r   r   Z
walk_nodesr   r   r<   r   r   isdirr   seprV   r%   	Exceptionr}   r   r   r?   r   makedirsW_OKrK   r   r_   )r   r   r|   r}   r   Zcreate_targetr   r   r   rM   r   r   r   r   r
   read_from_filenode  sJ    ! *r   )rB   )NFr   N)NFF)rp   Z
__future__r   ior   r   r:   Znumpyr^   r`   rj   rk   	RawIOBaser   objectrs   ry   r{   r   r   r   r   r   r   r   r
   <module>   s0      3$'e
  
b  