o
    4¥ÊZŠƒ ã                   @   s¼  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 dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlT d dlT d dlT G dd„ deƒZG dd„ deƒZG dd„ deƒZG d	d
„ d
eƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd „ d eƒZG d!d"„ d"eƒZG d#d$„ d$eƒZ G d%d&„ d&eƒZ!G d'd(„ d(eƒZ"G d)d*„ d*eƒZ#G d+d,„ d,eƒZ$G d-d.„ d.eƒZ%G d/d0„ d0eƒZ&G d1d2„ d2eƒZ'G d3d4„ d4eƒZ(G d5d6„ d6eƒZ)G d7d8„ d8eƒZ*d9d:„ Z+d;d<„ Z,d=d>„ Z-�dqd?d@„Z.�drdAdB„Z/dCdD„ Z0dEdF„ Z1dGdH„ Z2G dIdJ„ dJƒZ3G dKdL„ dLƒZ4dMdN„ Z5dOdP„ Z6dQdR„ Z7dSdT„ Z8dUdV„ Z9dWdX„ Z:G dYdZ„ dZe;ƒZ<G d[d\„ d\e<ƒZ=G d]d^„ d^e=ƒZ>G d_d`„ d`e>ƒZ?G dadb„ dbe?ƒZ@G dcdd„ dde=ƒZAG dedf„ dfe<ƒZBG dgdh„ dhe<ƒZCe+G didj„ dje<ƒƒZDdkdl„ ZEdmdn„ ZFG dodp„ dpe<ƒZGG dqdr„ dre<ƒZHG dsdt„ dte<ƒZIe+dudv„ ƒZJe+dwdx„ ƒZKe+dydz„ ƒZLe+d{d|„ ƒZMe+d}d~„ ƒZNe+dd€„ ƒZOe+d�d‚„ ƒZPe+dƒd„„ ƒZQe+d…d†„ ƒZRe+d‡dˆ„ ƒZSe+d‰dŠ„ ƒZTe+d‹dŒ„ ƒZUe+d�dŽ„ ƒZVe+d�d�„ ƒZWe+d‘d’„ ƒZXe+d“d”„ ƒZYe+d•d–„ ƒZZe+d—d˜„ ƒZ[e+d™dš„ ƒZ\e+d›dœ„ ƒZ]e+d�dž„ ƒZ^e+dŸd „ ƒZ_e+d¡d¢„ ƒZ`e+d£d¤„ ƒZae+d¥d¦„ ƒZbe+d§d¨„ ƒZce+d©dª„ ƒZdeMZeeNZfeOZgePZhe+d«d¬„ ƒZie+d­d®„ ƒZje+d¯d°„ ƒZke+d±d²„ ƒZle+d³d´„ ƒZme+dµd¶„ ƒZneiZoelZpejqd·kZre+d¸d¹„ ƒZse+dºd»„ ƒZte+d¼d½„ ƒZue+d¾d¿„ ƒZve+dÀdÁ„ ƒZwe+dÂdÃ„ ƒZxe+G dÄdÅ„ dÅe<ƒƒZyezdÆdÆdÆdÆdÇdÇdÇdÇdÇdÈdÈdÈdÈdÈdÉ�Z{dÊdË„ Z|G dÌdÍ„ dÍe>ƒZ}dÎdÏ„ Z~dÐdÑ„ ZdÒdÓ„ Z€dÔdÕ„ Z�e+G dÖd×„ d×e<ƒƒZ‚G dØdÙ„ dÙeƒƒZ„G dÚdÛ„ dÛe…ƒZ†G dÜdÝ„ dÝe>ƒZ‡G dÞdß„ dße…ƒZˆG dàdá„ dáe>ƒZ‰G dâdã„ dãe>ƒZŠG dädå„ dåe<ƒZ‹G dædç„ dçe<ƒZŒG dèdé„ dée=ƒZ�G dêdë„ dëe=ƒZŽG dìdí„ díe=ƒZ�G dîdï„ dïe=ƒZ�G dðdñ„ dñe=ƒZ‘G dòdó„ dóe=ƒZ’G dôdõ„ dõe<ƒZ“e+G död÷„ d÷e<ƒƒZ”G dødù„ dùe=ƒZ•G dúdû„ dûe=ƒZ–G düdý„ dýe<ƒZ—e+G dþdÿ„ dÿe<ƒƒZ˜G �d �d„ �de<ƒZ™e+G �d�d„ �de<ƒƒZše+G �d�d„ �de<ƒƒZ›G �d�d„ �de>ƒZœ�d�d	„ Z�G �d
�d„ �de>ƒZžG �d�d„ �de>ƒZŸG �d�d„ �de<ƒZ G �d�d„ �de<ƒZ¡�d�d„ Z¢�d�d„ Z£G �d�d„ �de<ƒZ¤G �d�d„ �de<ƒZ¥�d�d„ Z¦G �d�d„ �de<ƒZ§�ds�d�d „Z¨G �d!�d"„ �d"e=ƒZ©G �d#�d$„ �d$e=ƒZª�d%�d&„ Z«�d'�d(„ Z¬G �d)�d*„ �d*e=ƒZ­G �d+�d,„ �d,e=ƒZ®G �d-�d.„ �d.e<ƒZ¯e+G �d/�d0„ �d0e<ƒƒZ°e+G �d1�d2„ �d2e<ƒƒZ±e+G �d3�d4„ �d4e<ƒƒZ²G �d5�d6„ �d6e=ƒZ³�d7�d8„ Z´�d9�d:„ ZµG �d;�d<„ �d<e=ƒZ¶�d=�d>„ Z·G �d?�d@„ �d@e=ƒZ¸G �dA�dB„ �dBe=ƒZ¹G �dC�dD„ �dDe=ƒZºG �dE�dF„ �dFe=ƒZ»G �dG�dH„ �dHe=ƒZ¼G �dI�dJ„ �dJe=ƒZ½G �dK�dL„ �dLe=ƒZ¾G �dM�dN„ �dNe=ƒZ¿G �dO�dP„ �dPe<ƒZÀG �dQ�dR„ �dReAƒZÁG �dS�dT„ �dTe=ƒZÂG �dU�dV„ �dVe=ƒZÃG �dW�dX„ �dXezƒZÄG �dY�dZ„ �dZe<ƒZÅG �d[�d\„ �d\eÆƒZÇG �d]�d^„ �d^e=ƒZÈG �d_�d`„ �d`e<ƒZÉG �da�db„ �dbe>ƒZÊG �dc�dd„ �ddeÊƒZËG �de�df„ �dfe@ƒZÌ�dg�dh„ ZÍ�di�dj„ ZÎ�dk�dl„ ZÏG �dm�dn„ �dne>ƒZÐG �do�dp„ �dpe>ƒZÑdS (t  é    N)Ú*c                   @   ó   e Zd ZdS )ÚConstructErrorN©Ú__name__Ú
__module__Ú__qualname__© r	   r	   ú@/var/www/html/env/lib/python3.10/site-packages/construct/core.pyr      ó    r   c                   @   r   )ÚSizeofErrorNr   r	   r	   r	   r
   r      r   r   c                   @   r   )ÚAdaptationErrorNr   r	   r	   r	   r
   r      r   r   c                   @   r   )ÚValidationErrorNr   r	   r	   r	   r
   r      r   r   c                   @   r   )ÚStreamErrorNr   r	   r	   r	   r
   r      r   r   c                   @   r   )ÚFormatFieldErrorNr   r	   r	   r	   r
   r      r   r   c                   @   r   )ÚIntegerErrorNr   r	   r	   r	   r
   r      r   r   c                   @   r   )ÚStringErrorNr   r	   r	   r	   r
   r      r   r   c                   @   r   )ÚMappingErrorNr   r	   r	   r	   r
   r      r   r   c                   @   r   )Ú
RangeErrorNr   r	   r	   r	   r
   r      r   r   c                   @   r   )ÚRepeatErrorNr   r	   r	   r	   r
   r   !   r   r   c                   @   r   )Ú
ConstErrorNr   r	   r	   r	   r
   r   #   r   r   c                   @   r   )ÚIndexFieldErrorNr   r	   r	   r	   r
   r   %   r   r   c                   @   r   )Ú
CheckErrorNr   r	   r	   r	   r
   r   '   r   r   c                   @   r   )ÚExplicitErrorNr   r	   r	   r	   r
   r   )   r   r   c                   @   r   )ÚNamedTupleErrorNr   r	   r	   r	   r
   r   +   r   r   c                   @   r   )ÚTimestampErrorNr   r	   r	   r	   r
   r   -   r   r   c                   @   r   )Ú
UnionErrorNr   r	   r	   r	   r
   r   /   r   r   c                   @   r   )ÚSelectErrorNr   r	   r	   r	   r
   r   1   r   r   c                   @   r   )ÚSwitchErrorNr   r	   r	   r	   r
   r   3   r   r   c                   @   r   )ÚStopFieldErrorNr   r	   r	   r	   r
   r   5   r   r   c                   @   r   )ÚPaddingErrorNr   r	   r	   r	   r
   r    7   r   r    c                   @   r   )ÚTerminatedErrorNr   r	   r	   r	   r
   r!   9   r   r!   c                   @   r   )ÚRawCopyErrorNr   r	   r	   r	   r
   r"   ;   r   r"   c                   @   r   )ÚRotationErrorNr   r	   r	   r	   r
   r#   =   r   r#   c                   @   r   )ÚChecksumErrorNr   r	   r	   r	   r
   r$   ?   r   r$   c                   @   r   )ÚCancelParsingNr   r	   r	   r	   r
   r%   A   r   r%   c                    s   ˆ ƒ }‡ fdd„|_ |S )Nc                      s   ˆ j S ©N)r   r	   ©Úargr	   r
   Ú<lambda>J   s    zsingleton.<locals>.<lambda>)Ú
__reduce__)r(   Úxr	   r'   r
   Ú	singletonH   s   r,   c                 C   sd   |dk r
t d| ƒ‚z|  |¡}W n ty   t d|f ƒ‚w t|ƒ|kr0t d|t|ƒf ƒ‚|S )Nr   ú%length must be non-negative, found %sz(stream.read() failed, requested %s bytesz=stream read less then specified amount, expected %d, found %d)r   ÚreadÚ	ExceptionÚlen)ÚstreamÚlengthÚdatar	   r	   r
   Ústream_readN   s   ÿr4   c                 C   ó"   z|   ¡ W S  ty   tdƒ‚w )Nz+stream.read() failed when reading until EOF)r.   r/   r   ©r1   r	   r	   r
   Ústream_read_entireZ   ó
   
ÿr7   c                 C   s¤   t |tƒstd|f ƒ‚|d u rt|ƒ}|dk rtd| ƒ‚t|ƒ|kr.td|t|ƒf ƒ‚z|  |¡}W n tyC   td|f ƒ‚w ||krPtd||f ƒ‚d S )Nú*given non-bytes value, perhaps unicode? %rr   r-   z3bytes object of wrong length, expected %d, found %dzstream.write() failed, given %rz;stream written less then specified, expected %d, written %d)Ú
isinstanceÚbytestringtyper   r0   r   Úwriter/   )r1   r3   r2   Úwrittenr	   r	   r
   Ústream_writea   s    
ÿÿr>   c                 C   s.   z|   ||¡W S  ty   td||f ƒ‚w )Nz*stream.seek() failed, offset %s, whence %s)Úseekr/   r   )r1   ÚoffsetÚwhencer	   r	   r
   Ústream_seekr   s
   ÿrB   c                 C   r5   )Nzstream.tell() failed)Útellr/   r   r6   r	   r	   r
   Ústream_telly   r8   rD   c                 C   s"   |   ¡ }|  dd¡}|  |¡ |S ©Nr   é   )rC   r?   )r1   ÚfallbackÚendr	   r	   r
   Ústream_size€   s   
rI   c                 C   s"   |   ¡ }|  d¡}|  |¡ | S ©Né   )rC   r.   r?   )r1   rG   r3   r	   r	   r
   Ústream_iseof‡   s   

rL   c                   @   s,   e Zd Zdd„ Zdd„ Zdd„ Zdd„ Zd	S )
ÚCodeGenc                 C   s"   g | _ d| _i | _i | _i | _d S ©Nr   )ÚblocksÚnextidÚparsercacheÚlinkedinstancesÚlinkedparsers©Úselfr	   r	   r
   Ú__init__�   ó
   
zCodeGen.__init__c                 C   ó   |  j d7  _ | j S rJ   ©rP   rT   r	   r	   r
   Ú
allocateId–   ó   zCodeGen.allocateIdc                    sd   dd„ |  ¡ D ƒ}|d }t|ƒt| ¡ ƒ ‰ d ‡ fdd„|D ƒ¡}|| jvr0| j |¡ d S d S )Nc                 S   s   g | ]}|  ¡ r|‘qS r	   )Ústrip©Ú.0Úsr	   r	   r
   Ú
<listcomp>›   ó    z"CodeGen.append.<locals>.<listcomp>r   Ú
c                 3   s   � | ]	}|ˆ d … V  qd S r&   r	   r]   ©Útrimr	   r
   Ú	<genexpr>ž   ó   € z!CodeGen.append.<locals>.<genexpr>)Ú
splitlinesr0   ÚlstripÚjoinrO   Úappend)rU   ÚblockÚ	firstliner	   rc   r
   rj   š   s   
ÿzCodeGen.appendc                 C   s   d  | jdg ¡S )Nrb   Ú )ri   rO   rT   r	   r	   r
   ÚtoString¢   ó   zCodeGen.toStringN)r   r   r   rV   rZ   rj   rn   r	   r	   r	   r
   rM   Ž   s
    rM   c                   @   s   e Zd Zdd„ Zdd„ ZdS )ÚKsyGenc                 C   s   i | _ i | _i | _d| _d S rN   )Ú	instancesÚenumsÚtypesrP   rT   r	   r	   r
   rV   §   s   
zKsyGen.__init__c                 C   rX   rJ   rY   rT   r	   r	   r
   rZ   ­   r[   zKsyGen.allocateIdN)r   r   r   rV   rZ   r	   r	   r	   r
   rp   ¦   s    rp   c                 C   s   dd„ |   ¡ D ƒS )Nc                 S   s$   i | ]\}}|  d d¡ d¡|“qS )Ú_ú-)ÚreplaceÚrstrip©r^   ÚkÚvr	   r	   r
   Ú
<dictcomp>³   ó   $ z!hyphenatedict.<locals>.<dictcomp>)Úitems)Údr	   r	   r
   Úhyphenatedict²   ro   r   c                 C   s   dd„ | D ƒS )Nc                 S   s   g | ]}t |ƒ‘qS r	   )r   )r^   r~   r	   r	   r
   r`   ·   ó    z!hyphenatelist.<locals>.<listcomp>r	   )Úlr	   r	   r
   Úhyphenatelist¶   ó   r‚   c                     s>   ‡ fdd„‰ g }| D ]}|j r| ˆ |ƒ¡ q
| |¡ q
|S )Nc                    s:   t | ttfƒrˆ | jƒS t | tttttfƒr| j	S t
dƒ‚)NzFEmbedding only works with: Struct Sequence FocusedSeq Union LazyStruct)r:   ÚRenamedÚEmbeddedÚsubconÚStructÚSequenceÚ
FocusedSeqÚUnionÚ
LazyStructÚsubconsr   ©Úsc©Úselectr	   r
   r�   »   s
   
zmergefields.<locals>.select)ÚflagembeddedÚextendrj   )rŒ   ÚresultrŽ   r	   r�   r
   Úmergefieldsº   s   r”   c                 C   s*   t | tƒr
t| jƒS t | tƒrtdƒ‚| S )NzEmbedded itself is not parsable)r:   r„   Úextractfieldr†   r…   r   r�   r	   r	   r
   r•   Ë   s
   


r•   c                 C   s   t | ƒr| |ƒS | S r&   )Úcallable)ÚparamÚcontextr	   r	   r
   ÚevaluateÓ   ó   r™   c                 C   s   | rdS dS )Nz# zpass; r	   )Ú	conditionr	   r	   r
   Ú	disableif×   ó   rœ   c                   @   sH  e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ ZdPd%d&„Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ ZdPd1d2„ZdQd4d5„ZdRd8d9„ZdRd:d;„ZdRd<d=„Zd>d?„ Z d@dA„ Z!dBdC„ Z"dDdE„ Z#e#Z$dFdG„ Z%dHdI„ Z&dJdK„ Z'dLdM„ Z(dNdO„ Z)d$S )SÚ	Constructa?  
    The mother of all constructs.

    This object is generally not directly instantiated, and it does not directly implement parsing and building, so it is largely only of interest to subclass implementors. There are also other abstract classes sitting on top of this one.

    The external user API:

    * `parse`
    * `parse_stream`
    * `parse_file`
    * `build`
    * `build_stream`
    * `build_file`
    * `sizeof`
    * `compile`
    * `benchmark`

    Subclass authors should not override the external methods. Instead, another API is available:

    * `_parse`
    * `_build`
    * `_sizeof`
    * `_actualsize`
    * `_emitparse`
    * `_emitbuild`
    * `__getstate__`
    * `__setstate__`

    Attributes and Inheritance:

    All constructs have a name and flags. The name is used for naming struct members and context dictionaries. Note that the name can be a string, or None by default. A single underscore "_" is a reserved name, used as up-level in nested containers. The name should be descriptive, short, and valid as a Python identifier, although these rules are not enforced. The flags specify additional behavioral information about this construct. Flags are used by enclosing constructs to determine a proper course of action. Flags are often inherited from inner subconstructs but that depends on each class.
    c                 C   s"   d | _ d| _d| _d| _d | _d S )Nrm   F)ÚnameÚdocsÚflagbuildnoner‘   ÚparsedrT   r	   r	   r
   rV      rW   zConstruct.__init__c                 C   sH   d| j j| jrd| j nd| jrdnd| jrdnd| jr df S df S )Nz<%s%s%s%s%s>ú rm   ú
 +nonbuildú
 +embeddedú +docs)Ú	__class__r   rŸ   r¡   r‘   r    rT   r	   r	   r
   Ú__repr__  s   HzConstruct.__repr__c                 C   sv   i }t | dƒr| | j¡ g }| j}|d ur(t |dƒr!| |j¡ |j}|d us|D ]}t | |ƒr8t| |ƒ||< q*|S )NÚ__dict__Ú	__slots__)ÚhasattrÚupdater©   r§   r’   rª   Ú__base__Úgetattr)rU   ÚattrsÚslotsÚcrŸ   r	   r	   r
   Ú__getstate__
  s   

ý
€zConstruct.__getstate__c                 C   s"   |  ¡ D ]
\}}t| ||ƒ qd S r&   )r}   Úsetattr)rU   r¯   rŸ   Úvaluer	   r	   r
   Ú__setstate__  s   ÿzConstruct.__setstate__c                 C   s    t  | j¡}| | |  ¡ ¡ |S r&   )ÚobjectÚ__new__r§   rµ   r²   )rU   Úself2r	   r	   r
   Ú__copy__  s   zConstruct.__copy__c                 K   s   | j t |¡fi |¤ŽS )a¢  
        Parse an in-memory buffer (often bytes object). Strings, buffers, memoryviews, and other complete buffers can be parsed with this method.

        Whenever data cannot be read, ConstructError or its derivative is raised. This method is NOT ALLOWED to raise any other exceptions although (1) user-defined lambdas can raise arbitrary exceptions which are propagated (2) external libraries like numpy can raise arbitrary exceptions which are propagated (3) some list and dict lookups can raise IndexError and KeyError which are propagated.

        Context entries are passed only as keyword parameters \*\*contextkw.

        :param \*\*contextkw: context entries, usually empty

        :returns: some value, usually based on bytes read from the stream but sometimes it is computed from nothing or from the context dictionary, sometimes its non-deterministic

        :raises ConstructError: raised for any reason
        )Úparse_streamÚioÚBytesIO)rU   r3   Ú	contextkwr	   r	   r
   Úparse"  s   zConstruct.parsec                 K   sL   t di |¤Ž}d|_d|_d|_||_z|  ||d¡W S  ty%   Y dS w )z…
        Parse a stream. Files, pipes, sockets, and other streaming sources of data are handled by this method. See parse().
        TFz	(parsing)Nr	   )Ú	ContainerÚ_parsingÚ	_buildingÚ_sizingÚ_paramsÚ_parsereportr%   )rU   r1   r½   r˜   r	   r	   r
   rº   2  s   ÿzConstruct.parse_streamc                 K   s@   t |dƒ�}| j|fi |¤ŽW  d  ƒ S 1 sw   Y  dS )z:
        Parse a closed binary file. See parse().
        ÚrbN)Úopenrº   )rU   Úfilenamer½   Úfr	   r	   r
   Ú
parse_file@  s   $ÿzConstruct.parse_filec                 C   s(   |   |||¡}| jd ur|  ||¡ |S r&   )Ú_parser¢   ©rU   r1   r˜   ÚpathÚobjr	   r	   r
   rÄ   G  s   
zConstruct._parsereportc                 C   ó   t ‚©zOverride in your subclass.©ÚNotImplementedError©rU   r1   r˜   rÌ   r	   r	   r
   rÊ   M  ó   zConstruct._parsec                 K   s$   t  ¡ }| j||fi |¤Ž | ¡ S )a«  
        Build an object in memory (a bytes object).

        Whenever data cannot be written, ConstructError or its derivative is raised. This method is NOT ALLOWED to raise any other exceptions although (1) user-defined lambdas can raise arbitrary exceptions which are propagated (2) external libraries like numpy can raise arbitrary exceptions which are propagated (3) some list and dict lookups can raise IndexError and KeyError which are propagated.

        Context entries are passed only as keyword parameters \*\*contextkw.

        :param \*\*contextkw: context entries, usually empty

        :returns: bytes

        :raises ConstructError: raised for any reason
        )r»   r¼   Úbuild_streamÚgetvalue)rU   rÍ   r½   r1   r	   r	   r
   ÚbuildQ  s   zConstruct.buildc                 K   s:   t di |¤Ž}d|_d|_d|_||_|  |||d¡ dS )zF
        Build an object directly into a stream. See build().
        FTz
(building)Nr	   )r¿   rÀ   rÁ   rÂ   rÃ   Ú_build)rU   rÍ   r1   r½   r˜   r	   r	   r
   rÔ   c  s   zConstruct.build_streamc                 K   sD   t |dƒ�}| j||fi |¤Ž W d  ƒ dS 1 sw   Y  dS )zI
        Build an object into a closed binary file. See build().
        ÚwbN)rÆ   rÔ   )rU   rÍ   rÇ   r½   rÈ   r	   r	   r
   Ú
build_filen  s   "ÿzConstruct.build_filec                 C   rÎ   rÏ   rÐ   ©rU   rÍ   r1   r˜   rÌ   r	   r	   r
   r×   u  rÓ   zConstruct._buildc                 K   s2   t di |¤Ž}d|_d|_d|_||_|  |d¡S )aP  
        Calculate the size of this object, optionally using a context.

        Some constructs have fixed size (like FormatField), some have variable-size and can determine their size given a context entry (like Bytes(this.otherfield1)), and some cannot determine their size (like VarInt).

        Whenever size cannot be determined, SizeofError is raised. This method is NOT ALLOWED to raise any other exception, even if eg. context dictionary is missing a key, or subcon propagates ConstructError-derivative exception.

        Context entries are passed only as keyword parameters \*\*contextkw.

        :param \*\*contextkw: context entries, usually empty

        :returns: integer if computable, SizeofError otherwise

        :raises SizeofError: size could not be determined in actual context, or is impossible to be determined
        FTz(sizeof)Nr	   )r¿   rÀ   rÁ   rÂ   rÃ   Ú_sizeof)rU   r½   r˜   r	   r	   r
   Úsizeofy  s   zConstruct.sizeofc                 C   rÎ   rÏ   ©r   ©rU   r˜   rÌ   r	   r	   r
   rÛ   �  rÓ   zConstruct._sizeofc                 C   s   |   ||¡S r&   ©rÛ   rÒ   r	   r	   r
   Ú_actualsize”  r�   zConstruct._actualsizeNc           	      C   sÔ   t ƒ }| d¡ | d|  |¡f ¡ | ¡ }|r3t|dƒ�}| |¡ W d  ƒ n1 s.w   Y  tt | 	¡ ¡ 
¡ ƒ ¡ }t |¡}t|ddƒ}t||jƒ |j|_|j|_|j}||_||_||_| |_|S )a™  
        Transforms a construct into another construct that does same thing (has same parsing and building semantics) but is much faster when parsing. Already compiled instances just compile into itself.

        Optionally, partial source code can be saved to a text file. This is meant only to inspect the generated code, not to import it from external scripts.

        :returns: Compiled instance
        aM  
            # generated by Construct, this source is for inspection only! do not import!

            from construct import *
            from construct.lib import *
            from io import BytesIO
            import struct
            import collections
            import itertools

            def read_bytes(io, count):
                if not count >= 0: raise StreamError
                data = io.read(count)
                if not len(data) == count: raise StreamError
                return data
            def restream(data, func):
                return func(BytesIO(data))
            def reuse(obj, func):
                return func(obj)

            linkedinstances = {}
            linkedparsers = {}

            len_ = len
            sum_ = sum
            min_ = min
            max_ = max
            abs_ = abs
        z}
            def parseall(io, this):
                return %s
            compiled = Compiled(None, None, parseall)
        ÚwtNrm   Úexec)rM   rj   Ú_compileparsern   rÆ   r<   ÚhexlifyÚhashlibÚsha1ÚencodeÚdigestÚdecodeÚimpÚ
new_moduleÚcompilerâ   r©   rR   rS   ÚcompiledÚsourceÚmoduleÚ
modulenameÚdefersubcon)	rU   rÇ   Úcoderî   rÈ   rð   rï   r±   rí   r	   r	   r
   rì   —  s,   	

üÿ
zConstruct.compilec                 C   sd   t | ƒ|jv r|jt | ƒ S | dt | ƒ| f ¡ t| ƒ}||jt | ƒ< |j|jt | ƒ< dt | ƒ S )úUsed internally.z1
            # linkedinstances[%s] is %r
        zlinkedinstances[%s])ÚidrR   rj   r•   rÊ   rS   )rU   rò   Úfieldr	   r	   r
   Ú_compileinstance×  s   
þzConstruct._compileinstancec                 C   sf   zt | ƒ|jv r|jt | ƒ W S |  |¡}||jt | ƒ< |W S  ty2   |  |¡ dt | ƒ  Y S w )ró   z$linkedparsers[%s](io, this, '(???)'))rô   rQ   Ú
_emitparserÑ   rö   )rU   rò   Úemittedr	   r	   r
   rã   å  s   

þzConstruct._compileparsec                 C   rÎ   )ró   rÐ   ©rU   rò   r	   r	   r
   Ú_compilebuildñ  rÓ   zConstruct._compilebuildc                 C   rÎ   rÏ   rÐ   rù   r	   r	   r
   r÷   õ  rÓ   zConstruct._emitparsec                 C   rÎ   rÏ   rÐ   rù   r	   r	   r
   Ú
_emitbuildù  rÓ   zConstruct._emitbuildc                    sÊ  ddl m } z¨d}d}d}ˆ ˆ¡‰|‡‡fdd„dd�}tdtdtd	| ƒƒƒ}|dkr:|‡‡fd
d„|d�| }d |¡}ˆ ˆ¡ |‡‡fdd„dd�}tdtdtd	| ƒƒƒ}|dkrl|‡‡fdd„|d�| }d |¡}ˆ ¡ ‰ ˆ  ˆ¡}ˆ|ks€J ‚|‡ ‡fdd„dd�}tdtdtd	| ƒƒƒ}|dkr¨|‡ ‡fdd„|d�| }d |¡}W n	 ty·   Y nw g d¢}	d 	|	¡ |||¡}
|rãt
|dƒ�}| |
¡ W d  ƒ |
S 1 sÞw   Y  |
S )a�  
        Measures performance of your construct (its parsing and building runtime), both for the original instance and the compiled instance. Uses timeit module, over at min 1 sample, and at max over 1 second time.

        Optionally, results are saved to a text file for later inspection. Otherwise you can print the result string to terminal.

        Also this method checks correctness, by comparing parsing/building results from both instances.

        :param sampledata: bytes, a valid blob parsable by this construct
        :param filename: optional, string, source is saved to that file

        :returns: string containing measurements
        r   )ÚtimeitÚfailedc                      ó
   ˆ  ˆ ¡S r&   ©r¾   r	   ©Ú
sampledatarU   r	   r
   r)     ó   
 z%Construct.benchmark.<locals>.<lambda>rK   )Únumberiè  g      ð?c                      rþ   r&   rÿ   r	   r   r	   r
   r)     r  z{:.10f} sec/callc                      rþ   r&   ©rÖ   r	   ©Ú	sampleobjrU   r	   r
   r)     r  c                      rþ   r&   r  r	   r  r	   r
   r)     r  c                      ó
   ˆ   ˆ¡S r&   rÿ   r	   ©rí   r  r	   r
   r)   #  r  c                      r  r&   rÿ   r	   r  r	   r
   r)   &  r  )zTimeit measurements:zparsing:           {}zparsing compiled:  {}zbuilding:          {}rm   rb   rá   N)rü   r¾   ÚminÚmaxÚintÚformatrÖ   rì   r/   ri   rÆ   r<   )rU   r  rÇ   rü   Ú	parsetimeÚ	buildtimeÚ
parsetime2ÚrunsrÍ   ÚlinesÚresultsrÈ   r	   )rí   r  r  rU   r
   Ú	benchmarký  sJ   




ÿ
ÿþzConstruct.benchmarkÚunnamed_schemac           
      C   sœ   ddl m} |ƒ }d|_t ¡ }tƒ }tt|d�|  |¡|j|j	|j
d�}| ||¡ | ¡ }|rLt|dƒ�}	|	 |¡ W d   ƒ |S 1 sGw   Y  |S )Nr   )ÚYAMLF©rô   )ÚmetaÚseqrq   rr   rs   rá   )Úruamel.yamlr  Údefault_flow_styler»   ÚStringIOrp   ÚdictÚ_compileseqrq   rr   rs   ÚdumprÕ   rÆ   r<   )
rU   Ú
schemanamerÇ   r  ÚyamlÚoutputÚgenÚmainrî   rÈ   r	   r	   r
   Ú
export_ksy:  s   $
ÿþzConstruct.export_ksyFr   c                 C   sX   |dkrt dƒ‚z	t|  ||¡ƒW S  ty+   tdddi|  |||d ¡¤Žg Y S w )Né   ú'construct does not implement KSY exportrô   r+   rK   r	   )r   r‚   Ú_emitseqrÑ   r  Ú_compilefulltype©rU   ÚksyÚbitwiseÚ	recursionr	   r	   r
   r  I  s   &ÿzConstruct._compileseqc              
   C   s`   |dkrt dƒ‚z|  ||¡W S  ty/   d| ¡  }t|  |||d ¡d�|j|< | Y S w )Nr%  r&  ztype_%srK   )r  )r   Ú_emitprimitivetyperÑ   rZ   r  r  rs   )rU   r*  r+  r,  rŸ   r	   r	   r
   Ú_compileprimitivetypeQ  s   ýzConstruct._compileprimitivetypec              
   C   sN   |dkrt dƒ‚z	t|  ||¡ƒW S  ty&   t|  |||d ¡d� Y S w )Nr%  r&  rK   )Útype)r   r   Ú_emitfulltyperÑ   r  r.  r)  r	   r	   r
   r(  [  s   ÿzConstruct._compilefulltypec                 C   rÎ   rÏ   rÐ   ©rU   r*  r+  r	   r	   r
   r'  c  rÓ   zConstruct._emitseqc                 C   rÎ   rÏ   rÐ   r1  r	   r	   r
   r-  g  rÓ   zConstruct._emitprimitivetypec                 C   rÎ   rÏ   rÐ   r1  r	   r	   r
   r0  k  rÓ   zConstruct._emitfulltypec                 C   s   t | |d�S )zc
        Used for renaming subcons, usually part of a Struct, like Struct("index" / Byte).
        )Únewname)r„   ©rU   rŸ   r	   r	   r
   Ú__rtruediv__o  s   zConstruct.__rtruediv__c                 C   ó2   t |tƒrt| |d�S t|ƒrt| |d�S tdƒ‚©zz
        Used for adding docstrings and parsed hooks to subcons, like "field" / Byte * "docstring" * processfunc.
        )Únewdocs)Ú	newparsedz1operator * can only be used with string or lambda©r:   Ústringtypesr„   r–   r   ©rU   Úotherr	   r	   r
   Ú__mul__w  ó
   
zConstruct.__mul__c                 C   r5  r6  r9  r;  r	   r	   r
   Ú__rmul__�  r>  zConstruct.__rmul__c                 C   ó8   t | tƒr| jn| g}t |tƒr|jn|g}t|| Ž S )zM
        Used for making Struct like ("index"/Byte + "prefix"/Byte).
        )r:   r‡   rŒ   ©rU   r<  ÚlhsÚrhsr	   r	   r
   Ú__add__‹  ó   zConstruct.__add__c                 C   r@  )zA
        Used for making Sequences like (Byte >> Short).
        )r:   rˆ   rŒ   rA  r	   r	   r
   Ú
__rshift__“  rE  zConstruct.__rshift__c                 C   s6   t |tƒr	tdƒ‚t |tƒst|ƒrt|| ƒS tdƒ‚)zK
        Used for making Arrays like Byte[5] and Byte[this.count].
        zNsubcon[N] syntax can only be used for Arrays, use GreedyRange(subcon) instead?z2subcon[N] syntax expects integer or context lambda)r:   Úslicer   r  r–   ÚArray)rU   Úcountr	   r	   r
   Ú__getitem__›  s
   

zConstruct.__getitem__r&   )r  N)Fr   )*r   r   r   Ú__doc__rV   r¨   r²   rµ   r¹   r¾   rº   rÉ   rÄ   rÊ   rÖ   rÔ   rÙ   r×   rÜ   rÛ   rà   rì   rö   rã   rú   r÷   rû   r  r$  r  r.  r(  r'  r-  r0  r4  Ú__rdiv__r=  r?  rD  rF  rJ  r	   r	   r	   r
   rž   Þ   sP    !
@

=





rž   c                       ó@   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Zd
d„ Z‡  Z	S )ÚSubconstructzÈ
    Abstract subconstruct (wraps an inner construct, inheriting its name and flags). Parsing and building is by default deferred to subcon, same as sizeof.

    :param subcon: Construct instance
    c                    s:   t |tƒs	tdƒ‚tt| ƒ ¡  || _|j| _|j| _d S )Nz"subcon should be a Construct field)	r:   rž   Ú	TypeErrorÚsuperrN  rV   r†   r¡   r‘   ©rU   r†   ©r§   r	   r
   rV   ¬  s   
zSubconstruct.__init__c                 C   sL   d| j j| jrd| j nd| jrdnd| jrdnd| jrdndt| jƒf S )Nz<%s%s%s%s%s %s>r£   rm   r¤   r¥   r¦   )r§   r   rŸ   r¡   r‘   r    Úreprr†   rT   r	   r	   r
   r¨   ´  s   LzSubconstruct.__repr__c                 C   s   | j  |||¡S r&   )r†   rÄ   rÒ   r	   r	   r
   rÊ   ·  ó   zSubconstruct._parsec                 C   ó   | j  ||||¡S r&   ©r†   r×   rÚ   r	   r	   r
   r×   º  ro   zSubconstruct._buildc                 C   ó   | j  ||¡S r&   ©r†   rÛ   rÞ   r	   r	   r
   rÛ   ½  rƒ   zSubconstruct._sizeof)
r   r   r   rK  rV   r¨   rÊ   r×   rÛ   Ú__classcell__r	   r	   rR  r
   rN  ¦  s    rN  c                   @   ó0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )ÚAdapterz–
    Abstract adapter class.

    Needs to implement `_decode()` for parsing and `_encode()` for building.

    :param subcon: Construct instance
    c                 C   s   | j  |||¡}|  |||¡S r&   )r†   rÄ   Ú_decoderË   r	   r	   r
   rÊ   É  ó   zAdapter._parsec                 C   s$   |   |||¡}| j ||||¡}|S r&   )Ú_encoder†   r×   )rU   rÍ   r1   r˜   rÌ   Úobj2Úbuildretr	   r	   r
   r×   Í  s   zAdapter._buildc                 C   rÎ   r&   rÐ   ©rU   rÍ   r˜   rÌ   r	   r	   r
   r\  Ò  ó   zAdapter._decodec                 C   rÎ   r&   rÐ   ra  r	   r	   r
   r^  Õ  rb  zAdapter._encodeN)r   r   r   rK  rÊ   r×   r\  r^  r	   r	   r	   r
   r[  Á  s    r[  c                   @   ó   e Zd ZdZdd„ ZdS )ÚSymmetricAdapterz‘
    Abstract adapter class.

    Needs to implement `_decode()` only, for both parsing and building.

    :param subcon: Construct instance
    c                 C   s   |   |||¡S r&   )r\  ra  r	   r	   r
   r^  á  rƒ   zSymmetricAdapter._encodeN)r   r   r   rK  r^  r	   r	   r	   r
   rd  Ù  s    rd  c                   @   ó    e Zd ZdZdd„ Zdd„ ZdS )Ú	ValidatorzÇ
    Abstract class that validates a condition on the encoded/decoded object.

    Needs to implement `_validate()` that returns a bool (or a truthy value)

    :param subcon: Construct instance
    c                 C   s    |   |||¡std|f ƒ‚|S )Nzobject failed validation: %s)Ú	_validater   ra  r	   r	   r
   r\  í  s   zValidator._decodec                 C   rÎ   r&   rÐ   ra  r	   r	   r
   rg  ò  rb  zValidator._validateN)r   r   r   rK  r\  rg  r	   r	   r	   r
   rf  å  s    rf  c                   @   ó8   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ ZdS )ÚTunnelzã
    Abstract class that allows other constructs to read part of the stream as if they were reading the entrie stream. See Prefixed for example.

    Needs to implement `_decode()` for parsing and `_encode()` for building.
    c                 C   s*   t |ƒ}|  |||¡}| jj|fi |¤ŽS r&   )r7   r\  r†   r¾   ©rU   r1   r˜   rÌ   r3   r	   r	   r
   rÊ   ü  s   zTunnel._parsec                 C   s>   t  ¡ }| j ||||¡}| ¡ }|  |||¡}t||ƒ |S r&   )r»   r¼   r†   r×   rÕ   r^  r>   ©rU   rÍ   r1   r˜   rÌ   Ústream2r`  r3   r	   r	   r
   r×     s   
zTunnel._buildc                 C   rÎ   r&   rÝ   rÞ   r	   r	   r
   rÛ   	  rb  zTunnel._sizeofc                 C   rÎ   r&   rÐ   ©rU   r3   r˜   rÌ   r	   r	   r
   r\    rb  zTunnel._decodec                 C   rÎ   r&   rÐ   rm  r	   r	   r
   r^    rb  zTunnel._encodeN)	r   r   r   rK  rÊ   r×   rÛ   r\  r^  r	   r	   r	   r
   ri  ö  s    ri  c                       sL   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Zddd„Zddd„Z	‡  Z
S )ÚCompiledró   c                    ó$   t t| ƒ ¡  || _|| _|| _d S r&   )rP  rn  rV   rî   rñ   Ú	parsefunc)rU   rî   rñ   rp  rR  r	   r
   rV     ó   
zCompiled.__init__c                 C   s   |   ||¡S r&   )rp  rÒ   r	   r	   r
   rÊ     r�   zCompiled._parsec                 C   rU  r&   )rñ   r×   rÚ   r	   r	   r
   r×     ro   zCompiled._buildc                 C   rW  r&   )rñ   rÛ   rÞ   r	   r	   r
   rÛ   "  rƒ   zCompiled._sizeofNc                 C   ó   | S r&   r	   )rU   rÇ   r	   r	   r
   rì   %  rb  zCompiled.compilec                 C   rW  r&   )rñ   r  )rU   r  rÇ   r	   r	   r
   r  (  rƒ   zCompiled.benchmarkr&   )r   r   r   rK  rV   rÊ   r×   rÛ   rì   r  rY  r	   r	   rR  r
   rn    s    
rn  c                       óH   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	‡  Z
S )ÚBytesa±  
    Field consisting of a specified number of bytes.

    Parses into a bytes (of given length). Builds into the stream directly (but checks that given object matches specified length). Can also build from an integer for convenience (although BytesInteger should be used instead). Size is the specified length.

    :param length: integer or context lambda

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises StringError: building from non-bytes value, perhaps unicode

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Bytes(4)
        >>> d.parse(b'beef')
        b'beef'
        >>> d.build(b'beef')
        b'beef'
        >>> d.build(0)
        b'\x00\x00\x00\x00'
        >>> d.sizeof()
        4

        >>> d = Struct(
        ...     "length" / Int8ub,
        ...     "data" / Bytes(this.length),
        ... )
        >>> d.parse(b"\x04beef")
        Container(length=4)(data=b'beef')
        >>> d.sizeof()
        construct.core.SizeofError: cannot calculate size, key not found in context
    c                    ó   t t| ƒ ¡  || _d S r&   )rP  rt  rV   r2   )rU   r2   rR  r	   r
   rV   R  ó   
zBytes.__init__c                 C   s$   t | jƒr
|  |¡n| j}t||ƒS r&   )r–   r2   r4   )rU   r1   r˜   rÌ   r2   r	   r	   r
   rÊ   V  s   
zBytes._parsec                 C   sB   t | jƒr
|  |¡n| j}t|tƒrt||ƒn|}t|||ƒ |S r&   )r–   r2   r:   r  Úinteger2bytesr>   ©rU   rÍ   r1   r˜   rÌ   r2   r3   r	   r	   r
   r×   Z  s   zBytes._buildc              	   C   s:   zt | jƒr|  |¡W S | jW S  ttfy   tdƒ‚w ©Nú/cannot calculate size, key not found in context)r–   r2   ÚKeyErrorÚAttributeErrorr   rÞ   r	   r	   r
   rÛ   `  s
   ÿzBytes._sizeofc                 C   ó   d| j f S )Nzread_bytes(io, %s)©r2   rù   r	   r	   r
   r÷   f  r�   zBytes._emitparsec                 C   s   t | jd�S ©N©Úsize)r  r2   r1  r	   r	   r
   r0  i  r�   zBytes._emitfulltype©r   r   r   rK  rV   rÊ   r×   rÛ   r÷   r0  rY  r	   r	   rR  r
   rt  /  s    "rt  c                   @   rZ  )ÚGreedyBytesa·  
    Field consisting of unknown number of bytes.

    Parses the stream to the end. Builds into the stream directly (without checks). Size is undefined.

    :raises StreamError: stream failed when reading until EOF
    :raises StringError: building from non-bytes value, perhaps unicode

    Example::

        >>> GreedyBytes.parse(b"asislight")
        b'asislight'
        >>> GreedyBytes.build(b"asislight")
        b'asislight'
    c                 C   ó   t |ƒS r&   )r7   rÒ   r	   r	   r
   rÊ     ó   zGreedyBytes._parsec                 C   s   |  |¡ |S r&   )r<   rÚ   r	   r	   r
   r×   ‚  s   
zGreedyBytes._buildc                 C   ó   dS )Nz	io.read()r	   rù   r	   r	   r
   r÷   †  rb  zGreedyBytes._emitparsec                 C   ó
   t dd�S )NT)Úsize_eos©r  r1  r	   r	   r
   r0  ‰  ó   
zGreedyBytes._emitfulltypeN)r   r   r   rK  rÊ   r×   r÷   r0  r	   r	   r	   r
   rƒ  m  s    rƒ  c                    sˆ   zˆ   ¡ }tˆ t|d t|d ƒ}W n ty&   tˆ tdtddd„ ƒ}Y nw ‡ fdd„}‡ fdd„}‡ fd	d
„}||_||_||_|S )aO  
    Converts the stream from bytes to bits, and passes the bitstream to underlying subcon. Bitstream is a stream that contains 8 times as many bytes, and each byte is either \\x00 or \\x01 (in documentation those bytes are called bits).

    Parsing building and size are deferred to subcon, although size gets divided by 8.

    :param subcon: Construct instance, any field that works with bits (like BitsInteger) or is bit-byte agnostic (like Struct or Flag)

    See :class:`~construct.core.Transformed` and :class:`~construct.core.Restreamed` for raisable exceptions.

    Example::

        >>> d = Bitwise(Struct(
        ...     'a' / Nibble,
        ...     'b' / Bytewise(Float32b),
        ...     'c' / Padding(4),
        ... ))
        >>> d.parse(bytes(5))
        Container(a=0)(b=0.0)(c=None)
        >>> d.sizeof()
        5
    é   rK   c                 S   s   | d S ©Nr‹  r	   ©Únr	   r	   r
   r)   ¨  ó    zBitwise.<locals>.<lambda>c                    ó   ˆ j | dd�S ©NT©r+  ©r  ©r*  r+  ©r†   r	   r
   r'  ©  rƒ   zBitwise.<locals>._emitseqc                    r�  r‘  ©r.  r”  r•  r	   r
   r-  «  rƒ   z#Bitwise.<locals>._emitprimitivetypec                    r�  r‘  ©r(  r”  r•  r	   r
   r0  ­  rƒ   zBitwise.<locals>._emitfulltype)	rÜ   ÚTransformedÚ
bytes2bitsÚ
bits2bytesr   Ú
Restreamedr'  r-  r0  ©r†   r�  Úmacror'  r-  r0  r	   r•  r
   ÚBitwise�  ó   ÿrž  c                    sˆ   zˆ   ¡ }tˆ t|d t|d ƒ}W n ty&   tˆ tdtddd„ ƒ}Y nw ‡ fdd„}‡ fdd„}‡ fd	d
„}||_||_||_|S )aª  
    Converts the bitstream back to normal byte stream. Must be used within :class:`~construct.core.Bitwise`.

    Parsing building and size are deferred to subcon, although size gets multiplied by 8.

    :param subcon: Construct instance, any field that works with bytes or is bit-byte agnostic

    See :class:`~construct.core.Transformed` and :class:`~construct.core.Restreamed` for raisable exceptions.

    Example::

        >>> d = Bitwise(Struct(
        ...     'a' / Nibble,
        ...     'b' / Bytewise(Float32b),
        ...     'c' / Padding(4),
        ... ))
        >>> d.parse(bytes(5))
        Container(a=0)(b=0.0)(c=None)
        >>> d.sizeof()
        5
    r‹  rK   c                 S   s   | d S rŒ  r	   r�  r	   r	   r
   r)   Ð  r�  zBytewise.<locals>.<lambda>c                    r�  ©NFr’  r“  r”  r•  r	   r
   r'  Ñ  rƒ   zBytewise.<locals>._emitseqc                    r�  r   r–  r”  r•  r	   r
   r-  Ó  rƒ   z$Bytewise.<locals>._emitprimitivetypec                    r�  r   r—  r”  r•  r	   r
   r0  Õ  rƒ   zBytewise.<locals>._emitfulltype)	rÜ   r˜  rš  r™  r   r›  r'  r-  r0  rœ  r	   r•  r
   ÚBytewiseµ  rŸ  r¡  c                       rs  )ÚFormatFieldae  
    Field that uses `struct` module to pack and unpack CPU-sized integers and floats. This is used to implement most Int* Float* fields, but for example cannot pack 24-bit integers, which is left to :class:`~construct.core.BytesInteger` class.

    See `struct module <https://docs.python.org/3/library/struct.html>`_ documentation for instructions on crafting format strings.

    Parses into an integer. Builds from an integer into specified byte count and endianness. Size is determined by `struct` module according to specified format string.

    :param endianity: string, character like: < > =
    :param format: string, character like: f d B H L Q b h l q

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises FormatFieldError: wrong format string, or struct.(un)pack complained about the value

    Example::

        >>> d = FormatField(">", "H") or Int16ub
        >>> d.parse(b"\x01\x00")
        256
        >>> d.build(256)
        b"\x01\x00"
        >>> d.sizeof()
        2
    c                    sh   |t dƒvrtd|ƒ‚|t dƒvrtd|ƒ‚tt| ƒ ¡  || | _t || ¡| _t 	|| ¡| _
d S )Nz=<>zendianity must be like: = < >Ú
fdBHLQbhlqz(format must be like: f d B H L Q b h l q)Úlistr   rP  r¢  rV   ÚfmtstrÚstructÚcalcsizer2   r‡   Úpacker)rU   Ú	endianityr  rR  r	   r
   rV   ù  s   


zFormatField.__init__c                 C   s<   t || jƒ}z	| j |¡d W S  ty   td| j ƒ‚w )Nr   zstruct %r error during parsing)r4   r2   r¨  Úunpackr/   r   r¥  rj  r	   r	   r
   rÊ     s   ÿzFormatField._parsec                 C   sD   z| j  |¡}W n ty   td| j|f ƒ‚w t||| jƒ |S )Nz/struct %r error during building, given value %r)r¨  Úpackr/   r   r¥  r>   r2   )rU   rÍ   r1   r˜   rÌ   r3   r	   r	   r
   r×   
  s   ÿzFormatField._buildc                 C   ó   | j S r&   r~  rÞ   r	   r	   r
   rÛ     ó   zFormatField._sizeofc                 C   s.   d|  ¡  }| d|| jf ¡ d|| jf S )Nzformatfield_%sz%s = struct.Struct(%r)z %s.unpack(read_bytes(io, %s))[0])rZ   rj   r¥  r2   ©rU   rò   Úfnamer	   r	   r
   r÷     s   zFormatField._emitparsec                 C   sª   | j \}}| ¡ }|dkp|dkotjdk}|dv r>|r,|r J ‚|r$J ‚dd| j f S d|r1dnd	| j|r:d
f S df S |dv rS|rFJ ‚d| j|rOd
f S df S d S )Nú<ú=ÚlittleÚbhlqBHLQúb%sr‹  ú%s%s%sr_   ÚuÚleÚbeÚfdzf%s%s)r¥  ÚislowerÚsysÚ	byteorderr2   )rU   r*  r+  r©  r  ÚsignedÚswappedr	   r	   r
   r-    s   
$þzFormatField._emitprimitivetype©r   r   r   rK  rV   rÊ   r×   rÛ   r÷   r-  rY  r	   r	   rR  r
   r¢  à  s    
r¢  c                       óJ   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	‡  Z
S )ÚBytesIntegeraõ  
    Field that packs arbitrarily large integers. Some Int24* fields use this class.

    Parses into an integer. Builds from an integer into specified byte count and endianness. Size is specified in ctor.

    Analog to :class:`~construct.core.BitsInteger` that operates on bits. In fact, ``BytesInteger(n)`` is equivalent to ``Bitwise(BitsInteger(8*n))`` and ``BitsInteger(n)`` is equivalent to ``Bytewise(BytesInteger(n//8)))`` .

    :param length: integer or context lambda, number of bytes in the field
    :param signed: bool, whether the value is signed (two's complement), default is False (unsigned)
    :param swapped: bool, whether to swap byte order (little endian), default is False (big endian)

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises IntegerError: lenght is negative, given a negative value when field is not signed, or not an integer

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = BytesInteger(4) or Int32ub
        >>> d.parse(b"abcd")
        1633837924
        >>> d.build(1)
        b'\x00\x00\x00\x01'
        >>> d.sizeof()
        4
    Fc                    ro  r&   )rP  rÁ  rV   r2   r½  r¾  ©rU   r2   r½  r¾  rR  r	   r
   rV   F  rq  zBytesInteger.__init__c                 C   sP   | j }t|ƒr||ƒ}|dk rtdƒ‚t||ƒ}| jr"|d d d… }t|| jƒS )Nr   úlength must be non-negativeéÿÿÿÿ)r2   r–   r   r4   r¾  Úbytes2integerr½  ©rU   r1   r˜   rÌ   r2   r3   r	   r	   r
   rÊ   L  s   
zBytesInteger._parsec                 C   sˆ   t |tƒstd|f ƒ‚|dk r| jstd|f ƒ‚| j}t|ƒr%||ƒ}|dk r-tdƒ‚t||ƒ}| jr<|d d d… }t|||ƒ |S )Núvalue %r is not an integerr   ú-value %r is negative, but field is not signedrÃ  rÄ  )	r:   Úintegertypesr   r½  r2   r–   rw  r¾  r>   rx  r	   r	   r
   r×   W  s   

zBytesInteger._buildc              	   C   ó8   z| j }t|ƒr||ƒ}|W S  ttfy   tdƒ‚w ry  ©r2   r–   r{  r|  r   ©rU   r˜   rÌ   r2   r	   r	   r
   rÛ   g  ó   ÿzBytesInteger._sizeofc                 C   ó   d| j | jrdnd| jf S )Nz'bytes2integer(read_bytes(io, %s)%s, %s)ú[::-1]rm   ©r2   r¾  r½  rù   r	   r	   r
   r÷   p  ó   zBytesInteger._emitparsec                 C   sP   |r| j rJ ‚| jrJ ‚dd| j f S d| j rdnd| j| jr$df S df S )Nr´  r‹  rµ  r_   r¶  r·  r¸  ©r½  r¾  r2   r1  r	   r	   r
   r-  s  s
   

(zBytesInteger._emitprimitivetype©FFr¿  r	   r	   rR  r
   rÁ  *  s    	rÁ  c                       rÀ  )ÚBitsIntegera›  
    Field that packs arbitrarily large (or small) integers. Some fields (Bit Nibble Octet) use this class. Must be enclosed in :class:`~construct.core.Bitwise` context.

    Parses into an integer. Builds from an integer into specified bit count and endianness. Size (in bits) is specified in ctor.

    Note that little-endianness is only defined for multiples of 8 bits.

    Analog to :class:`~construct.core.BytesInteger` that operates on bytes. In fact, ``BytesInteger(n)`` is equivalent to ``Bitwise(BitsInteger(8*n))`` and ``BitsInteger(n)`` is equivalent to ``Bytewise(BytesInteger(n//8)))`` .

    :param length: integer or context lambda, number of bits in the field
    :param signed: bool, whether the value is signed (two's complement), default is False (unsigned)
    :param swapped: bool, whether to swap byte order (little endian), default is False (big endian)

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises IntegerError: lenght is negative, given a negative value when field is not signed, or not an integer

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Bitwise(BitsInteger(8)) or Bitwise(Octet)
        >>> d.parse(b"\x10")
        16
        >>> d.build(255)
        b'\xff'
        >>> d.sizeof()
        1
    Fc                    ro  r&   )rP  rÔ  rV   r2   r½  r¾  rÂ  rR  r	   r
   rV   š  rq  zBitsInteger.__init__c                 C   sZ   | j }t|ƒr||ƒ}|dk rtdƒ‚t||ƒ}| jr'|d@ r#tdƒ‚t|ƒ}t|| jƒS )Nr   rÃ  é   ú9little-endianness is only defined for multiples of 8 bits)r2   r–   r   r4   r¾  Ú	swapbytesÚbits2integerr½  rÆ  r	   r	   r
   rÊ      s   
zBitsInteger._parsec                 C   s’   t |tƒstd|f ƒ‚|dk r| jstd|f ƒ‚| j}t|ƒr%||ƒ}|dk r-tdƒ‚t||ƒ}| jrA|d@ r=tdƒ‚t|ƒ}t	|||ƒ |S )NrÇ  r   rÈ  rÃ  rÕ  rÖ  )
r:   rÉ  r   r½  r2   r–   Úinteger2bitsr¾  r×  r>   rx  r	   r	   r
   r×   ­  s    

zBitsInteger._buildc              	   C   rÊ  ry  rË  rÌ  r	   r	   r
   rÛ   ¿  rÍ  zBitsInteger._sizeofc                 C   rÎ  )Nz&bits2integer(read_bytes(io, %s)%s, %s)rÏ  rm   rÐ  rù   r	   r	   r
   r÷   È  rÑ  zBitsInteger._emitparsec                 C   s    | j rJ ‚| jr
J ‚d| jf S ©Nr´  rÒ  r1  r	   r	   r
   r-  Ë  s   

zBitsInteger._emitprimitivetyperÓ  r¿  r	   r	   rR  r
   rÔ  |  s    	rÔ  c                   C   ó   t dƒS )z>A 1-bit integer, must be enclosed in a Bitwise (eg. BitStruct)rK   ©rÔ  r	   r	   r	   r
   ÚBitÑ  ó   rÝ  c                   C   rÛ  )z>A 4-bit integer, must be enclosed in a Bitwise (eg. BitStruct)é   rÜ  r	   r	   r	   r
   ÚNibbleÕ  rÞ  rà  c                   C   rÛ  )z>A 8-bit integer, must be enclosed in a Bitwise (eg. BitStruct)r‹  rÜ  r	   r	   r	   r
   ÚOctetÙ  rÞ  rá  c                   C   ó
   t ddƒS )z"Unsigned, big endian 8-bit integerú>ÚB©r¢  r	   r	   r	   r
   ÚInt8ubÞ  ó   
ræ  c                   C   râ  )z#Unsigned, big endian 16-bit integerrã  ÚHrå  r	   r	   r	   r
   ÚInt16ubâ  rç  ré  c                   C   râ  )z#Unsigned, big endian 32-bit integerrã  ÚLrå  r	   r	   r	   r
   ÚInt32ubæ  rç  rë  c                   C   râ  )z#Unsigned, big endian 64-bit integerrã  ÚQrå  r	   r	   r	   r
   ÚInt64ubê  rç  rí  c                   C   râ  )z Signed, big endian 8-bit integerrã  Úbrå  r	   r	   r	   r
   ÚInt8sbï  rç  rï  c                   C   râ  )z!Signed, big endian 16-bit integerrã  Úhrå  r	   r	   r	   r
   ÚInt16sbó  rç  rñ  c                   C   râ  )z!Signed, big endian 32-bit integerrã  r�   rå  r	   r	   r	   r
   ÚInt32sb÷  rç  rò  c                   C   râ  )z!Signed, big endian 64-bit integerrã  Úqrå  r	   r	   r	   r
   ÚInt64sbû  rç  rô  c                   C   râ  )z%Unsigned, little endian 8-bit integerr°  rä  rå  r	   r	   r	   r
   ÚInt8ul   rç  rõ  c                   C   râ  )z&Unsigned, little endian 16-bit integerr°  rè  rå  r	   r	   r	   r
   ÚInt16ul  rç  rö  c                   C   râ  )z&Unsigned, little endian 32-bit integerr°  rê  rå  r	   r	   r	   r
   ÚInt32ul  rç  r÷  c                   C   râ  )z&Unsigned, little endian 64-bit integerr°  rì  rå  r	   r	   r	   r
   ÚInt64ul  rç  rø  c                   C   râ  )z#Signed, little endian 8-bit integerr°  rî  rå  r	   r	   r	   r
   ÚInt8sl  rç  rù  c                   C   râ  )z$Signed, little endian 16-bit integerr°  rð  rå  r	   r	   r	   r
   ÚInt16sl  rç  rú  c                   C   râ  )z$Signed, little endian 32-bit integerr°  r�   rå  r	   r	   r	   r
   ÚInt32sl  rç  rû  c                   C   râ  )z$Signed, little endian 64-bit integerr°  ró  rå  r	   r	   r	   r
   ÚInt64sl  rç  rü  c                   C   râ  )z(Unsigned, native endianity 8-bit integerr±  rä  rå  r	   r	   r	   r
   ÚInt8un"  rç  rý  c                   C   râ  )z)Unsigned, native endianity 16-bit integerr±  rè  rå  r	   r	   r	   r
   ÚInt16un&  rç  rþ  c                   C   râ  )z)Unsigned, native endianity 32-bit integerr±  rê  rå  r	   r	   r	   r
   ÚInt32un*  rç  rÿ  c                   C   râ  )z)Unsigned, native endianity 64-bit integerr±  rì  rå  r	   r	   r	   r
   ÚInt64un.  rç  r   c                   C   râ  )z&Signed, native endianity 8-bit integerr±  rî  rå  r	   r	   r	   r
   ÚInt8sn3  rç  r  c                   C   râ  )z'Signed, native endianity 16-bit integerr±  rð  rå  r	   r	   r	   r
   ÚInt16sn7  rç  r  c                   C   râ  )z'Signed, native endianity 32-bit integerr±  r�   rå  r	   r	   r	   r
   ÚInt32sn;  rç  r  c                   C   râ  )z'Signed, native endianity 64-bit integerr±  ró  rå  r	   r	   r	   r
   ÚInt64sn?  rç  r  c                   C   râ  )z-Big endian, 32-bit IEEE floating point numberrã  rÈ   rå  r	   r	   r	   r
   ÚFloat32bI  rç  r  c                   C   râ  )z0Little endian, 32-bit IEEE floating point numberr°  rÈ   rå  r	   r	   r	   r
   ÚFloat32lM  rç  r  c                   C   râ  )z3Native endianity, 32-bit IEEE floating point numberr±  rÈ   rå  r	   r	   r	   r
   ÚFloat32nQ  rç  r  c                   C   râ  )z-Big endian, 64-bit IEEE floating point numberrã  r~   rå  r	   r	   r	   r
   ÚFloat64bV  rç  r  c                   C   râ  )z0Little endian, 64-bit IEEE floating point numberr°  r~   rå  r	   r	   r	   r
   ÚFloat64lZ  rç  r	  c                   C   râ  )z3Native endianity, 64-bit IEEE floating point numberr±  r~   rå  r	   r	   r	   r
   ÚFloat64n^  rç  r
  r²  c                   C   ó   t dddd�S )zFA 3-byte big-endian unsigned integer, as used in ancient file formats.r%  F©r½  r¾  ©rÁ  r	   r	   r	   r
   ÚInt24ubh  ó   r  c                   C   ó   t dddd�S )zIA 3-byte little-endian unsigned integer, as used in ancient file formats.r%  FTr  r  r	   r	   r	   r
   ÚInt24ull  r  r  c                   C   ó   t ddtd�S )zIA 3-byte native-endian unsigned integer, as used in ancient file formats.r%  Fr  ©rÁ  Únativer	   r	   r	   r
   ÚInt24unp  r  r  c                   C   r  )zDA 3-byte big-endian signed integer, as used in ancient file formats.r%  TFr  r  r	   r	   r	   r
   ÚInt24sbt  r  r  c                   C   r  )zGA 3-byte little-endian signed integer, as used in ancient file formats.r%  Tr  r  r	   r	   r	   r
   ÚInt24slx  r  r  c                   C   r  )zGA 3-byte native-endian signed integer, as used in ancient file formats.r%  Tr  r  r	   r	   r	   r
   ÚInt24sn|  r  r  c                   @   s(   e Zd ZdZdd„ Zdd„ Zdd„ ZdS )	ÚVarInta#  
    VarInt encoded integer. Each 7 bits of the number are encoded in one byte of the stream, where leftmost bit (MSB) is unset when byte is terminal. Scheme is defined at Google site related to `Protocol Buffers <https://developers.google.com/protocol-buffers/docs/encoding>`_.

    Can only encode non-negative numbers.

    Parses into an integer. Builds from an integer. Size is undefined.

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises IntegerError: given a negative value, or not an integer

    Example::

        >>> VarInt.build(1)
        b'\x01'
        >>> VarInt.build(2**100)
        b'\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x04'
    c                 C   sP   g }	 t t|dƒƒ}| |d@ ¡ |d@ snqd}t|ƒD ]}|d> |B }q|S )NTrK   é   é€   r   rÕ  )Úbyte2intr4   rj   Úreversed)rU   r1   r˜   rÌ   Úaccrî  Únumr	   r	   r
   rÊ   –  s   üzVarInt._parsec                 C   sp   t |tƒs	tdƒ‚|dk rtd|f ƒ‚|}|dkr.t|td|d@ B ƒdƒ |dL }|dkst|t|ƒdƒ |S )Nzvalue is not an integerr   z,varint cannot build from negative number: %rr  r  rK   rÕ  )r:   rÉ  r   r>   Úint2byte)rU   rÍ   r1   r˜   rÌ   r+   r	   r	   r
   r×   ¢  s   
þzVarInt._buildc                 C   r†  )NÚvlq_base128_ler	   r1  r	   r	   r
   r-  ®  rb  zVarInt._emitprimitivetypeN)r   r   r   rK  rÊ   r×   r-  r	   r	   r	   r
   r  ‚  s
    r  rK   rF   rß  )ÚasciiÚutf8Úutf_8Úu8Úutf16Úutf_16Úu16Ú	utf_16_beÚ	utf_16_leÚutf32Úutf_32Úu32Ú	utf_32_beÚ	utf_32_lec                 C   s4   |   dd¡ ¡ } | tvrtd| tf ƒ‚tt|  ƒS )ró   ru   rt   zencoding %r not found among %r)rv   ÚlowerÚpossiblestringencodingsr   Úbytes©Úencodingr	   r	   r
   ÚencodingunitÀ  s   r5  c                       ó8   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Z‡  ZS )
ÚStringEncodedró   c                    s&   t t| ƒ |¡ |stdƒ‚|| _d S )Nz)String* classes require explicit encoding)rP  r7  rV   r   r4  )rU   r†   r4  rR  r	   r
   rV   Ë  s   
zStringEncoded.__init__c                 C   s   |  | j¡S r&   )ré   r4  ra  r	   r	   r
   r\  Ñ  r�   zStringEncoded._decodec                 C   s*   t |tƒs	tdƒ‚|dkrdS | | j¡S )Nz/string encoding failed, expected unicode stringrm   ó    )r:   Úunicodestringtyper   rç   r4  ra  r	   r	   r
   r^  Ô  s
   
zStringEncoded._encodec                 C   ó   d| j  |¡| jf S )Nz(%s).decode(%r))r†   rã   r4  rù   r	   r	   r
   r÷   Û  ó   zStringEncoded._emitparse©	r   r   r   rK  rV   r\  r^  r÷   rY  r	   r	   rR  r
   r7  È  s    r7  c                    s4   t tˆtttˆ ƒd�ƒˆ ƒ}‡ ‡fdd„}||_|S )u+  
    Configurable, fixed-length or variable-length string field.

    When parsing, the byte string is stripped of null bytes (per encoding unit), then decoded. Length is an integer or context lambda. When building, the string is encoded and then padded to specified length. If encoded string is larger then the specified length, it fails with PaddingError. Size is same as length parameter.

    .. warning:: PaddedString and CString only support encodings explicitly listed in :class:`~construct.core.possiblestringencodings` .

    :param length: integer or context lambda, length in bytes (not unicode characters)
    :param encoding: string like: utf8 utf16 utf32 ascii

    :raises StringError: building a non-unicode string
    :raises StringError: selected encoding is not on supported list

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = PaddedString(10, "utf8")
        >>> d.build(u"Ð�Ñ„Ð¾Ð½")
        b'\xd0\x90\xd1\x84\xd0\xbe\xd0\xbd\x00\x00'
        >>> d.parse(_)
        u'Ð�Ñ„Ð¾Ð½'
    ©Úpadc                    s   t ˆdˆ d�S )NÚstrz)r�  r/  r4  r‰  r”  ©r4  r2   r	   r
   r0  ø  rƒ   z#PaddedString.<locals>._emitfulltype)r7  Ú
FixedSizedÚNullStrippedrƒ  r5  r0  )r2   r4  r�  r0  r	   r@  r
   ÚPaddedStringß  s   rC  c                    s(   t tˆtƒˆ ƒ}‡ ‡fdd„}||_|S )u   
    Length-prefixed string. The length field can be variable length (such as VarInt) or fixed length (such as Int64ub). :class:`~construct.core.VarInt` is recommended when designing new protocols. Stored length is in bytes, not characters. Size is not defined.

    :param lengthfield: Construct instance, field used to parse and build the length (like VarInt Int64ub)
    :param encoding: string like: utf8 utf16 utf32 ascii

    :raises StringError: building a non-unicode string

    Example::

        >>> d = PascalString(VarInt, "utf8")
        >>> d.build(u"Ð�Ñ„Ð¾Ð½")
        b'\x08\xd0\x90\xd1\x84\xd0\xbe\xd0\xbd'
        >>> d.parse(_)
        u'Ð�Ñ„Ð¾Ð½'
    c                    s$   t dˆ | |¡d�t dddˆ d�gS )NÚlengthfield©rô   r/  r3   Ústr)rô   r�  r/  r4  ©r  r.  r”  ©r4  rD  r	   r
   r'    s   þzPascalString.<locals>._emitseq)r7  ÚPrefixedrƒ  r'  )rD  r4  r�  r'  r	   rH  r
   ÚPascalStringþ  s   rJ  c                    s,   t tttˆ ƒd�ˆ ƒ}‡ fdd„}||_|S )u@  
    String ending in a terminating null byte (or null bytes in case of UTF16 UTF32).

    .. warning:: String and CString only support encodings explicitly listed in :class:`~construct.core.possiblestringencodings` .

    :param encoding: string like: utf8 utf16 utf32 ascii

    :raises StringError: building a non-unicode string
    :raises StringError: selected encoding is not on supported list

    Example::

        >>> d = CString("utf8")
        >>> d.build(u"Ð�Ñ„Ð¾Ð½")
        b'\xd0\x90\xd1\x84\xd0\xbe\xd0\xbd\x00'
        >>> d.parse(_)
        u'Ð�Ñ„Ð¾Ð½'
    )Útermc                    s   t dˆ d�S )Nr?  )r/  r4  r‰  r”  r3  r	   r
   r0  -  r�   zCString.<locals>._emitfulltype)r7  ÚNullTerminatedrƒ  r5  r0  ©r4  r�  r0  r	   r3  r
   ÚCString  s   rN  c                    s    t tˆ ƒ}‡ fdd„}||_|S )u  
    String that reads entire stream until EOF, and writes a given string as-is. Analog to :class:`~construct.core.GreedyBytes` but also applies unicode-to-bytes encoding.

    :param encoding: string like: utf8 utf16 utf32 ascii

    :raises StringError: building a non-unicode string
    :raises StreamError: stream failed when reading until EOF

    Example::

        >>> d = GreedyString("utf8")
        >>> d.build(u"Ð�Ñ„Ð¾Ð½")
        b'\xd0\x90\xd1\x84\xd0\xbe\xd0\xbd'
        >>> d.parse(_)
        u'Ð�Ñ„Ð¾Ð½'
    c                    s   t ddˆ d�S )NTrF  )rˆ  r/  r4  r‰  r”  r3  r	   r
   r0  E  rƒ   z#GreedyString.<locals>._emitfulltype)r7  rƒ  r0  rM  r	   r3  r
   ÚGreedyString3  s   
rO  c                   @   rh  )ÚFlagaœ  
    One byte (or one bit) field that maps to True or False. Other non-zero bytes are also considered True. Size is defined as 1.

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes

    Example::

        >>> Flag.parse(b"\x01")
        True
        >>> Flag.build(True)
        b'\x01'
    c                 C   s   t |dƒdkS )NrK   ó    )r4   rÒ   r	   r	   r
   rÊ   ]  rƒ   zFlag._parsec                 C   s   t ||rdnddƒ |S )Nó   rQ  rK   )r>   rÚ   r	   r	   r
   r×   `  s   zFlag._buildc                 C   r†  rJ   r	   rÞ   r	   r	   r
   rÛ   d  rb  zFlag._sizeofc                 C   r†  )Nz(read_bytes(io, 1) != b'\x00')r	   rù   r	   r	   r
   r÷   g  rb  zFlag._emitparsec                 C   s   t |rddd�S ddd�S )NÚb1Úu1rP  )r/  Ú_construct_renderr‰  r1  r	   r	   r
   r0  j  ó   zFlag._emitfulltypeN)	r   r   r   rK  rÊ   r×   rÛ   r÷   r0  r	   r	   r	   r
   rP  N  s    rP  c                   @   s   e Zd ZdZdS )ÚEnumIntegerró   N)r   r   r   rK  r	   r	   r	   r
   rW  n  s    rW  c                   @   s,   e Zd ZdZdd„ Zdd„ Zedd„ ƒZdS )	ÚEnumIntegerStringró   c                 C   s   d| j t | ¡f S )NzEnumIntegerString.new(%s, %s))ÚintvaluerF  r¨   rT   r	   r	   r
   r¨   v  rš   zEnumIntegerString.__repr__c                 C   r¬  r&   )rY  rT   r	   r	   r
   Ú__int__y  r­  zEnumIntegerString.__int__c                 C   s   t |ƒ}| |_|S r&   )rX  rY  )rY  ÚstringvalueÚretr	   r	   r
   Únew|  s   zEnumIntegerString.newN)r   r   r   rK  r¨   rZ  Ústaticmethodr]  r	   r	   r	   r
   rX  s  s    rX  c                       rs  )ÚEnumaã  
    Translates unicode label names to subcon values, and vice versa.

    Parses integer subcon, then uses that value to lookup mapping dictionary. Returns an integer-convertible string (if mapping found) or an integer (otherwise). Building is a reversed process. Can build from an integer flag or string label. Size is same as subcon, unless it raises SizeofError.

    There is no default parameter, because if no mapping is found, it parses into an integer without error.

    This class supports enum34 module. See examples.

    This class supports exposing member labels as attributes, as integer-convertible strings. See examples.

    :param subcon: Construct instance, subcon to map to/from
    :param \*merge: optional, list of enum.IntEnum and enum.IntFlag instances, to merge labels and values from
    :param \*\*mapping: dict, mapping string names to values

    :raises MappingError: building from string but no mapping found

    Example::

        >>> d = Enum(Byte, one=1, two=2, four=4, eight=8)
        >>> d.parse(b"\x01")
        'one'
        >>> int(d.parse(b"\x01"))
        1
        >>> d.parse(b"\xff")
        255
        >>> int(d.parse(b"\xff"))
        255

        >>> d.build(d.one or "one" or 1)
        b'\x01'
        >>> d.one
        'one'

        import enum
        class E(enum.IntEnum or enum.IntFlag):
            one = 1
            two = 2

        Enum(Byte, E) <--> Enum(Byte, one=1, two=2)
        FlagsEnum(Byte, E) <--> FlagsEnum(Byte, one=1, two=2)
    c                    sp   t t| ƒ |¡ |D ]}|D ]}|j||j< qq
dd„ | ¡ D ƒ| _dd„ | ¡ D ƒ| _dd„ | ¡ D ƒ| _d S )Nc                 S   s   i | ]\}}t  ||¡|“qS r	   ©rX  r]  rx   r	   r	   r
   r{   ´  ó    z!Enum.__init__.<locals>.<dictcomp>c                 S   s   i | ]\}}|t  ||¡“qS r	   r`  rx   r	   r	   r
   r{   µ  ra  c                 S   ó   i | ]\}}||“qS r	   r	   rx   r	   r	   r
   r{   ¶  ó    )	rP  r_  rV   r´   rŸ   r}   Ú
encmappingÚ
decmappingÚ
ksymapping)rU   r†   ÚmergeÚmappingÚenumÚ	enumentryrR  r	   r
   rV   ¯  s   ÿzEnum.__init__c                 C   s   || j v r| j| j |  S t‚r&   )rd  re  r|  r3  r	   r	   r
   Ú__getattr__¸  s   
zEnum.__getattr__c                 C   s(   z| j | W S  ty   t|ƒ Y S w r&   )re  r{  rW  ra  r	   r	   r
   r\  ½  s
   ÿzEnum._decodec                 C   s:   zt |tƒr	|W S | j| W S  ty   td|f ƒ‚w )Nz"building failed, no mapping for %r)r:   rÉ  rd  r{  r   ra  r	   r	   r
   r^  Ã  s   
ÿzEnum._encodec                 C   s4   d|  ¡  }| d|| jf ¡ d| j |¡|f S )Nú
factory_%sú%s = %rz.reuse(%s, lambda x: %s.get(x, EnumInteger(x)))©rZ   rj   re  r†   rã   r®  r	   r	   r
   r÷   Ë  ó   zEnum._emitparsec                 C   s   d|  ¡  }| j|j|< |S )Nzenum_%s)rZ   rf  rr   )rU   r*  r+  rŸ   r	   r	   r
   r-  Ð  s   zEnum._emitprimitivetype)r   r   r   rK  rV   rk  r\  r^  r÷   r-  rY  r	   r	   rR  r
   r_  ƒ  s    +	r_  c                   @   rc  )ÚBitwisableStringró   c                 C   s   t d | |¡ƒS )Nz{}|{})rp  r  r;  r	   r	   r
   Ú__or__Ü  rT  zBitwisableString.__or__N)r   r   r   rK  rq  r	   r	   r	   r
   rp  Ö  s    rp  c                       rs  )Ú	FlagsEnuma  
    Translates unicode label names to subcon integer (sub)values, and vice versa.

    Parses integer subcon, then creates a Container, where flags define each key. Builds from a container by bitwise-oring of each flag if it matches a set key. Can build from an integer flag or string label directly, as well as | concatenations thereof (see examples). Size is same as subcon, unless it raises SizeofError.

    This class supports enum34 module. See examples.

    This class supports exposing member labels as attributes, as bitwisable strings. See examples.

    :param subcon: Construct instance, must operate on integers
    :param \*merge: optional, list of enum.IntEnum and enum.IntFlag instances, to merge labels and values from
    :param \*\*flags: dict, mapping string names to integer values

    :raises MappingError: building from object not like: integer string dict
    :raises MappingError: building from string but no mapping found

    Can raise arbitrary exceptions when computing | and & and value is non-integer.

    Example::

        >>> d = FlagsEnum(Byte, one=1, two=2, four=4, eight=8)
        >>> d.parse(b"\x03")
        Container(one=True, two=True, four=False, eight=False)
        >>> d.build(dict(one=True,two=True))
        b'\x03'

        >>> d.build(d.one|d.two or "one|two" or 1|2)
        b'\x03'

        import enum
        class E(enum.IntEnum or enum.IntFlag):
            one = 1
            two = 2

        Enum(Byte, E) <--> Enum(Byte, one=1, two=2)
        FlagsEnum(Byte, E) <--> FlagsEnum(Byte, one=1, two=2)
    c                    sN   t t| ƒ |¡ |D ]}|D ]}|j||j< qq
|| _dd„ | ¡ D ƒ| _d S )Nc                 S   rb  r	   r	   rx   r	   r	   r
   r{     rc  z&FlagsEnum.__init__.<locals>.<dictcomp>)rP  rr  rV   r´   rŸ   Úflagsr}   Úreverseflags)rU   r†   rg  rs  ri  rj  rR  r	   r
   rV     s   ÿzFlagsEnum.__init__c                 C   s   || j v r	t|ƒS t‚r&   )rs  rp  r|  r3  r	   r	   r
   rk    s   
zFlagsEnum.__getattr__c                 C   s8   t ƒ }d|_| j ¡ D ]\}}||@ |k|t|ƒ< q|S ©NT)r¿   Ú
_flagsenumrs  r}   rp  )rU   rÍ   r˜   rÌ   r_  rŸ   r´   r	   r	   r
   r\    s
   zFlagsEnum._decodec                 C   s¼   zOt |tƒr	|W S t |tƒr(d}| d¡D ]}| ¡ }|r$|| j| O }q|W S t |tƒrId}| ¡ D ]\}}| d¡sE|rE|| j| O }q3|W S t	d|f ƒ‚ t
y]   t	d|f ƒ‚w )Nr   ú|rt   z#building failed, unknown object: %rz"building failed, unknown label: %r)r:   rÉ  r:  Úsplitr\   rs  r  r}   Ú
startswithr   r{  )rU   rÍ   r˜   rÌ   rs  rŸ   r´   r	   r	   r
   r^    s.   

€

€ÿzFlagsEnum._encodec                 C   s*   d| j  |¡d dd„ | j ¡ D ƒ¡f S )Nz"reuse(%s, lambda x: Container(%s))ú, c                 s   s    � | ]\}}d ||f V  qdS )z%s=bool(x & %s)Nr	   rx   r	   r	   r
   re   2  ó   € z'FlagsEnum._emitparse.<locals>.<genexpr>)r†   rã   ri   rs  r}   rù   r	   r	   r
   r÷   1  ó   *zFlagsEnum._emitparsec              	   C   sX   | j  ¡ d }g }t|ƒD ]}d|> }| j |d| ¡}| t|dt|ƒdd�¡ q|S )Nr‹  rK   z
unknown_%srS  rP  )rô   r/  ÚdocrU  )r†   rÜ   Úrangert  Úgetrj   r  Úhex)rU   r*  r+  Ú	bitstotalr  Úir´   rŸ   r	   r	   r
   r'  4  s   zFlagsEnum._emitseq)r   r   r   rK  rV   rk  r\  r^  r÷   r'  rY  r	   r	   rR  r
   rr  à  s    &rr  c                       r6  )
ÚMappingaY  
    Adapter that maps objects to other objects. Translates objects after parsing and before building. Can for example, be used to translate between enum34 objects and strings, but Enum class supports enum34 already and is recommended.

    :param subcon: Construct instance
    :param mapping: dict, for encoding (building) mapping, the reversed is used for parsing mapping

    :raises MappingError: parsing or building but no mapping found

    Example::

        >>> x = object
        >>> d = Mapping(Byte, {x:0})
        >>> d.parse(b"\x00")
        x
        >>> d.build(x)
        b'\x00'
    c                    s.   t t| ƒ |¡ dd„ | ¡ D ƒ| _|| _d S )Nc                 S   rb  r	   r	   rx   r	   r	   r
   r{   S  rc  z$Mapping.__init__.<locals>.<dictcomp>)rP  rƒ  rV   r}   re  rd  )rU   r†   rh  rR  r	   r
   rV   Q  s   
zMapping.__init__c              	   C   ó.   z| j | W S  ttfy   td|f ƒ‚w )Nz*parsing failed, no decoding mapping for %r)re  r{  rO  r   ra  r	   r	   r
   r\  V  ó
   ÿzMapping._decodec              	   C   r„  )Nz+building failed, no encoding mapping for %r)rd  r{  rO  r   ra  r	   r	   r
   r^  \  r…  zMapping._encodec                 C   s4   d|  ¡  }| d|| jf ¡ d|| j |¡f S )Nrl  rm  z%s[%s]rn  r®  r	   r	   r
   r÷   b  ro  zMapping._emitparser<  r	   r	   rR  r
   rƒ  >  s    rƒ  c                       óP   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
‡  ZS )r‡   a  
    Sequence of usually named constructs, similar to structs in C. The members are parsed and build in the order they are defined. If a member is anonymous (its name is None) then it gets parsed and the value discarded, or it gets build from nothing (from None).

    Some fields do not need to be named, since they are built without value anyway. See: Const Padding Check Error Pass Terminated Seek Tell for examples of such fields. :class:`~construct.core.Embedded` fields do not need to (and should not) be named.

    Operator + can also be used to make Structs (although not recommended).

    Parses into a Container (dict with attribute and key access) where keys match subcon names. Builds from a dict (not necessarily a Container) where each member gets a value from the dict matching the subcon name. If field has build-from-none flag, it gets build even when there is no matching entry in the dict. Size is the sum of all subcon sizes, unless any subcon raises SizeofError.

    This class does context nesting, meaning its members are given access to a new dictionary where the "_" entry points to the outer context. When parsing, each member gets parsed and subcon parse return value is inserted into context under matching key only if the member was named. When building, the matching entry gets inserted into context before subcon gets build, and if subcon build returns a new value (not None) that gets replaced in the context.

    This class supports embedding. :class:`~construct.core.Embedded` semantics dictate, that during instance creation (in ctor), each field is checked for embedded flag, and its subcon members are merged. This changes behavior of some code examples. Only few classes are supported: Struct Sequence FocusedSeq Union LazyStruct, although those can be used interchangably (a Struct can embed a Sequence, or rather its members).

    This class exposes subcons as attributes. You can refer to subcons that were inlined (and therefore do not exist as variable in the namespace) by accessing the struct attributes, under same name. Also note that compiler does not support this feature. See examples.

    This class exposes subcons in the context. You can refer to subcons that were inlined (and therefore do not exist as variable in the namespace) within other inlined fields using the context. Note that you need to use a lambda (`this` expression is not supported). Also note that compiler does not support this feature. See examples.

    This class supports stopping. If :class:`~construct.core.StopIf` field is a member, and it evaluates its lambda as positive, this class ends parsing or building as successful without processing further fields.

    :param \*subcons: Construct instances, list of members, some can be anonymous
    :param \*\*subconskw: Construct instances, list of members (requires Python 3.6)

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises KeyError: building a subcon but found no corresponding key in dictionary

    Example::

        >>> d = Struct("num"/Int8ub, "data"/Bytes(this.num))
        >>> d.parse(b"\x04DATA")
        Container(num=4)(data=b"DATA")
        >>> d.build(dict(num=4, data=b"DATA"))
        b"\x04DATA"

        >>> d = Struct(Const(b"MZ"), Padding(2), Pass, Terminated)
        >>> d.build({})
        b'MZ\x00\x00'
        >>> d.parse(_)
        Container()
        >>> d.sizeof()
        4

        >>> d = Struct(
        ...     "animal" / Enum(Byte, giraffe=1),
        ... )
        >>> d.animal.giraffe
        'giraffe'
        >>> d = Struct(
        ...     "count" / Byte,
        ...     "data" / Bytes(lambda this: this.count - this._subcons.count.sizeof()),
        ... )
        >>> d.build(dict(count=3, data=b"12"))
        b'\x0312'

        Alternative syntax (not recommended):
        >>> ("a"/Byte + "b"/Byte + "c"/Byte + "d"/Byte)

        Alternative syntax, but requires Python 3.6 or any PyPy:
        >>> Struct(a=Byte, b=Byte, c=Byte, d=Byte)
    c                    óf   t t| ƒ ¡  t|ƒtdd„ | ¡ D ƒƒ }t|Ž | _tdd„ | jD ƒƒ| _t	dd„ | jD ƒƒ| _
d S )Nc                 s   ó   � | ]	\}}|| V  qd S r&   r	   rx   r	   r	   r
   re   ª  rf   z"Struct.__init__.<locals>.<genexpr>c                 s   ó    � | ]}|j r|j |fV  qd S r&   ©rŸ   ©r^   rŽ   r	   r	   r
   re   ¬  r{  c                 s   ó   � | ]}|j V  qd S r&   ©r¡   r‹  r	   r	   r
   re   ­  ó   € )rP  r‡   rV   r¤  r}   r”   rŒ   r¿   Ú_subconsÚallr¡   ©rU   rŒ   Ú	subconskwrR  r	   r
   rV   ¨  ó
   
zStruct.__init__c                 C   ó   || j v r
| j | S t‚r&   ©r�  r|  r3  r	   r	   r
   rk  ¯  ó   

zStruct.__getattr__c                 C   sš   t ƒ }||_t ||jd |j|j|j| j|| dd ¡d�	}|j d|¡|_	| j
D ]#}z| |||¡}|jr>|||j< |||j< W q' tyJ   Y  |S w |S ©NÚ_index©	rt   rÃ   Ú_rootrÀ   rÁ   rÂ   r�  Ú_ior˜  rš  )r¿   r›  rÃ   rÀ   rÁ   rÂ   r�  r  rt   rš  rŒ   rÄ   rŸ   r   )rU   r1   r˜   rÌ   rÍ   rŽ   Úsubobjr	   r	   r
   rÊ   ´  s    ,


€þzStruct._parsec                 C   óÎ   |d u rt ƒ }t ||jd |j|j|j| j|| dd ¡d�	}|j d|¡|_| 	|¡ | j
D ]7}z*|jr;| |jd ¡}n||j }|jrH|||j< | ||||¡}|jrX|||j< W q- tyd   Y  |S w |S r—  ©r¿   rÃ   rÀ   rÁ   rÂ   r�  r  rt   rš  r¬   rŒ   r¡   rŸ   r×   r   ©rU   rÍ   r1   r˜   rÌ   rŽ   rœ  r`  r	   r	   r
   r×   Ã  s*   ,




€þzStruct._buildc                    ót   t ˆ ˆ jd ˆ jˆ jˆ j| jd ˆ  dd ¡d�	‰ ˆ j dˆ ¡ˆ _zt	‡ ‡fdd„| j
D ƒƒW S  ttfy9   tdƒ‚w )Nr˜  r™  rš  c                 3   ó   � | ]	}|  ˆ ˆ¡V  qd S r&   rß   r‹  ©r˜   rÌ   r	   r
   re   Þ  rf   z!Struct._sizeof.<locals>.<genexpr>rz  ©r¿   rÃ   rÀ   rÁ   rÂ   r�  r  rt   rš  ÚsumrŒ   r{  r|  r   rÞ   r	   r¢  r
   rÛ   Ú  ó   ,ÿzStruct._sizeofc                 C   sj   d|  ¡  }d|f }| jD ]}|d|jrd|j|jf nd| |¡f 7 }q|d7 }| |¡ d|f S )Nzparse_struct_%sae  
            def %s(io, this):
                result = Container()
                this = Container(_ = this, _params = this['_params'], _root = None, _parsing = True, _building = False, _sizing = False, _subcons = None, _io = io, _index = this.get('_index', None))
                this['_root'] = this['_'].get('_root', this)
                try:
        z&
                    %s%s
            zresult[%r] = this[%r] = rm   ú€
                    pass
                except StopFieldError:
                    pass
                return result
        ú%s(io, this))rZ   rŒ   rŸ   rã   rj   ©rU   rò   r¯  rk   rŽ   r	   r	   r
   r÷   â  s   ú
"þ

zStruct._emitparsec                    ó   ‡ ‡fdd„| j D ƒS )Nc                    ó   g | ]}|  ˆˆ ¡‘qS r	   r—  r‹  ©r+  r*  r	   r
   r`   ù  ra   z#Struct._emitseq.<locals>.<listcomp>©rŒ   r1  r	   r«  r
   r'  ø  r;  zStruct._emitseq©r   r   r   rK  rV   rk  rÊ   r×   rÛ   r÷   r'  rY  r	   r	   rR  r
   r‡   k  s    <r‡   c                       r†  )rˆ   aÿ  
    Sequence of usually un-named constructs. The members are parsed and build in the order they are defined. If a member is named, its parsed value gets inserted into the context. This allows using members that refer to previous members. :class:`~construct.core.Embedded` fields do not need to (and should not) be named.

    Operator >> can also be used to make Sequences (although not recommended).

    Parses into a ListContainer (list with pretty-printing) where values are in same order as subcons. Builds from a list (not necessarily a ListContainer) where each subcon is given the element at respective position. Size is the sum of all subcon sizes, unless any subcon raises SizeofError.

    This class does context nesting, meaning its members are given access to a new dictionary where the "_" entry points to the outer context. When parsing, each member gets parsed and subcon parse return value is inserted into context under matching key only if the member was named. When building, the matching entry gets inserted into context before subcon gets build, and if subcon build returns a new value (not None) that gets replaced in the context.

    This class supports embedding. :class:`~construct.core.Embedded` semantics dictate, that during instance creation (in ctor), each field is checked for embedded flag, and its subcon members are merged. This changes behavior of some code examples. Only few classes are supported: Struct Sequence FocusedSeq Union LazyStruct, although those can be used interchangably (a Struct can embed a Sequence, or rather its members).

    This class exposes subcons as attributes. You can refer to subcons that were inlined (and therefore do not exist as variable in the namespace) by accessing the struct attributes, under same name. Also note that compiler does not support this feature. See examples.

    This class exposes subcons in the context. You can refer to subcons that were inlined (and therefore do not exist as variable in the namespace) within other inlined fields using the context. Note that you need to use a lambda (`this` expression is not supported). Also note that compiler does not support this feature. See examples.

    This class supports stopping. If :class:`~construct.core.StopIf` field is a member, and it evaluates its lambda as positive, this class ends parsing or building as successful without processing further fields.

    :param \*subcons: Construct instances, list of members, some can be named
    :param \*\*subconskw: Construct instances, list of members (requires Python 3.6)

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises KeyError: building a subcon but found no corresponding key in dictionary

    Example::

        >>> d = Sequence(Byte, Float32b)
        >>> d.build([0, 1.23])
        b'\x00?\x9dp\xa4'
        >>> d.parse(_)
        [0, 1.2300000190734863] # a ListContainer

        >>> d = Sequence(
        ...     "animal" / Enum(Byte, giraffe=1),
        ... )
        >>> d.animal.giraffe
        'giraffe'
        >>> d = Sequence(
        ...     "count" / Byte,
        ...     "data" / Bytes(lambda this: this.count - this._subcons.count.sizeof()),
        ... )
        >>> d.build([3, b"12"])
        b'\x0312'

        Alternative syntax (not recommended):
        >>> (Byte >> "Byte >> "c"/Byte >> "d"/Byte)

        Alternative syntax, but requires Python 3.6 or any PyPy:
        >>> Sequence(a=Byte, b=Byte, c=Byte, d=Byte)
    c                    r‡  )Nc                 s   rˆ  r&   r	   rx   r	   r	   r
   re   1  rf   z$Sequence.__init__.<locals>.<genexpr>c                 s   r‰  r&   rŠ  r‹  r	   r	   r
   re   3  r{  c                 s   rŒ  r&   r�  r‹  r	   r	   r
   re   4  rŽ  )rP  rˆ   rV   r¤  r}   r”   rŒ   r¿   r�  r�  r¡   r‘  rR  r	   r
   rV   /  r“  zSequence.__init__c                 C   r”  r&   r•  r3  r	   r	   r
   rk  6  r–  zSequence.__getattr__c                 C   sœ   t ƒ }t||jd |j|j|j| j|| dd ¡d�	}|j d|¡|_	t
| jƒD ]%\}}z| |||¡}| |¡ |jr?|||j< W q& tyK   Y  |S w |S r—  )ÚListContainerr¿   rÃ   rÀ   rÁ   rÂ   r�  r  rt   rš  Ú	enumeraterŒ   rÄ   rj   rŸ   r   )rU   r1   r˜   rÌ   rÍ   r‚  rŽ   rœ  r	   r	   r
   rÊ   ;  s   ,

€þzSequence._parsec           
      C   sÔ   |d u rt dd„ | jD ƒƒ}t||jd |j|j|j| j|| dd ¡d�	}|j	 d|¡|_
t ƒ }tt| j|ƒƒD ]0\}\}}z|jrF|||j< | ||||¡}	| |	¡ |jr[|	||j< W q7 tyg   Y  |S w |S )Nc                 S   s   g | ]}d ‘qS r&   r	   r‹  r	   r	   r
   r`   K  s    z#Sequence._build.<locals>.<listcomp>r˜  r™  rš  )r®  rŒ   r¿   rÃ   rÀ   rÁ   rÂ   r�  r  rt   rš  r¯  ÚziprŸ   r×   rj   r   )
rU   rÍ   r1   r˜   rÌ   Úretlistr‚  rŽ   rœ  r`  r	   r	   r
   r×   I  s&   ,


€þzSequence._buildc                    r   )Nr˜  r™  rš  c                 3   r¡  r&   rß   r‹  r¢  r	   r
   re   `  rf   z#Sequence._sizeof.<locals>.<genexpr>rz  r£  rÞ   r	   r¢  r
   rÛ   \  r¥  zSequence._sizeofc                 C   sf   d|  ¡  }d|f }| jD ]}|d| |¡ 7 }|jr$|d|jf 7 }q|d7 }| |¡ d|f S )Nzparse_sequence_%sai  
            def %s(io, this):
                result = ListContainer()
                this = Container(_ = this, _params = this['_params'], _root = None, _parsing = True, _building = False, _sizing = False, _subcons = None, _io = io, _index = this.get('_index', None))
                this['_root'] = this['_'].get('_root', this)
                try:
        z3
                    result.append(%s)
            z;
                    this[%r] = result[-1]
                r¦  r§  )rZ   rŒ   rã   rŸ   rj   r¨  r	   r	   r
   r÷   d  s    ú
þþ€

zSequence._emitparsec                    r©  )Nc                    rª  r	   r—  r‹  r«  r	   r
   r`     ra   z%Sequence._emitseq.<locals>.<listcomp>r¬  r1  r	   r«  r
   r'  ~  r;  zSequence._emitseqr­  r	   r	   rR  r
   rˆ   ü  s    2rˆ   c                       rÀ  )rH  a˜  
    Homogenous array of elements, similar to C# generic T[].

    Parses into a ListContainer (a list). Parsing and building processes an exact amount of elements. If given list has more or less than count elements, raises RangeError. Size is defined as count multiplied by subcon size, but only if subcon is fixed size.

    Operator [] can be used to make Array instances (recommended syntax).

    :param count: integer or context lambda, strict amount of elements
    :param subcon: Construct instance, subcon to process individual elements
    :param discard: optional, bool, if set then parsing returns empty list

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises RangeError: specified count is not valid
    :raises RangeError: given object has different length than specified count

    Can propagate any exception from the lambdas, possibly non-ConstructError.

    Example::

        >>> d = Array(5, Byte) or Byte[5]
        >>> d.build(range(5))
        b'\x00\x01\x02\x03\x04'
        >>> d.parse(_)
        [0, 1, 2, 3, 4]
    Fc                    ó    t t| ƒ |¡ || _|| _d S r&   )rP  rH  rV   rI  Údiscard)rU   rI  r†   r³  rR  r	   r
   rV      ó   
zArray.__init__c                 C   sj   | j }t|ƒr||ƒ}d|kstd|f ƒ‚tƒ }t|ƒD ]}||_| j |||¡}| js2| 	|¡ q|S )Nr   úinvalid count %s)
rI  r–   r   r®  r~  r˜  r†   rÄ   r³  rj   )rU   r1   r˜   rÌ   rI  rÍ   r‚  Úer	   r	   r
   rÊ   ¥  s   
€zArray._parsec           
      C   óŠ   | j }t|ƒr||ƒ}d|kstd|f ƒ‚t|ƒ|ks&td|t|ƒf ƒ‚tƒ }t|ƒD ]\}}||_| j ||||¡}	| 	|	¡ q-|S ©Nr   rµ  zexpected %d elements, found %d©
rI  r–   r   r0   r®  r¯  r˜  r†   r×   rj   ©
rU   rÍ   r1   r˜   rÌ   rI  r±  r‚  r¶  r`  r	   r	   r
   r×   ³  s   zArray._buildc              	   C   óH   z| j }t|ƒr||ƒ}W n ttfy   tdƒ‚w || j ||¡ S ry  ©rI  r–   r{  r|  r   r†   rÛ   ©rU   r˜   rÌ   rI  r	   r	   r
   rÛ   Â  s   €ÿzArray._sizeofc                 C   r:  )NzHListContainer((this.__setitem__('_index',i),(%s))[1] for i in range(%s)))r†   rã   rI  rù   r	   r	   r
   r÷   Ë  r;  zArray._emitparsec                 C   s   t | j ||¡d| jd�S )NÚexpr)r/  ÚrepeatÚrepeat_expr)r  r†   r.  rI  r1  r	   r	   r
   r0  Î  rV  zArray._emitfulltype©Fr‚  r	   r	   rR  r
   rH  …  s    	rH  c                       óB   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Zd	d
„ Zdd„ Z‡  Z	S )ÚGreedyRangeag  
    Homogenous array of elements, similar to C# generic IEnumerable<T>, but works with unknown count of elements by parsing until end of stream.

    Parses into a ListContainer (a list). Parsing stops when an exception occured when parsing the subcon, either due to EOF or subcon format not being able to parse the data. Either way, when GreedyRange encounters either failure it seeks the stream back to a position after last successful subcon parsing. Builds from enumerable, each element as-is. Size is undefined.

    This class supports stopping. If :class:`~construct.core.StopIf` field is a member, and it evaluates its lambda as positive, this class ends parsing or building as successful without processing further fields.

    :param subcon: Construct instance, subcon to process individual elements
    :param discard: optional, bool, if set then parsing returns empty list

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises StreamError: stream is not seekable and tellable

    Can propagate any exception from the lambdas, possibly non-ConstructError.

    Example::

        >>> d = GreedyRange(Byte)
        >>> d.build(range(8))
        b'\x00\x01\x02\x03\x04\x05\x06\x07'
        >>> d.parse(_)
        [0, 1, 2, 3, 4, 5, 6, 7]
    Fc                    ó   t t| ƒ |¡ || _d S r&   )rP  rÃ  rV   r³  )rU   r†   r³  rR  r	   r
   rV   ë  ó   
zGreedyRange.__init__c                 C   sˆ   t ƒ }z!t ¡ D ]}||_t|ƒ}| j |||¡}| js!| |¡ qW |S  t	y.   Y |S  t
y5   ‚  tyC   t||ƒ Y |S w r&   )r®  Ú	itertoolsrI  r˜  rD   r†   rÄ   r³  rj   r   r   r/   rB   )rU   r1   r˜   rÌ   rÍ   r‚  rG   r¶  r	   r	   r
   rÊ   ï  s(   
€ûúüþzGreedyRange._parsec           	      C   sV   z t ƒ }t|ƒD ]\}}||_| j ||||¡}| |¡ q|W S  ty*   Y d S w r&   )r®  r¯  r˜  r†   r×   rj   r   )	rU   rÍ   r1   r˜   rÌ   r±  r‚  r¶  r`  r	   r	   r
   r×    	  s   ÿzGreedyRange._buildc                 C   rÎ   r&   rÝ   rÞ   r	   r	   r
   rÛ   	  rb  zGreedyRange._sizeofc                 C   s   t | j ||¡dd�S )NÚeos)r/  r¿  )r  r†   r.  r1  r	   r	   r
   r0  	  r;  zGreedyRange._emitfulltyperÁ  ©
r   r   r   rK  rV   rÊ   r×   rÛ   r0  rY  r	   r	   rR  r
   rÃ  Ò  s    rÃ  c                       rÀ  )ÚRepeatUntilaŽ  
    Homogenous array of elements, similar to C# generic IEnumerable<T>, that repeats until the predicate indicates it to stop. Note that the last element (that predicate indicated as True) is included in the return list.

    Parse iterates indefinately until last element passed the predicate. Build iterates indefinately over given list, until an element passed the precicate (or raises RepeatError if no element passed it). Size is undefined.

    :param predicate: lambda that takes (obj, list, context) and returns True to break or False to continue (or a truthy value)
    :param subcon: Construct instance, subcon used to parse and build each element
    :param discard: optional, bool, if set then parsing returns empty list

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises RepeatError: consumed all elements in the stream but neither passed the predicate

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = RepeatUntil(lambda x,lst,ctx: x > 7, Byte)
        >>> d.build(range(20))
        b'\x00\x01\x02\x03\x04\x05\x06\x07\x08'
        >>> d.parse(b"\x01\xff\x02")
        [1, 255]

        >>> d = RepeatUntil(lambda x,lst,ctx: lst[-2:] == [0,0], Byte)
        >>> d.parse(b"\x01\x00\x00\xff")
        [1, 0, 0]
    Fc                    r²  r&   )rP  rÉ  rV   Ú	predicater³  )rU   rÊ  r†   r³  rR  r	   r
   rV   .	  r´  zRepeatUntil.__init__c                    sl   | j ‰ tˆ ƒs‡ fdd„‰ tƒ }t ¡ D ]}||_| j |||¡}| js)| 	|¡ ˆ |||ƒr3|  S qd S )Nc                    ó   ˆ S r&   r	   ©Ú_1Ú_2Ú_3©rÊ  r	   r
   r)   6	  ó    z$RepeatUntil._parse.<locals>.<lambda>)
rÊ  r–   r®  rÆ  rI  r˜  r†   rÄ   r³  rj   )rU   r1   r˜   rÌ   rÍ   r‚  r¶  r	   rÐ  r
   rÊ   3	  s   
ÿûzRepeatUntil._parsec           
         s~   | j ‰ tˆ ƒs‡ fdd„‰ tƒ }tƒ }t|ƒD ]#\}}||_| j ||||¡}	| |	¡ | |	¡ ˆ |||ƒr: |S qtdƒ‚)Nc                    rË  r&   r	   rÌ  rÐ  r	   r
   r)   C	  rÑ  z$RepeatUntil._build.<locals>.<lambda>z3expected any item to match predicate, when building)	rÊ  r–   r®  r¯  r˜  r†   r×   rj   r   )
rU   rÍ   r1   r˜   rÌ   Úpartiallistr±  r‚  r¶  r`  r	   rÐ  r
   r×   @	  s   

üzRepeatUntil._buildc                 C   ó   t dƒ‚)Nz4cannot calculate size, amount depends on actual datarÝ   rÞ   r	   r	   r
   rÛ   Q	  r…  zRepeatUntil._sizeofc                 C   s8   d|  ¡  }d|| j |¡| jf }| |¡ d|f S )Nzparse_repeatuntil_%sa)  
            def %s(io, this):
                list_ = ListContainer()
                for i in itertools.count():
                    this['_index'] = i
                    obj_ = %s
                    list_.append(obj_)
                    if (%s):
                        return list_
        r§  )rZ   r†   rã   rÊ  rj   )rU   rò   r¯  rk   r	   r	   r
   r÷   T	  s   	÷


zRepeatUntil._emitparsec                 C   s&   t | j ||¡dt| jƒ dd¡d�S )NÚuntilÚobj_rt   )r/  r¿  Úrepeat_until)r  r†   r.  rS  rÊ  rv   r1  r	   r	   r
   r0  c	  s   &zRepeatUntil._emitfulltyperÁ  r‚  r	   r	   rR  r
   rÉ  	  s    rÉ  c                       ó    e Zd ZdZ‡ fdd„Z‡  ZS )r…   ap  
    Special wrapper that allows outer multiple-subcons construct to merge fields from another multiple-subcons construct. Embedded does not change a field, only wraps it like a candy with a flag.

    .. warning::

        Can only be used between Struct Sequence FocusedSeq Union LazyStruct, although they can be used interchangably, for example Struct can embed fields from a Sequence. There is also :class:`~construct.core.EmbeddedSwitch` macro that pseudo-embeds a Switch. Its not possible to embed IfThenElse.

    Parsing building and sizeof are deferred to subcon.

    :param subcon: Construct instance, its fields to embed inside a struct or sequence

    Example::

        >>> outer = Struct(
        ...     Embedded(Struct(
        ...         "data" / Bytes(4),
        ...     )),
        ... )
        >>> outer.parse(b"1234")
        Container(data=b'1234')
    c                    ó   t t| ƒ |¡ d| _d S ru  )rP  r…   rV   r‘   rQ  rR  r	   r
   rV   �	  rÅ  zEmbedded.__init__©r   r   r   rK  rV   rY  r	   r	   rR  r
   r…   j	  s    r…   c                       sb   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Z‡  ZS )r„   a'  
    Special wrapper that allows a Struct (or other similar class) to see a field as having a name (or a different name) or having a parsed hook. Library classes do not have names (its None). Renamed does not change a field, only wraps it like a candy with a label. Used internally by / and * operators.

    Also this wrapper is responsible for building a path info (a chain of names) that gets attached to error message when parsing, building, or sizeof fails. Fields that are not named do not appear in the path string.

    Parsing building and size are deferred to subcon.

    :param subcon: Construct instance
    :param newname: optional, string
    :param newdocs: optional, string
    :param newparsed: optional, lambda

    Example::

        >>> "number" / Int32ub
        <Renamed: number>
    Nc                    sJ   t t| ƒ |¡ |r|n|j| _|r|n|j| _|r|| _d S |j| _d S r&   )rP  r„   rV   rŸ   r    r¢   )rU   r†   r2  r7  r8  rR  r	   r
   rV   ™	  s   zRenamed.__init__c                 C   s   t | j|ƒS r&   )r®   r†   r3  r	   r	   r
   rk  Ÿ	  r�   zRenamed.__getattr__c                 C   s    |d| j f 7 }| j |||¡S ©Nz -> %s)rŸ   r†   rÄ   rÒ   r	   r	   r
   rÊ   ¢	  s   zRenamed._parsec                 C   s"   |d| j f 7 }| j ||||¡S rÚ  )rŸ   r†   r×   rÚ   r	   r	   r
   r×   ¦	  ó   zRenamed._buildc                 C   s   |d| j f 7 }| j ||¡S rÚ  )rŸ   r†   rÛ   rÞ   r	   r	   r
   rÛ   ª	  r]  zRenamed._sizeofc                 C   ó   | j  |¡S r&   ©r†   rã   rù   r	   r	   r
   r÷   ®	  r�   zRenamed._emitparsec                 C   rW  r&   ©r†   r  r1  r	   r	   r
   r'  ±	  rƒ   zRenamed._emitseqc                 C   rW  r&   ©r†   r.  r1  r	   r	   r
   r-  ´	  rƒ   zRenamed._emitprimitivetypec                 C   sF   t ƒ }| jr|j| jd� | | j ||¡¡ | jr!|j| jd� |S )Nr  )r}  )r  rŸ   r¬   r†   r(  r    )rU   r*  r+  Úrr	   r	   r
   r0  ·	  s   zRenamed._emitfulltype)NNN)r   r   r   rK  rV   rk  rÊ   r×   rÛ   r÷   r'  r-  r0  rY  r	   r	   rR  r
   r„   †	  s    r„   c                       rÀ  )ÚConsta¿  
    Field enforcing a constant. It is used for file signatures, to validate that the given pattern exists. Data in the stream must strictly match the specified value.

    Note that a variable sized subcon may still provide positive verification. Const does not consume a precomputed amount of bytes, but depends on the subcon to read the appropriate amount (eg. VarInt is acceptable). Whatever subcon parses into, gets compared against the specified value.

    Parses using subcon and return its value (after checking). Builds using subcon from nothing (or given object, if not None). Size is the same as subcon, unless it raises SizeofError.

    :param value: expected value, usually a bytes literal
    :param subcon: optional, Construct instance, subcon used to build value from, assumed to be Bytes if value parameter was a bytes literal

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises ConstError: parsed data does not match specified value, or building from wrong value
    :raises StringError: building from non-bytes value, perhaps unicode

    Example::

        >>> d = Const(b"IHDR")
        >>> d.build(None)
        b'IHDR'
        >>> d.parse(b"JPEG")
        construct.core.ConstError: expected b'IHDR' but parsed b'JPEG'

        >>> d = Const(255, Int32ul)
        >>> d.build(None)
        b'\xff\x00\x00\x00'
    Nc                    sL   |d u rt |tƒstd|f ƒ‚tt|ƒƒ}tt| ƒ |¡ || _d| _	d S )Nr9   T)
r:   r;   r   rt  r0   rP  rá  rV   r´   r¡   )rU   r´   r†   rR  r	   r
   rV   à	  s   

zConst.__init__c                 C   s0   | j  |||¡}|| jkrtd| j|f ƒ‚|S )Nz!parsing expected %r but parsed %r)r†   rÄ   r´   r   rË   r	   r	   r
   rÊ   é	  s   
zConst._parsec                 C   s4   |d | j fvrtd| j |f ƒ‚| j | j |||¡S )Nz'building expected None or %r but got %r)r´   r   r†   r×   rÚ   r	   r	   r
   r×   ï	  s   zConst._buildc                 C   rW  r&   rX  rÞ   r	   r	   r
   rÛ   ô	  rƒ   zConst._sizeofc                 C   s    |  d¡ d| j |¡| jf S )Nz�
            def parse_const(value, expected):
                if not value == expected: raise ConstError
                return value
        zparse_const(%s, %r))rj   r†   rã   r´   rù   r	   r	   r
   r÷   ÷	  s   
zConst._emitparsec                 C   s    | j  | j¡}ttt|ƒƒd�S )N)Úcontents)r†   rÖ   r´   r  r¤  Úiterateints)rU   r*  r+  r3   r	   r	   r
   r0  ÿ	  s   zConst._emitfulltyper&   r‚  r	   r	   rR  r
   rá  Ä	  s    	rá  c                       rM  )ÚComputeda„  
    Field computing a value from the context dictionary or some outer source like os.urandom or random module. Underlying byte stream is unaffected. The source can be non-deterministic.

    Parsing and Building return the value returned by the context lambda (although a constant value can also be used). Size is defined as 0 because parsing and building does not consume or produce bytes into the stream.

    :param func: context lambda or constant value

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::
        >>> d = Struct(
        ...     "width" / Byte,
        ...     "height" / Byte,
        ...     "total" / Computed(this.width * this.height),
        ... )
        >>> d.build(dict(width=4,height=5))
        b'\x04\x05'
        >>> d.parse(b"12")
        Container(width=49, height=50, total=2450)

        >>> d = Computed(7)
        >>> d.parse(b"")
        7
        >>> d = Computed(lambda ctx: 7)
        >>> d.parse(b"")
        7

        >>> import os
        >>> d = Computed(lambda ctx: os.urandom(10))
        >>> d.parse(b"")
        b'\x98\xc2\xec\x10\x07\xf5\x8e\x98\xc2\xec'
    c                    ó   t t| ƒ ¡  || _d| _d S ru  )rP  rä  rV   Úfuncr¡   ©rU   ræ  rR  r	   r
   rV   &
  ó   
zComputed.__init__c                 C   s   t | jƒr
|  |¡S | jS r&   ©r–   ræ  rÒ   r	   r	   r
   rÊ   +
  rV  zComputed._parsec                 C   s   t | jƒr
|  |¡S | jS r&   ré  rÚ   r	   r	   r
   r×   .
  rV  zComputed._buildc                 C   r†  rN   r	   rÞ   r	   r	   r
   rÛ   1
  rb  zComputed._sizeofc                 C   r}  )Nz%r)ræ  rù   r	   r	   r
   r÷   4
  r�   zComputed._emitparse©
r   r   r   rK  rV   rÊ   r×   rÛ   r÷   rY  r	   r	   rR  r
   rä  
  s    !rä  c                       r6  )
ÚIndexaˆ  
    Indexes a field inside outer :class:`~construct.core.Array` :class:`~construct.core.GreedyRange` :class:`~construct.core.RepeatUntil` context.

    Note that you can use this class, or use `this._index` expression instead, depending on how its used. See the examples.

    Parsing and building pulls _index key from the context. Size is 0 because stream is unaffected.

    :raises IndexFieldError: did not find either key in context

    Example::

        >>> d = Array(3, Index)
        >>> d.parse(b"")
        [0, 1, 2]
        >>> d = Array(3, Struct("i" / Index))
        >>> d.parse(b"")
        [Container(i=0), Container(i=1), Container(i=2)]

        >>> d = Array(3, Computed(this._index+1))
        >>> d.parse(b"")
        [1, 2, 3]
        >>> d = Array(3, Struct("i" / Computed(this._._index+1)))
        >>> d.parse(b"")
        [Container(i=1), Container(i=2), Container(i=3)]
    c                    ó   t | j| ƒ ¡  d| _d S ru  ©rP  r§   rV   r¡   rT   rR  r	   r
   rV   T
  rÅ  zIndex.__init__c                 C   s   |  dd ¡S ©Nr˜  ©r  r   rÒ   r	   r	   r
   rÊ   X
  r�   zIndex._parsec                 C   s   |  dd ¡S rî  rï  rÚ   r	   r	   r
   r×   \
  r�   zIndex._buildc                 C   r†  rN   r	   rÞ   r	   r	   r
   rÛ   `
  rb  zIndex._sizeof©	r   r   r   rK  rV   rÊ   r×   rÛ   rY  r	   r	   rR  r
   rë  8
  s    rë  c                       rs  )ÚRebuilda©  
    Field where building does not require a value, because the value gets recomputed when needed. Comes handy when building a Struct from a dict with missing keys. Useful for length and count fields when :class:`~construct.core.Prefixed` and :class:`~construct.core.PrefixedArray` cannot be used.

    Parsing defers to subcon. Building is defered to subcon, but it builds from a value provided by the context lambda (or constant). Size is the same as subcon, unless it raises SizeofError.

    Difference between Default and Rebuild, is that in first the build value is optional and in second the build value is ignored.

    :param subcon: Construct instance
    :param func: context lambda or constant value

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Struct(
        ...     "count" / Rebuild(Byte, len_(this.items)),
        ...     "items" / Byte[this.count],
        ... )
        >>> d.build(dict(items=[1,2,3]))
        b'\x03\x01\x02\x03'
    c                    ó    t t| ƒ |¡ || _d| _d S ru  )rP  rñ  rV   ræ  r¡   )rU   r†   ræ  rR  r	   r
   rV   }
  r´  zRebuild.__init__c                 C   s,   t | jƒr
|  |¡n| j}| j ||||¡S r&   )r–   ræ  r†   r×   rÚ   r	   r	   r
   r×   ‚
  s   zRebuild._buildc                 C   rÜ  r&   rÝ  rù   r	   r	   r
   r÷   †
  r�   zRebuild._emitparsec                 C   rW  r&   rÞ  r1  r	   r	   r
   r'  ‰
  rƒ   zRebuild._emitseqc                 C   rW  r&   rß  r1  r	   r	   r
   r-  Œ
  rƒ   zRebuild._emitprimitivetypec                 C   rW  r&   ©r†   r(  r1  r	   r	   r
   r0  �
  rƒ   zRebuild._emitfulltype©r   r   r   rK  rV   r×   r÷   r'  r-  r0  rY  r	   r	   rR  r
   rñ  d
  s    rñ  c                       rs  )ÚDefaulta3  
    Field where building does not require a value, because the value gets taken from default. Comes handy when building a Struct from a dict with missing keys.

    Parsing defers to subcon. Building is defered to subcon, but it builds from a default (if given object is None) or from given object. Building does not require a value, but can accept one. Size is the same as subcon, unless it raises SizeofError.

    Difference between Default and Rebuild, is that in first the build value is optional and in second the build value is ignored.

    :param subcon: Construct instance
    :param value: context lambda or constant value

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Struct(
        ...     "a" / Default(Byte, 0),
        ... )
        >>> d.build(dict(a=1))
        b'\x01'
        >>> d.build(dict())
        b'\x00'
    c                    rò  ru  )rP  rõ  rV   r´   r¡   )rU   r†   r´   rR  r	   r
   rV   ­
  r´  zDefault.__init__c                 C   s8   |d u rt | jƒr|  |¡n| jn|}| j ||||¡S r&   )r–   r´   r†   r×   rÚ   r	   r	   r
   r×   ²
  s   &zDefault._buildc                 C   rÜ  r&   rÝ  rù   r	   r	   r
   r÷   ¶
  r�   zDefault._emitparsec                 C   rW  r&   rÞ  r1  r	   r	   r
   r'  ¹
  rƒ   zDefault._emitseqc                 C   rW  r&   rß  r1  r	   r	   r
   r-  ¼
  rƒ   zDefault._emitprimitivetypec                 C   rW  r&   ró  r1  r	   r	   r
   r0  ¿
  rƒ   zDefault._emitfulltyperô  r	   r	   rR  r
   rõ  “
  s    rõ  c                       rM  )ÚChecka  
    Checks for a condition, and raises CheckError if the check fails.

    Parsing and building return nothing (but check the condition). Size is 0 because stream is unaffected.

    :param func: bool or context lambda, that gets run on parsing and building

    :raises CheckError: lambda returned false

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        Check(lambda ctx: len(ctx.payload.data) == ctx.payload_len)
        Check(len_(this.payload.data) == this.payload_len)
    c                    rå  ru  )rP  rö  rV   ræ  r¡   rç  rR  r	   r
   rV   Õ
  rè  zCheck.__init__c                 C   s*   t | jƒr
|  |¡n| j}|stdƒ‚d S )Nzcheck failed during parsing©r–   ræ  r   )rU   r1   r˜   rÌ   Úpassedr	   r	   r
   rÊ   Ú
  ó   ÿzCheck._parsec                 C   s*   t | jƒr
|  |¡n| j}|stdƒ‚d S )Nzcheck failed during buildingr÷  )rU   rÍ   r1   r˜   rÌ   rø  r	   r	   r
   r×   ß
  rù  zCheck._buildc                 C   r†  rN   r	   rÞ   r	   r	   r
   rÛ   ä
  rb  zCheck._sizeofc                 C   ó   |  d¡ d| jf S )Nzd
            def parse_check(condition):
                if not condition: raise CheckError
        zparse_check(%s))rj   ræ  rù   r	   r	   r
   r÷   ç
  s   
zCheck._emitparserê  r	   r	   rR  r
   rö  Ã
  s    rö  c                       rM  )ÚErrorag  
    Raises ExplicitError, unconditionally.

    Parsing and building always raise ExplicitError. Size is undefined.

    :raises ExplicitError: unconditionally, on parsing and building

    Example::

        >>> d = Struct("num"/Byte, Error)
        >>> d.parse(b"data...")
        construct.core.ExplicitError: Error field was activated during parsing
    c                    rì  ru  rí  rT   rR  r	   r
   rV   ÿ
  rÅ  zError.__init__c                 C   rÓ  )Nz(Error field was activated during parsing©r   rÒ   r	   r	   r
   rÊ     r…  zError._parsec                 C   rÓ  )Nz)Error field was activated during buildingrü  rÚ   r	   r	   r
   r×     r…  zError._buildc                 C   rÓ  )NzDError does not have size, because it interrupts parsing and buildingrÝ   rÞ   r	   r	   r
   rÛ   	  r…  zError._sizeofc                 C   s   |  d¡ dS )NzL
            def parse_error():
                raise ExplicitError
        zparse_error())rj   rù   r	   r	   r
   r÷     s   
zError._emitparserê  r	   r	   rR  r
   rû  ï
  s    rû  c                       r†  )r‰   a³  
    Allows constructing more elaborate "adapters" than Adapter class.

    Parse does parse all subcons in sequence, but returns only the element that was selected (discards other values). Build does build all subcons in sequence, where each gets build from nothing (except the selected subcon which is given the object). Size is the sum of all subcon sizes, unless any subcon raises SizeofError.

    This class does context nesting, meaning its members are given access to a new dictionary where the "_" entry points to the outer context. When parsing, each member gets parsed and subcon parse return value is inserted into context under matching key only if the member was named. When building, the matching entry gets inserted into context before subcon gets build, and if subcon build returns a new value (not None) that gets replaced in the context.

    This class supports embedding. :class:`~construct.core.Embedded` semantics dictate, that during instance creation (in ctor), each field is checked for embedded flag, and its subcon members are merged. This changes behavior of some code examples. Only few classes are supported: Struct Sequence FocusedSeq Union LazyStruct, although those can be used interchangably (a Struct can embed a Sequence, or rather its members).

    This class exposes subcons as attributes. You can refer to subcons that were inlined (and therefore do not exist as variable in the namespace) by accessing the struct attributes, under same name. Also note that compiler does not support this feature. See examples.

    This class exposes subcons in the context. You can refer to subcons that were inlined (and therefore do not exist as variable in the namespace) within other inlined fields using the context. Note that you need to use a lambda (`this` expression is not supported). Also note that compiler does not support this feature. See examples.

    This class is used internally to implement :class:`~construct.core.PrefixedArray`.

    :param parsebuildfrom: string name or context lambda, selects a subcon
    :param \*subcons: Construct instances, list of members, some can be named
    :param \*\*subconskw: Construct instances, list of members (requires Python 3.6)

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises UnboundLocalError: selector does not match any subcon

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Excample::

        >>> d = FocusedSeq("num", Const(b"SIG"), "num"/Byte, Terminated)
        >>> d.parse(b"SIG\xff")
        255
        >>> d.build(255)
        b'SIG\xff'

        >>> d = FocusedSeq("animal",
        ...     "animal" / Enum(Byte, giraffe=1),
        ... )
        >>> d.animal.giraffe
        'giraffe'
        >>> d = FocusedSeq("count",
        ...     "count" / Byte,
        ...     "data" / Padding(lambda this: this.count - this._subcons.count.sizeof()),
        ... )
        >>> d.build(4)
        b'\x04\x00\x00\x00'

        PrefixedArray <--> FocusedSeq("items",
            "count" / Rebuild(lengthfield, len_(this.items)),
            "items" / subcon[this.count],
        )
    c                    sV   t t| ƒ ¡  || _t|ƒtdd„ | ¡ D ƒƒ }t|Ž | _tdd„ | jD ƒƒ| _	d S )Nc                 s   rˆ  r&   r	   rx   r	   r	   r
   re   J  rf   z&FocusedSeq.__init__.<locals>.<genexpr>c                 s   r‰  r&   rŠ  r‹  r	   r	   r
   re   L  r{  )
rP  r‰   rV   Úparsebuildfromr¤  r}   r”   rŒ   r¿   r�  )rU   rý  rŒ   r’  rR  r	   r
   rV   G  s
   
zFocusedSeq.__init__c                 C   r”  r&   r•  r3  r	   r	   r
   rk  N  r–  zFocusedSeq.__getattr__c           	      C   sŒ   t ||jd |j|j|j| j|| dd ¡d�	}|j d|¡|_t	| j
|ƒ}t| jƒD ]\}}| |||¡}|jr<|||j< |j|krC|}q)|S r—  )r¿   rÃ   rÀ   rÁ   rÂ   r�  r  rt   rš  r™   rý  r¯  rŒ   rÄ   rŸ   )	rU   r1   r˜   rÌ   rý  r‚  rŽ   ÚparseretÚfinalretr	   r	   r
   rÊ   S  s   ,

€zFocusedSeq._parsec           
      C   s¤   t ||jd |j|j|j| j|| dd ¡d�	}|j d|¡|_t	| j
|ƒ}|||< t| jƒD ]"\}}| |j|kr:|nd |||¡}|jrH|||j< |j|krO|}	q-|	S r—  )r¿   rÃ   rÀ   rÁ   rÂ   r�  r  rt   rš  r™   rý  r¯  rŒ   r×   rŸ   )
rU   rÍ   r1   r˜   rÌ   rý  r‚  rŽ   r`  rÿ  r	   r	   r
   r×   _  s   ,

€zFocusedSeq._buildc                    r   )Nr˜  r™  rš  c                 3   r¡  r&   rß   r‹  r¢  r	   r
   re   p  rf   z%FocusedSeq._sizeof.<locals>.<genexpr>rz  r£  rÞ   r	   r¢  r
   rÛ   l  r¥  zFocusedSeq._sizeofc                 C   sp   d|  ¡  }d|f }| jD ]}|d| |¡f 7 }|jr%|d|jf 7 }q|d| jf 7 }| |¡ d|f S )Nzparse_focusedseq_%saG  
            def %s(io, this):
                result = []
                this = Container(_ = this, _params = this['_params'], _root = None, _parsing = True, _building = False, _sizing = False, _subcons = None, _io = io, _index = this.get('_index', None))
                this['_root'] = this['_'].get('_root', this)
        z/
                result.append(%s)
            z7
                this[%r] = result[-1]
                z)
                return this[%r]
        r§  )rZ   rŒ   rã   rŸ   rý  rj   r¨  r	   r	   r
   r÷   t  s$   û

þþ€þ

zFocusedSeq._emitparsec                    r©  )Nc                    rª  r	   r—  r‹  r«  r	   r
   r`   ‹  ra   z'FocusedSeq._emitseq.<locals>.<listcomp>r¬  r1  r	   r«  r
   r'  Š  r;  zFocusedSeq._emitseqr­  r	   r	   rR  r
   r‰     s    2r‰   c                   @   re  )ÚPickledaÉ  
    Preserves arbitrary Python objects.

    Parses using `pickle.load() <https://docs.python.org/3/library/pickle.html#pickle.load>`_ and builds using `pickle.dump() <https://docs.python.org/3/library/pickle.html#pickle.dump>`_ functions, using default Pickle binary protocol. Size is undefined.

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes

    Can propagate pickle.load() and pickle.dump() exceptions.

    Example::

        >>> x = [1, 2.3, {}]
        >>> Pickled.build(x)
        b'\x80\x03]q\x00(K\x01G@\x02ffffff}q\x01e.'
        >>> Pickled.parse(_)
        [1, 2.3, {}]
    c                 C   s
   t  |¡S r&   )ÚpickleÚloadrÒ   r	   r	   r
   rÊ   ¢  rŠ  zPickled._parsec                 C   s   t  ||¡ |S r&   )r  r  rÚ   r	   r	   r
   r×   ¥  s   zPickled._buildN©r   r   r   rK  rÊ   r×   r	   r	   r	   r
   r   Ž  s    r   c                   @   re  )ÚNumpya  
    Preserves numpy arrays (both shape, dtype and values).

    Parses using `numpy.load() <https://docs.scipy.org/doc/numpy/reference/generated/numpy.load.html#numpy.load>`_ and builds using `numpy.save() <https://docs.scipy.org/doc/numpy/reference/generated/numpy.save.html#numpy.save>`_ functions, using Numpy binary protocol. Size is undefined.

    :raises ImportError: numpy could not be imported during parsing or building
    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes

    Can propagate numpy.load() and numpy.save() exceptions.

    Example::

        >>> import numpy
        >>> a = numpy.asarray([1,2,3])
        >>> Numpy.build(a)
        b"\x93NUMPY\x01\x00F\x00{'descr': '<i8', 'fortran_order': False, 'shape': (3,), }            \n\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00"
        >>> Numpy.parse(_)
        array([1, 2, 3])
    c                 C   s   dd l }| |¡S rN   )Únumpyr  )rU   r1   r˜   rÌ   r  r	   r	   r
   rÊ   À  s   
zNumpy._parsec                 C   s   dd l }| ||¡ |S rN   )r  Úsave)rU   rÍ   r1   r˜   rÌ   r  r	   r	   r
   r×   Ä  s   zNumpy._buildNr  r	   r	   r	   r
   r  ª  s    r  c                       r†  )Ú
NamedTupleaÔ  
    Both arrays, structs, and sequences can be mapped to a namedtuple from `collections module <https://docs.python.org/3/library/collections.html#collections.namedtuple>`_. To create a named tuple, you need to provide a name and a sequence of fields, either a string with space-separated names or a list of string names, like the standard namedtuple.

    Parses into a collections.namedtuple instance, and builds from such instance (although it also builds from lists and dicts). Size is undefined.

    :param tuplename: string
    :param tuplefields: string or list of strings
    :param subcon: Construct instance, either Struct Sequence Array GreedyRange

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises NamedTupleError: subcon is neither Struct Sequence Array GreedyRange

    Can propagate collections exceptions.

    Example::

        >>> d = NamedTuple("coord", "x y z", Byte[3])
        >>> d = NamedTuple("coord", "x y z", Byte >> Byte >> Byte)
        >>> d = NamedTuple("coord", "x y z", "x"/Byte + "y"/Byte + "z"/Byte)
        >>> d.parse(b"123")
        coord(x=49, y=50, z=51)
    c                    sH   t |ttttfƒstdƒ‚tt| ƒ |¡ || _	|| _
t ||¡| _d S )Nú3subcon is neither Struct Sequence Array GreedyRange)r:   r‡   rˆ   rH  rÃ  r   rP  r  rV   Ú	tuplenameÚtuplefieldsÚcollectionsÚ
namedtupleÚfactory)rU   r	  r
  r†   rR  r	   r
   rV   â  s   zNamedTuple.__init__c                 C   sF   t | jtƒr|d= | jdi |¤ŽS t | jtttfƒr| j|Ž S tdƒ‚)Nr›  z>subcon is neither Struct Sequence Array GreedyRangeGreedyRanger	   )r:   r†   r‡   r  rˆ   rH  rÃ  r   ra  r	   r	   r
   r\  ê  s   
zNamedTuple._decodec                    sH   t | jtƒrt‡ fdd„| jjD ƒƒS t | jtttfƒr tˆ ƒS t	dƒ‚)Nc                    s"   i | ]}|j r|j tˆ |j ƒ“qS r	   )rŸ   r®   r‹  ©rÍ   r	   r
   r{   ô  s   " z&NamedTuple._encode.<locals>.<dictcomp>r  )
r:   r†   r‡   r¿   rŒ   rˆ   rH  rÃ  r¤  r   ra  r	   r  r
   r^  ò  s
   zNamedTuple._encodec                 C   sr   d|  ¡  }| d|| j| jf ¡ t| jtƒr"d|| j |¡f S t| jtt	t
fƒr5d|| j |¡f S tdƒ‚)Nrl  z9
            %s = collections.namedtuple(%r, %r)
        z
%s(**(%s))z	%s(*(%s))r  )rZ   rj   r	  r
  r:   r†   r‡   rã   rˆ   rH  rÃ  r   r®  r	   r	   r
   r÷   ù  s   þzNamedTuple._emitparsec                 C   rW  r&   rÞ  r1  r	   r	   r
   r'    rƒ   zNamedTuple._emitseqc                 C   rW  r&   rß  r1  r	   r	   r
   r-    rƒ   zNamedTuple._emitprimitivetypec                 C   rW  r&   ró  r1  r	   r	   r
   r0  
  rƒ   zNamedTuple._emitfulltype)r   r   r   rK  rV   r\  r^  r÷   r'  r-  r0  rY  r	   r	   rR  r
   r  Ê  s    r  c           	   	      s  ddl ‰ tˆtƒstdƒ‚tˆtttfƒstdƒ‚tˆtˆ jtfƒs&tdƒ‚ˆdks.ˆdkr^tdt	dƒ d	t	d
ƒ dt	dƒ dt	dƒ dt	dƒ dt	dƒ ƒ}G ‡ fdd„dt
ƒ}||ƒ}ntˆtƒrjˆ  ˆdd¡‰G ‡‡fdd„dt
ƒ}|ˆƒ}‡fdd„}‡fdd„}||_||_|S )a—  
    Datetime, represented as `Arrow <https://pypi.org/project/arrow/>`_ object.

    Note that accuracy is not guaranteed, because building rounds the value to integer (even when Float subcon is used), due to floating-point errors in general, and because MSDOS scheme has only 5-bit (32 values) seconds field (seconds are rounded to multiple of 2).

    Unit is a fraction of a second. 1 is second resolution, 10**-3 is milliseconds resolution, 10**-6 is microseconds resolution, etc. Usually its 1 on Unix and MacOSX, 10**-7 on Windows. Epoch is a year (if integer) or a specific day (if Arrow object). Usually its 1970 on Unix, 1904 on MacOSX, 1600 on Windows. MSDOS format doesnt support custom unit or epoch, it uses 2-seconds resolution and 1980 epoch.

    :param subcon: Construct instance like Int* Float*, or Int32ub with msdos format
    :param unit: integer or float, or msdos string
    :param epoch: integer, or Arrow instance, or msdos string

    :raises ImportError: arrow could not be imported during ctor
    :raises TimestampError: subcon is not a Construct instance
    :raises TimestampError: unit or epoch is a wrong type

    Example::

        >>> d = Timestamp(Int64ub, 1., 1970)
        >>> d.parse(b'\x00\x00\x00\x00ZIz\x00')
        <Arrow [2018-01-01T00:00:00+00:00]>
        >>> d = Timestamp(Int32ub, "msdos", "msdos")
        >>> d.parse(b'H9\x8c"')
        <Arrow [2016-01-25T17:33:04+00:00]>
    r   NzPsubcon should be Int*, experimentally Float*, or Int32ub when using msdos formatz%unit must be one of: int float stringz&epoch must be one of: int Arrow stringÚmsdosÚyearrÕ  Úmonthrß  Údayé   ÚhourÚminuteé   Úsecondc                       s    e Zd Z‡ fdd„Zdd„ ZdS )z(Timestamp.<locals>.MsdosTimestampAdapterc                    s8   ˆ   ddd¡j|j|jd |jd |j|j|jd d�S )Né¼  rK   rF   )ÚyearsÚmonthsÚdaysÚhoursÚminutesÚseconds)ÚArrowÚshiftr  r  r  r  r  r  ra  ©Úarrowr	   r
   r\  :  s   8z0Timestamp.<locals>.MsdosTimestampAdapter._decodec                 S   s0   |  ¡ }t|jd |j|j|j|j|jd d�S )Nr  rF   )r  r  r  r  r  r  )Ú	timetupler¿   Útm_yearÚtm_monÚtm_mdayÚtm_hourÚtm_minÚtm_sec)rU   rÍ   r˜   rÌ   Útr	   r	   r
   r^  <  s   (z0Timestamp.<locals>.MsdosTimestampAdapter._encodeN©r   r   r   r\  r^  r	   r!  r	   r
   ÚMsdosTimestampAdapter9  s    r,  rK   c                       s(   e Zd Z‡ ‡fdd„Z‡ ‡fdd„ZdS )z#Timestamp.<locals>.TimestampAdapterc                    s   ˆ j |ˆ d�S )N)r  )r   ra  ©ÚepochÚunitr	   r
   r\  E  rT  z+Timestamp.<locals>.TimestampAdapter._decodec                    s   t |ˆ   ¡ ˆ ƒS r&   )r  Útotal_secondsra  r-  r	   r
   r^  G  rš   z+Timestamp.<locals>.TimestampAdapter._encodeNr+  r	   r-  r	   r
   ÚTimestampAdapterD  s    r1  c                    ó   ˆ   | |¡S r&   r—  r”  r•  r	   r
   r0  K  r�   z Timestamp.<locals>._emitfulltypec                    r2  r&   r–  r”  r•  r	   r
   r-  M  r�   z%Timestamp.<locals>._emitprimitivetype)r"  r:   rž   r   rÉ  Úfloatr:  r  Ú	BitStructrÔ  r[  r0  r-  )	r†   r/  r.  Ústr,  r�  r1  r0  r-  r	   )r"  r.  r†   r/  r
   Ú	Timestamp  s6   






ú

r6  c                   @   ó@   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dS )ÚHexaŸ  
    Adapter for displaying hexadecimal/hexlified representation of integers/bytes/RawCopy dictionaries.

    Parsing results in int-alike bytes-alike or dict-alike object, whose only difference from original is pretty-printing. If you look at the result, you will be presented with its `repr` which remains as-is. If you print it, then you will see its `str` whic is a hexlified representation. Building and sizeof defer to subcon.

    To obtain a hexlified string (like before Hex HexDump changed semantics) use binascii.(un)hexlify on parsed results.

    Example::

        >>> d = Hex(Int32ub)
        >>> obj = d.parse(b"\x00\x00\x01\x02")
        >>> obj
        258
        >>> print(obj)
        0x00000102

        >>> d = Hex(GreedyBytes)
        >>> obj = d.parse(b"\x00\x00\x01\x02")
        >>> obj
        b'\x00\x00\x01\x02'
        >>> print(obj)
        unhexlify('00000102')

        >>> d = Hex(RawCopy(Int32ub))
        >>> obj = d.parse(b"\x00\x00\x01\x02")
        >>> obj
        {'data': b'\x00\x00\x01\x02',
         'length': 4,
         'offset1': 0,
         'offset2': 4,
         'value': 258}
        >>> print(obj)
        unhexlify('00000102')
    c              	   C   sP   t |tƒrt |dd| j ||¡  ¡S t |tƒrt|ƒS t |tƒr&t	|ƒS |S )Nz0%sXrF   )
r:   rÉ  ÚHexDisplayedIntegerr]  r†   rÛ   r;   ÚHexDisplayedBytesr  ÚHexDisplayedDictra  r	   r	   r
   r\  w  s   


zHex._decodec                 C   ó   |S r&   r	   ra  r	   r	   r
   r^  €  rb  zHex._encodec                 C   rÜ  r&   rÝ  rù   r	   r	   r
   r÷   ƒ  r�   zHex._emitparsec                 C   rW  r&   rÞ  r1  r	   r	   r
   r'  †  rƒ   zHex._emitseqc                 C   rW  r&   rß  r1  r	   r	   r
   r-  ‰  rƒ   zHex._emitprimitivetypec                 C   rW  r&   ró  r1  r	   r	   r
   r0  Œ  rƒ   zHex._emitfulltypeN©
r   r   r   rK  r\  r^  r÷   r'  r-  r0  r	   r	   r	   r
   r8  T  s    "	r8  c                   @   r7  )ÚHexDumpaŒ  
    Adapter for displaying hexlified representation of bytes/RawCopy dictionaries.

    Parsing results in bytes-alike or dict-alike object, whose only difference from original is pretty-printing. If you look at the result, you will be presented with its `repr` which remains as-is. If you print it, then you will see its `str` whic is a hexlified representation. Building and sizeof defer to subcon.

    To obtain a hexlified string (like before Hex HexDump changed semantics) use construct.lib.hexdump on parsed results.

    Example::

        >>> d = HexDump(GreedyBytes)
        >>> obj = d.parse(b"\x00\x00\x01\x02")
        >>> obj
        b'\x00\x00\x01\x02'
        >>> print(obj)
        hexundump('''
        0000   00 00 01 02                                       ....
        ''')

        >>> d = HexDump(RawCopy(Int32ub))
        >>> obj = d.parse(b"\x00\x00\x01\x02")
        >>> obj
        {'data': b'\x00\x00\x01\x02',
         'length': 4,
         'offset1': 0,
         'offset2': 4,
         'value': 258}
        >>> print(obj)
        hexundump('''
        0000   00 00 01 02                                       ....
        ''')
    c                 C   s(   t |tƒr	t|ƒS t |tƒrt|ƒS |S r&   )r:   r;   ÚHexDumpDisplayedBytesr  ÚHexDumpDisplayedDictra  r	   r	   r
   r\  °  s
   

zHexDump._decodec                 C   r<  r&   r	   ra  r	   r	   r
   r^  ·  rb  zHexDump._encodec                 C   rÜ  r&   rÝ  rù   r	   r	   r
   r÷   º  r�   zHexDump._emitparsec                 C   rW  r&   rÞ  r1  r	   r	   r
   r'  ½  rƒ   zHexDump._emitseqc                 C   rW  r&   rß  r1  r	   r	   r
   r-  À  rƒ   zHexDump._emitprimitivetypec                 C   rW  r&   ró  r1  r	   r	   r
   r0  Ã  rƒ   zHexDump._emitfulltypeNr=  r	   r	   r	   r
   r>  �  s    r>  c                       rs  )rŠ   a"  
    Treats the same data as multiple constructs (similar to C union) so you can look at the data in multiple views. Fields are usually named (so parsed values are inserted into dictionary under same name). :class:`~construct.core.Embedded` fields do not need to (and should not) be named.

    Parses subcons in sequence, and reverts the stream back to original position after each subcon. Afterwards, advances the stream by selected subcon. Builds from first subcon that has a matching key in given dict. Size is undefined (because parsefrom is not used for building).

    This class does context nesting, meaning its members are given access to a new dictionary where the "_" entry points to the outer context. When parsing, each member gets parsed and subcon parse return value is inserted into context under matching key only if the member was named. When building, the matching entry gets inserted into context before subcon gets build, and if subcon build returns a new value (not None) that gets replaced in the context.

    This class supports embedding. :class:`~construct.core.Embedded` semantics dictate, that during instance creation (in ctor), each field is checked for embedded flag, and its subcon members are merged. This changes behavior of some code examples. Only few classes are supported: Struct Sequence FocusedSeq Union LazyStruct, although those can be used interchangably (a Struct can embed a Sequence, or rather its members).

    This class exposes subcons as attributes. You can refer to subcons that were inlined (and therefore do not exist as variable in the namespace) by accessing the struct attributes, under same name. Also note that compiler does not support this feature. See examples.

    This class exposes subcons in the context. You can refer to subcons that were inlined (and therefore do not exist as variable in the namespace) within other inlined fields using the context. Note that you need to use a lambda (`this` expression is not supported). Also note that compiler does not support this feature. See examples.

    .. warning:: If you skip `parsefrom` parameter then stream will be left back at starting offset, not seeked to any common denominator.

    :param parsefrom: how to leave stream after parsing, can be integer index or string name selecting a subcon, or None (leaves stream at initial offset, the default), or context lambda
    :param \*subcons: Construct instances, list of members, some can be anonymous
    :param \*\*subconskw: Construct instances, list of members (requires Python 3.6)

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises StreamError: stream is not seekable and tellable
    :raises UnionError: selector does not match any subcon, or dict given to build does not contain any keys matching any subcon
    :raises IndexError: selector does not match any subcon
    :raises KeyError: selector does not match any subcon

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Union(0, 
        ...     "raw" / Bytes(8),
        ...     "ints" / Int32ub[2],
        ...     "shorts" / Int16ub[4],
        ...     "chars" / Byte[8],
        ... )
        >>> d.parse(b"12345678")
        Container(raw=b'12345678', ints=[825373492, 892745528], shorts=[12594, 13108, 13622, 14136], chars=[49, 50, 51, 52, 53, 54, 55, 56])
        >>> d.build(dict(chars=range(8)))
        b'\x00\x01\x02\x03\x04\x05\x06\x07'

        >>> d = Union(None,
        ...     "animal" / Enum(Byte, giraffe=1),
        ... )
        >>> d.animal.giraffe
        'giraffe'
        >>> d = Union(None,
        ...     "chars" / Byte[4],
        ...     "data" / Bytes(lambda this: this._subcons.chars.sizeof()),
        ... )
        >>> d.parse(b"\x01\x02\x03\x04")
        Container(chars=[1, 2, 3, 4])(data=b'\x01\x02\x03\x04')

        Alternative syntax, but requires Python 3.6 or any PyPy:
        >>> Union(0, raw=Bytes(8), ints=Int32ub[2], shorts=Int16ub[4], chars=Byte[8])
    c                    sh   t |tƒr	tdƒ‚tt| ƒ ¡  || _t|ƒtdd„ | ¡ D ƒƒ }t	|Ž | _
tdd„ | j
D ƒƒ| _d S )Nz9parsefrom should be either: None int str context-functionc                 s   rˆ  r&   r	   rx   r	   r	   r
   re     rf   z!Union.__init__.<locals>.<genexpr>c                 s   r‰  r&   rŠ  r‹  r	   r	   r
   re   
  r{  )r:   rž   r   rP  rŠ   rV   Ú	parsefromr¤  r}   r”   rŒ   r¿   r�  )rU   rA  rŒ   r’  rR  r	   r
   rV     s   

zUnion.__init__c                 C   r”  r&   r•  r3  r	   r	   r
   rk    r–  zUnion.__getattr__c                 C   sä   t ƒ }t ||jd |j|j|j| j|| dd ¡d�	}|j d|¡|_t	|ƒ}i }t
| jƒD ]-\}}| |||¡}	|jrD|	||j< |	||j< t	|ƒ||< |jrTt	|ƒ||j< t||ƒ q,| j}
t|
ƒre|
|ƒ}
|
d urpt|||
 ƒ |S r—  )r¿   rÃ   rÀ   rÁ   rÂ   r�  r  rt   rš  rD   r¯  rŒ   rÄ   rŸ   rB   rA  r–   )rU   r1   r˜   rÌ   rÍ   rG   Úforwardsr‚  rŽ   rœ  rA  r	   r	   r
   rÊ     s(   ,

zUnion._parsec                 C   sÎ   t ||jd |j|j|j| j|| dd ¡d�	}|j d|¡|_| 	|¡ | j
D ]9}|jr3| |jd ¡}n|j|v r>||j }nq&|jrG|||j< | ||||¡}|jrW|||j< t |j|iƒ  S td|f ƒ‚)Nr˜  r™  rš  z=cannot build, none of subcons were found in the dictionary %r)r¿   rÃ   rÀ   rÁ   rÂ   r�  r  rt   rš  r¬   rŒ   r¡   rŸ   r×   r   rŸ  r	   r	   r
   r×   '  s    ,




zUnion._buildc                 C   rÓ  )Nz=Union builds depending on actual object dict, size is unknownrÝ   rÞ   r	   r	   r
   rÛ   =  r…  zUnion._sizeofc           	      C   sb  t | jƒr	tdƒ‚d| ¡  }d|f }t| jtd ƒƒr"d}d}d}t| jtƒr@| j}| j|  d}| j|  ¡ | jd  ¡ k}t| jt	ƒrcdd„ t
| jƒD ƒ| j }d}| j|  ¡ | jd  ¡ k}t
| jƒD ].\}}|d	|jrvd
|j nd| |¡f 7 }||kr‰|s‰|d7 }|t| jƒd k r–|d7 }qh|s�|d7 }|s£|d7 }|d7 }| |¡ d|f S )Nz-Union does not compile non-constant parsefromzparse_union_%saP  
            def %s(io, this):
                this = Container(_ = this, _params = this['_params'], _root = None, _parsing = True, _building = False, _sizing = False, _subcons = None, _io = io, _index = this.get('_index', None))
                this['_root'] = this['_'].get('_root', this)
                fallback = io.tell()
        rÄ  FTc                 S   s   i | ]\}}|j r|j |“qS r	   rŠ  ©r^   r‚  rŽ   r	   r	   r
   r{   T  ra  z$Union._emitparse.<locals>.<dictcomp>z"
                %s%s
            zthis[%r] = rm   z5
                forward = io.tell()
                rK   z3
                io.seek(fallback)
                z/
                io.seek(fallback)
            z.
                io.seek(forward)
            zf
                del this['_']
                del this['_index']
                return this
        r§  )r–   rA  rÑ   rZ   r:   r/  r  rŒ   rÜ   rF  r¯  rŸ   rã   r0   rj   )	rU   rò   r¯  rk   ÚindexÚskipfallbackÚskipforwardr‚  rŽ   r	   r	   r
   r÷   @  sF   
û
þ€

zUnion._emitparse)r   r   r   rK  rV   rk  rÊ   r×   rÛ   r÷   rY  r	   r	   rR  r
   rŠ   Ê  s    8	rŠ   c                       ó0   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Z‡  ZS )ÚSelectu?  
    Selects the first matching subconstruct.

    Parses and builds by literally trying each subcon in sequence until one of them parses or builds without exception. Stream gets reverted back to original position after each failed attempt, but not if parsing succeeds. Size is not defined.

    :param \*subcons: Construct instances, list of members, some can be anonymous
    :param \*\*subconskw: Construct instances, list of members (requires Python 3.6)

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises StreamError: stream is not seekable and tellable
    :raises SelectError: neither subcon succeded when parsing or building

    Example::

        >>> d = Select(Int32ub, CString("utf8"))
        >>> d.build(1)
        b'\x00\x00\x00\x01'
        >>> d.build(u"Ð�Ñ„Ð¾Ð½")
        b'\xd0\x90\xd1\x84\xd0\xbe\xd0\xbd\x00'

        Alternative syntax, but requires Python 3.6 or any PyPy:
        >>> Select(num=Int32ub, text=CString("utf8"))
    c                    s^   t t| ƒ ¡  t|ƒtdd„ | ¡ D ƒƒ | _tdd„ | jD ƒƒ| _tdd„ | jD ƒƒ| _d S )Nc                 s   rˆ  r&   r	   rx   r	   r	   r
   re   �  rf   z"Select.__init__.<locals>.<genexpr>c                 s   rŒ  r&   r�  r‹  r	   r	   r
   re   ‘  rŽ  c                 s   rŒ  r&   )r‘   r‹  r	   r	   r
   re   ’  rŽ  )	rP  rH  rV   r¤  r}   rŒ   r�  r¡   r‘   r‘  rR  r	   r
   rV   Ž  s    zSelect.__init__c              	   C   s^   | j D ]'}t|ƒ}z| |||¡}W |  S  ty   ‚  ty*   t||ƒ Y qw tdƒ‚)Nzno subconstruct matched)rŒ   rD   rÄ   r   r   rB   r   )rU   r1   r˜   rÌ   rŽ   rG   rÍ   r	   r	   r
   rÊ   ”  s   
ûÿzSelect._parsec              	   C   sb   | j D ]&}z|j|fi |¤Ž}W n ty   ‚  ty    Y qw t||ƒ |  S td|f ƒ‚)Nzno subconstruct matched: %s)rŒ   rÖ   r   r/   r>   r   )rU   rÍ   r1   r˜   rÌ   rŽ   r3   r	   r	   r
   r×   ¡  s   
ÿ
zSelect._build©r   r   r   rK  rV   rÊ   r×   rY  r	   r	   rR  r
   rH  u  s
    rH  c                 C   s
   t | tƒS )a¤  
    Makes an optional field.

    Parsing attempts to parse subcon. If sub-parsing fails, returns None and reports success. Building attempts to build subcon. If sub-building fails, writes nothing and reports success. Size is undefined, because whether bytes would be consumed or produced depends on actual data and actual context.

    :param subcon: Construct instance

    Example::

        Optional  <-->  Select(subcon, Pass)

        >>> d = Optional(Int64ul)
        >>> d.parse(b"12345678")
        4050765991979987505
        >>> d.parse(b"")
        None
        >>> d.build(1)
        b'\x01\x00\x00\x00\x00\x00\x00\x00'
        >>> d.build(None)
        b''
    )rH  ÚPassr•  r	   r	   r
   ÚOptional¯  s   
rK  c                    s$   t ˆ ˆtƒ}‡ ‡fdd„}||_|S )aq  
    If-then conditional construct.

    Parsing evaluates condition, if True then subcon is parsed, otherwise just returns None. Building also evaluates condition, if True then subcon gets build from, otherwise does nothing. Size is either same as subcon or 0, depending how condfunc evaluates.

    :param condfunc: bool or context lambda (or a truthy value)
    :param subcon: Construct instance, used if condition indicates True

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        If <--> IfThenElse(condfunc, subcon, Pass)

        >>> d = If(this.x > 0, Byte)
        >>> d.build(255, x=1)
        b'\xff'
        >>> d.build(255, x=0)
        b''
    c                    s    t ˆ | |¡tˆ ƒ dd¡d�S )Núthis.rm   )r/  Úif_)r  r.  rS  rv   r”  ©Úcondfuncr†   r	   r
   r0  à  ó    zIf.<locals>._emitfulltype)Ú
IfThenElserJ  r0  )rO  r†   r�  r0  r	   rN  r
   ÚIfÈ  s   rR  c                       rs  )rQ  aR  
    If-then-else conditional construct, similar to ternary operator.

    Parsing and building evaluates condition, and defers to either subcon depending on the value. Size is computed the same way.

    :param condfunc: bool or context lambda (or a truthy value)
    :param thensubcon: Construct instance, used if condition indicates True
    :param elsesubcon: Construct instance, used if condition indicates False

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = IfThenElse(this.x > 0, VarInt, Byte)
        >>> d.build(255, dict(x=1))
        b'\xff\x01'
        >>> d.build(255, dict(x=0))
        b'\xff'
    c                    s2   t t| ƒ ¡  || _|| _|| _|jo|j| _d S r&   )rP  rQ  rV   rO  Ú
thensubconÚ
elsesubconr¡   )rU   rO  rS  rT  rR  r	   r
   rV   ý  s
   zIfThenElse.__init__c                 C   s4   | j }t|ƒr||ƒ}|r| jn| j}| |||¡S r&   )rO  r–   rS  rT  rÄ   )rU   r1   r˜   rÌ   rO  rŽ   r	   r	   r
   rÊ     ó
   zIfThenElse._parsec                 C   s6   | j }t|ƒr||ƒ}|r| jn| j}| ||||¡S r&   )rO  r–   rS  rT  r×   )rU   rÍ   r1   r˜   rÌ   rO  rŽ   r	   r	   r
   r×     ó
   zIfThenElse._buildc                 C   s2   | j }t|ƒr||ƒ}|r| jn| j}| ||¡S r&   )rO  r–   rS  rT  rÛ   )rU   r˜   rÌ   rO  rŽ   r	   r	   r
   rÛ     s
   zIfThenElse._sizeofc                 C   s    d| j  |¡| j| j |¡f S )Nz((%s) if (%s) else (%s)))rS  rã   rO  rT  rù   r	   r	   r
   r÷     rP  zIfThenElse._emitparsec                 C   sN   t d| j ||¡t| jƒ dd¡d�t d| j ||¡t| j ƒ dd¡d�gS )NÚ	thenvaluerL  rm   )rô   r/  rM  rT  )r  rS  r.  rS  rO  rv   rT  r1  r	   r	   r
   r'    s   $&þzIfThenElse._emitseq)r   r   r   rK  rV   rÊ   r×   rÛ   r÷   r'  rY  r	   r	   rR  r
   rQ  æ  s    rQ  c                       rÂ  )ÚSwitcha+  
    A conditional branch.

    Parsing and building evaluate keyfunc and select a subcon based on the value and dictionary entries. Dictionary (cases) maps values into subcons. If no case matches then `default` is used (that is Pass by default). Note that `default` is a Construct instance, not a dictionary key. Size is evaluated in same way as parsing and building, by evaluating keyfunc and selecting a field accordingly.

    :param keyfunc: context lambda or constant, that matches some key in cases
    :param cases: dict mapping keys to Construct instances
    :param default: optional, Construct instance, used when keyfunc is not found in cases, Pass is default value for this parameter, Error is a possible value for this parameter

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Switch(this.n, { 1:Int8ub, 2:Int16ub, 4:Int32ub })
        >>> d.build(5, n=1)
        b'\x05'
        >>> d.build(5, n=4)
        b'\x00\x00\x00\x05'

        >>> d = Switch(this.n, {}, default=Byte)
        >>> d.parse(b"\x01", n=255)
        1
        >>> d.build(1, n=255)
        b"\x01"
    Nc                    sV   |d u rt }tt| ƒ ¡  || _|| _|| _t| ¡ ƒ|g }t	dd„ |D ƒƒ| _
d S )Nc                 s   rŒ  r&   r�  r‹  r	   r	   r
   re   H  rŽ  z"Switch.__init__.<locals>.<genexpr>)rJ  rP  rX  rV   ÚkeyfuncÚcasesÚdefaultr¤  Úvaluesr�  r¡   )rU   rY  rZ  r[  ÚallcasesrR  r	   r
   rV   @  s   zSwitch.__init__c                 C   s4   | j }t|ƒr||ƒ}| j || j¡}| |||¡S r&   )rY  r–   rZ  r  r[  rÄ   )rU   r1   r˜   rÌ   rY  rŽ   r	   r	   r
   rÊ   J  rU  zSwitch._parsec                 C   s6   | j }t|ƒr||ƒ}| j || j¡}| ||||¡S r&   )rY  r–   rZ  r  r[  r×   )rU   rÍ   r1   r˜   rÌ   rY  rŽ   r	   r	   r
   r×   Q  rV  zSwitch._buildc              	   C   sP   z| j }t|ƒr||ƒ}| j || j¡}| ||¡W S  ttfy'   tdƒ‚w ry  )	rY  r–   rZ  r  r[  rÛ   r{  r|  r   )rU   r˜   rÌ   rY  rŽ   r	   r	   r
   rÛ   X  s   ÿzSwitch._sizeofc              	      sn   dˆ   ¡  }ˆ  d|d ‡ fdd„| j ¡ D ƒ¡f ¡ dˆ   ¡  }ˆ  d|| j ˆ ¡f ¡ d|| j|f S )	Nrl  z	%s = {%s}rz  c                 3   s&   � | ]\}}d ||  ˆ ¡f V  qdS )z%r : lambda io,this: %sN©rã   )r^   ÚkeyrŽ   ©rò   r	   r
   re   e  ó   €$ z$Switch._emitparse.<locals>.<genexpr>zcompiled_%sz%s = lambda io,this: %sz%s.get(%s, %s)(io, this))rZ   rj   ri   rZ  r}   r[  rã   rY  )rU   rò   r¯  Údefaultfnamer	   r`  r
   r÷   c  s
   ,zSwitch._emitparser&   rê  r	   r	   rR  r
   rX  #  s    
rX  c                 C   sJ   t | jƒ}| ¡ D ]\}}|jD ]}| |jt||k|ƒ ¡ qq	t|Ž S )aI  
    Macro that simulates embedding Switch, which under new embedding semantics is not possible. This macro does NOT produce a Switch. It generates classes that behave the same way as you would expect from embedded Switch, only that. Instance created by this macro CAN be embedded.

    Both `merged` and all values in `mapping` must be Struct instances. Macro re-creates a single struct that contains all fields, where each field is wrapped in `If(selector == key, ...)`. Note that resulting dictionary contains None values for fields that would not be chosen by switch. Note also that if selector does not match any cases, it passes successfully (default Switch behavior).

    All fields should have unique names. Otherwise fields that were not selected during parsing may return None and override other fields context entries that have same name. This is because `If` field returns None value if condition is not met, but the Struct inserts that None value into the context entry regardless.

    :param merged: Struct instance
    :param selector: this expression, that references one of `merged` fields
    :param mapping: dict with values being Struct instances

    Example::

        d = EmbeddedSwitch(
            Struct(
                "type" / Byte,
            ),
            this.type,
            {
                0: Struct("name" / PascalString(Byte, "utf8")),
                1: Struct("value" / Byte),
            }
        )

        # generates essentially following
        d = Struct(
            "type" / Byte,
            "name" / If(this.type == 0, PascalString(Byte, "utf8")),
            "value" / If(this.type == 1, Byte),
        )

        # both parse like following
        >>> d.parse(b"\x00\x00")
        Container(type=0, name=u'', value=None)
        >>> d.parse(b"\x01\x00")
        Container(type=1, name=None, value=0)
    )r¤  rŒ   r}   rj   rŸ   rR  r‡   )ÚmergedÚselectorrh  Úmerged2r_  r5  rŽ   r	   r	   r
   ÚEmbeddedSwitchl  s   
'
ÿrf  c                       rM  )ÚStopIfaº  
    Checks for a condition, and stops certain classes (:class:`~construct.core.Struct` :class:`~construct.core.Sequence` :class:`~construct.core.GreedyRange`) from parsing or building further.

    Parsing and building check the condition, and raise StopFieldError if indicated. Size is undefined.

    :param condfunc: bool or context lambda (or truthy value)

    :raises StopFieldError: used internally

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> Struct('x'/Byte, StopIf(this.x == 0), 'y'/Byte)
        >>> Sequence('x'/Byte, StopIf(this.x == 0), 'y'/Byte)
        >>> GreedyRange(FocusedSeq(0, 'x'/Byte, StopIf(this.x == 0)))
    c                    rå  ru  )rP  rg  rV   rO  r¡   )rU   rO  rR  r	   r
   rV   ­  rè  zStopIf.__init__c                 C   s"   | j }t|ƒr||ƒ}|rt‚d S r&   ©rO  r–   r   )rU   r1   r˜   rÌ   rO  r	   r	   r
   rÊ   ²  ó   ÿzStopIf._parsec                 C   s"   | j }t|ƒr||ƒ}|rt‚d S r&   rh  )rU   rÍ   r1   r˜   rÌ   rO  r	   r	   r
   r×   ¹  ri  zStopIf._buildc                 C   rÓ  )NzxStopIf cannot determine size because it depends on actual context which then depends on actual data and outer constructsrÝ   rÞ   r	   r	   r
   rÛ   À  r…  zStopIf._sizeofc                 C   rú  )Nzy
            def parse_stopif(condition):
                if condition:
                    raise StopFieldError
        zparse_stopif(%s))rj   rO  rù   r	   r	   r
   r÷   Ã  s   
zStopIf._emitparserê  r	   r	   rR  r
   rg  š  s    rg  rQ  c                    s6   t ˆ t|d�}‡ fdd„}‡ fdd„}||_||_|S )ap  
    Appends null bytes.

    Parsing consumes specified amount of bytes and discards it. Building writes specified pattern byte multiplied into specified length. Size is same as specified.

    :param length: integer or context lambda, length of the padding
    :param pattern: b-character, padding pattern, default is \\x00

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises PaddingError: length was negative
    :raises PaddingError: pattern was not bytes (b-character)

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Padding(4) or Padded(4, Pass)
        >>> d.build(None)
        b'\x00\x00\x00\x00'
        >>> d.parse(b"****")
        None
        >>> d.sizeof()
        4
    )Úpatternc                    s   |st ‚dˆ f S rÚ  rÐ   r”  r~  r	   r
   r-  é  ó   
z#Padding.<locals>._emitprimitivetypec                    s   |rt ‚tˆ d�S r  )rÑ   r  r”  r~  r	   r
   r0  í  rk  zPadding.<locals>._emitfulltype)ÚPaddedrJ  r-  r0  )r2   rj  r�  r-  r0  r	   r~  r
   ÚPaddingÏ  s   rm  c                       rÀ  )rl  aí  
    Appends additional null bytes to achieve a length.

    Parsing first parses the subcon, then uses stream.tell() to measure how many bytes were read and consumes additional bytes accordingly. Building first builds the subcon, then uses stream.tell() to measure how many bytes were written and produces additional bytes accordingly. Size is same as `length`, but negative amount results in error. Note that subcon can actually be variable size, it is the eventual amount of bytes that is read or written during parsing or building that determines actual padding.

    :param length: integer or context lambda, length of the padding
    :param subcon: Construct instance
    :param pattern: optional, b-character, padding pattern, default is \\x00

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises PaddingError: length is negative
    :raises PaddingError: subcon read or written more than the length (would cause negative pad)
    :raises PaddingError: pattern is not bytes of length 1

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Padded(4, Byte)
        >>> d.build(255)
        b'\xff\x00\x00\x00'
        >>> d.parse(_)
        255
        >>> d.sizeof()
        4

        >>> d = Padded(4, VarInt)
        >>> d.build(1)
        b'\x01\x00\x00\x00'
        >>> d.build(70000)
        b'\xf0\xa2\x04\x00'
    rQ  c                    ó>   t |tƒrt|ƒdkrtdƒ‚tt| ƒ |¡ || _|| _d S )NrK   z(pattern expected to be bytes of length 1)	r:   r;   r0   r    rP  rl  rV   r2   rj  )rU   r2   r†   rj  rR  r	   r
   rV     ó
   
zPadded.__init__c           	      C   sr   t | j|ƒ}|dk rtdƒ‚t|ƒ}| j |||¡}t|ƒ}|||  }|dk r2td|| |f ƒ‚t||ƒ |S )Nr   úlength cannot be negativez.subcon parsed %d bytes but was allowed only %d)r™   r2   r    rD   r†   rÄ   r4   )	rU   r1   r˜   rÌ   r2   Ú	position1rÍ   Ú	position2r>  r	   r	   r
   rÊ     s   
zPadded._parsec           
      C   s|   t | j|ƒ}|dk rtdƒ‚t|ƒ}| j ||||¡}t|ƒ}|||  }	|	dk r3td|| |f ƒ‚t|| j|	 |	ƒ |S ©Nr   rp  z-subcon build %d bytes but was allowed only %d)r™   r2   r    rD   r†   r×   r>   rj  )
rU   rÍ   r1   r˜   rÌ   r2   rq  r`  rr  r>  r	   r	   r
   r×   ,  s   zPadded._buildc              	   C   s>   zt | j|ƒ}|dk rtdƒ‚|W S  ttfy   tdƒ‚w )Nr   rp  rz  )r™   r2   r    r{  r|  r   rÌ  r	   r	   r
   rÛ   9  s   ÿzPadded._sizeofc                 C   s   d| j  |¡| j| j  ¡ f S )Nz#(%s, read_bytes(io, (%s)-(%s) ))[0])r†   rã   r2   rÜ   rù   r	   r	   r
   r÷   B  ó   zPadded._emitparsec                 C   s   t | j| j ||¡d�S )N)r�  r/  )r  r2   r†   r.  r1  r	   r	   r
   r0  E  ó   zPadded._emitfulltype©rQ  r‚  r	   r	   rR  r
   rl  ö  s    !	rl  c                       rÂ  )ÚAlignedaÙ  
    Appends additional null bytes to achieve a length that is shortest multiple of a modulus.

    Note that subcon can actually be variable size, it is the eventual amount of bytes that is read or written during parsing or building that determines actual padding.

    Parsing first parses subcon, then consumes an amount of bytes to sum up to specified length, and discards it. Building first builds subcon, then writes specified pattern byte to sum up to specified length. Size is subcon size plus modulo remainder, unless SizeofError was raised.

    :param modulus: integer or context lambda, modulus to final length
    :param subcon: Construct instance
    :param pattern: optional, b-character, padding pattern, default is \\x00

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises PaddingError: modulus was less than 2
    :raises PaddingError: pattern was not bytes (b-character)

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Aligned(4, Int16ub)
        >>> d.parse(b'\x00\x01\x00\x00')
        1
        >>> d.sizeof()
        4
    rQ  c                    rn  )NrK   z&pattern expected to be bytes character)	r:   r;   r0   r    rP  rw  rV   Úmodulusrj  )rU   rx  r†   rj  rR  r	   r
   rV   d  ro  zAligned.__init__c           	      C   sf   t | jƒr
|  |¡n| j}|dk rtdƒ‚t|ƒ}| j |||¡}t|ƒ}||  | }t||ƒ |S ©NrF   úexpected modulo 2 or greater)r–   rx  r    rD   r†   rÄ   r4   )	rU   r1   r˜   rÌ   rx  rq  rÍ   rr  r>  r	   r	   r
   rÊ   k  s   
zAligned._parsec           
      C   sp   t | jƒr
|  |¡n| j}|dk rtdƒ‚t|ƒ}| j ||||¡}t|ƒ}||  | }	t|| j|	 |	ƒ |S ry  )r–   rx  r    rD   r†   r×   r>   rj  )
rU   rÍ   r1   r˜   rÌ   rx  rq  r`  rr  r>  r	   r	   r
   r×   v  s   zAligned._buildc              	   C   sd   z$t | jƒr|  |¡n| j}|dk rtdƒ‚| j ||¡}|| |  W S  ttfy1   tdƒ‚w )NrF   rz  rz  )r–   rx  r    r†   rÛ   r{  r|  r   )rU   r˜   rÌ   rx  Ú	subconlenr	   r	   r
   rÛ   �  s   ÿzAligned._sizeofc                 C   s   d| j  |¡| j  ¡ | jf S )Nz'(%s, read_bytes(io, -(%s) %% (%s) ))[0])r†   rã   rÜ   rx  rù   r	   r	   r
   r÷   ‹  rt  zAligned._emitparserv  rê  r	   r	   rR  r
   rw  I  s    
rw  c                    s4   t |ƒt dd„ | ¡ D ƒƒ }t‡ fdd„|D ƒŽ S )a‰  
    Makes a structure where each field is aligned to the same modulus (it is a struct of aligned fields, NOT an aligned struct).

    See :class:`~construct.core.Aligned` and :class:`~construct.core.Struct` for semantics and raisable exceptions.

    :param modulus: integer or context lambda, passed to each member
    :param \*subcons: Construct instances, list of members, some can be anonymous
    :param \*\*subconskw: Construct instances, list of members (requires Python 3.6)

    Example::

        >>> d = AlignedStruct(4, "a"/Int8ub, "b"/Int16ub)
        >>> d.build(dict(a=0xFF,b=0xFFFF))
        b'\xff\x00\x00\x00\xff\xff\x00\x00'
    c                 s   rˆ  r&   r	   rx   r	   r	   r
   re   Ÿ  rf   z AlignedStruct.<locals>.<genexpr>c                    s   g | ]
}|j tˆ |ƒ ‘qS r	   )rŸ   rw  r‹  ©rx  r	   r
   r`      s    z!AlignedStruct.<locals>.<listcomp>)r¤  r}   r‡   )rx  rŒ   r’  r	   r|  r
   ÚAlignedStruct�  s   r}  c                  O   s   t t| i |¤ŽƒS )a¥  
    Makes a structure inside a Bitwise.

    See :class:`~construct.core.Bitwise` and :class:`~construct.core.Struct` for semantics and raisable exceptions.

    :param \*subcons: Construct instances, list of members, some can be anonymous
    :param \*\*subconskw: Construct instances, list of members (requires Python 3.6)

    Example::

        BitStruct  <-->  Bitwise(Struct(...))

        >>> d = BitStruct(
        ...     "a" / Flag,
        ...     "b" / Nibble,
        ...     "c" / BitsInteger(10),
        ...     "d" / Padding(1),
        ... )
        >>> d.parse(b"\xbe\xef")
        Container(a=True)(b=7)(c=887)(d=None)
        >>> d.sizeof()
        2
    )rž  r‡   )rŒ   r’  r	   r	   r
   r4  £  s   r4  c                       rÀ  )ÚPointeraC  
    Jumps in the stream forth and back for one field.

    Parsing and building seeks the stream to new location, processes subcon, and seeks back to original location. Size is defined as 0 but that does not mean no bytes are written into the stream.

    Offset can be positive, indicating a position from stream beginning forward, or negative, indicating a position from EOF backwards.

    :param offset: integer or context lambda, positive or negative
    :param subcon: Construct instance
    :param stream: None to use original stream (default), or context lambda to provide a different stream

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises StreamError: stream is not seekable and tellable

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Pointer(8, Bytes(1))
        >>> d.parse(b"abcdefghijkl")
        b'i'
        >>> d.build(b"Z")
        b'\x00\x00\x00\x00\x00\x00\x00\x00Z'
    Nc                    r²  r&   )rP  r~  rV   r@   r1   )rU   r@   r†   r1   rR  r	   r
   rV   Û  r´  zPointer.__init__c                 C   sZ   t | j|ƒ}t | j|ƒp|}t|ƒ}t|||dk rdndƒ | j |||¡}t||ƒ |S rE   )r™   r@   r1   rD   rB   r†   rÄ   )rU   r1   r˜   rÌ   r@   rG   rÍ   r	   r	   r
   rÊ   à  s   
zPointer._parsec                 C   s\   t | j|ƒ}t | j|ƒp|}t|ƒ}t|||dk rdndƒ | j ||||¡}t||ƒ |S rE   )r™   r@   r1   rD   rB   r†   r×   )rU   rÍ   r1   r˜   rÌ   r@   rG   r`  r	   r	   r
   r×   é  s   
zPointer._buildc                 C   r†  rN   r	   rÞ   r	   r	   r
   rÛ   ò  rb  zPointer._sizeofc                 C   s    |  d¡ d| j| j |¡f S )Nzñ
            def parse_pointer(io, offset, func):
                fallback = io.tell()
                io.seek(offset, 2 if offset < 0 else 0)
                obj = func()
                io.seek(fallback)
                return obj
        z!parse_pointer(io, %s, lambda: %s))rj   r@   r†   rã   rù   r	   r	   r
   r÷   õ  s   
zPointer._emitparsec                 C   sL   t | jƒr
| j ¡ n| j}d| ¡  }tdd|i| j ||¡¤Ž|j|< |S )Nzinstance_%sÚposr	   )r–   r@   Ú__getfield__rZ   r  r†   r(  rq   )rU   r*  r+  r@   rŸ   r	   r	   r
   r-     s   "zPointer._emitprimitivetyper&   r¿  r	   r	   rR  r
   r~  Á  s    		r~  c                       rM  )ÚPeekaÚ  
    Peeks at the stream.

    Parsing sub-parses (and returns None if failed), then reverts stream to original position. Building does nothing (its NOT deferred). Size is defined as 0 because there is no building.

    This class is used in :class:`~construct.core.Union` class to parse each member.

    :param subcon: Construct instance

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises StreamError: stream is not seekable and tellable

    Example::

        >>> d = Sequence(Peek(Int8ub), Peek(Int16ub))
        >>> d.parse(b"\x01\x02")
        [1, 258]
        >>> d.sizeof()
        0
    c                    rØ  ru  )rP  r�  rV   r¡   rQ  rR  r	   r
   rV     rÅ  zPeek.__init__c              	   C   sf   t |ƒ}z(z| j |||¡W W t||ƒ S  ty   ‚  ty$   Y nw W t||ƒ d S t||ƒ w r&   )rD   r†   rÄ   rB   r   r   )rU   r1   r˜   rÌ   rG   r	   r	   r
   rÊ   !  s   ûÿzPeek._parsec                 C   r<  r&   r	   rÚ   r	   r	   r
   r×   ,  rb  zPeek._buildc                 C   r†  rN   r	   rÞ   r	   r	   r
   rÛ   /  rb  zPeek._sizeofc                 C   s   |  d¡ d| j |¡f S )NaJ  
            def parse_peek(io, func):
                fallback = io.tell()
                try:
                    return func()
                except ExplicitError:
                    raise
                except ConstructError:
                    pass
                finally:
                    io.seek(fallback)
        zparse_peek(io, lambda: %s))rj   r†   rã   rù   r	   r	   r
   r÷   2  s   
zPeek._emitparserê  r	   r	   rR  r
   r�    s    r�  c                       rÂ  )ÚSeekaZ  
    Seeks the stream.

    Parsing and building seek the stream to given location (and whence), and return stream.seek() return value. Size is not defined.

    .. seealso:: Analog :class:`~construct.core.Pointer` wrapper that has same side effect but also processes a subcon, and also seeks back.

    :param at: integer or context lambda, where to jump to
    :param whence: optional, integer or context lambda, is the offset from beginning (0) or from current position (1) or from EOF (2), default is 0

    :raises StreamError: stream is not seekable

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = (Seek(5) >> Byte)
        >>> d.parse(b"01234x")
        [5, 120]

        >>> d = (Bytes(10) >> Seek(5) >> Byte)
        >>> d.build([b"0123456789", None, 255])
        b'01234\xff6789'
    r   c                    s$   t t| ƒ ¡  || _|| _d| _d S ru  )rP  r‚  rV   ÚatrA   r¡   )rU   rƒ  rA   rR  r	   r
   rV   \  rq  zSeek.__init__c                 C   s@   t | jƒr
|  |¡n| j}t | jƒr|  |¡n| j}t|||ƒS r&   ©r–   rƒ  rA   rB   )rU   r1   r˜   rÌ   rƒ  rA   r	   r	   r
   rÊ   b  ó   zSeek._parsec                 C   s@   t | jƒr
|  |¡n| j}t | jƒr|  |¡n| j}t|||ƒS r&   r„  )rU   rÍ   r1   r˜   rÌ   rƒ  rA   r	   r	   r
   r×   g  r…  zSeek._buildc                 C   rÓ  )Nz2Seek only moves the stream, size is not meaningfulrÝ   rÞ   r	   r	   r
   rÛ   l  r…  zSeek._sizeofc                 C   s   d| j | jf S )Nzio.seek(%s, %s))rƒ  rA   rù   r	   r	   r
   r÷   o  rT  zSeek._emitparse©r   rê  r	   r	   rR  r
   r‚  B  s    r‚  c                       rM  )ÚTella1  
    Tells the stream.

    Parsing and building return current stream offset using using stream.tell(). Size is defined as 0 because parsing and building does not consume or add into the stream.

    Tell is useful for adjusting relative offsets to absolute positions, or to measure sizes of Constructs. To get an absolute pointer, use a Tell plus a relative offset. To get a size, place two Tells and measure their difference using a Compute field. However, its recommended to use :class:`~construct.core.RawCopy` instead of manually extracting two positions and computing difference.

    :raises StreamError: stream is not tellable

    Example::

        >>> d = Struct("num"/VarInt, "offset"/Tell)
        >>> d.parse(b"X")
        Container(num=88)(offset=1)
        >>> d.build(dict(num=88))
        b'X'
    c                    rì  ru  rí  rT   rR  r	   r
   rV   ‡  rÅ  zTell.__init__c                 C   r„  r&   ©rD   rÒ   r	   r	   r
   rÊ   ‹  r…  zTell._parsec                 C   s   t |ƒS r&   rˆ  rÚ   r	   r	   r
   r×   Ž  r…  zTell._buildc                 C   r†  rN   r	   rÞ   r	   r	   r
   rÛ   ‘  rb  zTell._sizeofc                 C   r†  )Nz	io.tell()r	   rù   r	   r	   r
   r÷   ”  rb  zTell._emitparserê  r	   r	   rR  r
   r‡  s  s    r‡  c                       rs  )rJ  a  
    No-op construct, useful as default cases for Switch and Enum.

    Parsing returns None. Building does nothing. Size is 0 by definition.

    Example::

        >>> Pass.parse(b"")
        None
        >>> Pass.build(None)
        b''
        >>> Pass.sizeof()
        0
    c                    rì  ru  rí  rT   rR  r	   r
   rV   ©  rÅ  zPass.__init__c                 C   s   d S r&   r	   rÒ   r	   r	   r
   rÊ   ­  rb  zPass._parsec                 C   r<  r&   r	   rÚ   r	   r	   r
   r×   °  rb  zPass._buildc                 C   r†  rN   r	   rÞ   r	   r	   r
   rÛ   ³  rb  zPass._sizeofc                 C   r†  )NÚNoner	   rù   r	   r	   r
   r÷   ¶  rb  zPass._emitparsec                 C   r‡  )Nr   r€  r‰  r1  r	   r	   r
   r0  ¹  rŠ  zPass._emitfulltyper‚  r	   r	   rR  r
   rJ  ˜  s    rJ  c                       r6  )
Ú
Terminateda5  
    Asserts end of stream (EOF). You can use it to ensure no more unparsed data follows in the stream.

    Parsing checks if stream reached EOF, and raises TerminatedError if not. Building does nothing. Size is defined as 0 because parsing and building does not consume or add into the stream, as far as other constructs see it.

    :raises TerminatedError: stream not at EOF when parsing

    Example::

        >>> Terminated.parse(b"")
        None
        >>> Terminated.parse(b"remaining")
        construct.core.TerminatedError: expected end of stream
    c                    rì  ru  rí  rT   rR  r	   r
   rV   Î  rÅ  zTerminated.__init__c                 C   s   |  d¡r	tdƒ‚d S )NrK   zexpected end of stream)r.   r!   rÒ   r	   r	   r
   rÊ   Ò  s   
ÿzTerminated._parsec                 C   r<  r&   r	   rÚ   r	   r	   r
   r×   Ö  rb  zTerminated._buildc                 C   rÎ   r&   rÝ   rÞ   r	   r	   r
   rÛ   Ù  rb  zTerminated._sizeofrð  r	   r	   rR  r
   rŠ  ½  s    rŠ  c                   @   re  )ÚRawCopya‘  
    Used to obtain byte representation of a field (aside of object value).

    Returns a dict containing both parsed subcon value, the raw bytes that were consumed by subcon, starting and ending offset in the stream, and amount in bytes. Builds either from raw bytes representation or a value used by subcon. Size is same as subcon.

    Object is a dictionary with either "data" or "value" keys, or both.

    :param subcon: Construct instance

    :raises StreamError: stream is not seekable and tellable
    :raises RawCopyError: building and neither data or value was given
    :raises StringError: building from non-bytes value, perhaps unicode

    Example::

        >>> d = RawCopy(Byte)
        >>> d.parse(b"\xff")
        Container(data=b'\xff')(value=255)(offset1=0)(offset2=1)(length=1)
        >>> d.build(dict(data=b"\xff"))
        '\xff'
        >>> d.build(dict(value=255))
        '\xff'
    c                 C   sN   t |ƒ}| j |||¡}t |ƒ}t||ƒ t||| ƒ}t|||||| d�S )N©r3   r´   Úoffset1Úoffset2r2   )rD   r†   rÄ   rB   r4   r¿   )rU   r1   r˜   rÌ   r�  rÍ   rŽ  r3   r	   r	   r
   rÊ   ù  s   
zRawCopy._parsec           
      C   sÔ   |d u r| j jrtd d�}d|v r-|d }t|ƒ}t||ƒ t|ƒ}t|||||| d�S d|v rf|d }t|ƒ}| j  ||||¡}	|	d u rH|n|	}t|ƒ}t||ƒ t||| ƒ}t||||||| d�S t	dƒ‚)N)r´   r3   )r3   r�  rŽ  r2   r´   rŒ  z:RawCopy cannot build, both data and value keys are missing)
r†   r¡   r  rD   r>   r¿   r×   rB   r4   r"   )
rU   rÍ   r1   r˜   rÌ   r3   r�  rŽ  r´   r`  r	   r	   r
   r×     s$   


zRawCopy._buildNr  r	   r	   r	   r
   r‹  à  s    r‹  c                 C   s   |   ¡ }t| t|t|ƒS )aã  
    Swaps the byte order within boundaries of given subcon. Requires a fixed sized subcon.

    :param subcon: Construct instance, subcon on top of byte swapped bytes

    :raises SizeofError: ctor or compiler could not compute subcon size

    See :class:`~construct.core.Transformed` and :class:`~construct.core.Restreamed` for raisable exceptions.

    Example::

        Int24ul <--> ByteSwapped(Int24ub) <--> BytesInteger(3, swapped=True) <--> ByteSwapped(BytesInteger(3))
    )rÜ   r˜  r×  ©r†   r�  r	   r	   r
   ÚByteSwapped  s   r�  c                 C   sD   z|   ¡ }t| t|t|ƒW S  ty!   t| tdtddd„ ƒ Y S w )aC  
    Swaps the bit order within each byte within boundaries of given subcon. Does NOT require a fixed sized subcon.

    :param subcon: Construct instance, subcon on top of bit swapped bytes

    :raises SizeofError: compiler could not compute subcon size

    See :class:`~construct.core.Transformed` and :class:`~construct.core.Restreamed` for raisable exceptions.

    Example::

        >>> d = Bitwise(Bytes(8))
        >>> d.parse(b"\x01")
        '\x00\x00\x00\x00\x00\x00\x00\x01'
        >>>> BitsSwapped(d).parse(b"\x01")
        '\x01\x00\x00\x00\x00\x00\x00\x00'
    rK   c                 S   rr  r&   r	   r�  r	   r	   r
   r)   @  rÑ  zBitsSwapped.<locals>.<lambda>)rÜ   r˜  Úswapbitsinbytesr   r›  r�  r	   r	   r
   ÚBitsSwapped)  s   ÿr’  c                       sR   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
‡  ZS )rI  aŽ  
    Prefixes a field with byte count.

    Parses the length field. Then reads that amount of bytes, and parses subcon using only those bytes. Constructs that consume entire remaining stream are constrained to consuming only the specified amount of bytes (a substream). When building, data gets prefixed by its length. Optionally, length field can include its own size. Size is the sum of both fields sizes, unless either raises SizeofError.

    Analog to :class:`~construct.core.PrefixedArray` which prefixes with an element count, instead of byte count. Semantics is similar but implementation is different.

    :class:`~construct.core.VarInt` is recommended for new protocols, as it is more compact and never overflows.

    :param lengthfield: Construct instance, field used for storing the length
    :param subcon: Construct instance, subcon used for storing the value
    :param includelength: optional, bool, whether length field should include its own size, default is False

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes

    Example::

        >>> d = Prefixed(VarInt, GreedyRange(Int32ul))
        >>> d.parse(b"\x08abcdefgh")
        [1684234849, 1751606885]

        >>> d = PrefixedArray(VarInt, Int32ul)
        >>> d.parse(b"\x02abcdefgh")
        [1684234849, 1751606885]
    Fc                    r²  r&   )rP  rI  rV   rD  Úincludelength)rU   rD  r†   r“  rR  r	   r
   rV   ^  r´  zPrefixed.__init__c                 C   sr   | j  |||¡}| jr|| j  ||¡8 }t||ƒ}| jtu r |S t| jƒtu r.| 	| jj
¡S | j t |¡||¡S r&   )rD  rÄ   r“  rÛ   r4   r†   rƒ  r/  rO  ré   r4  r»   r¼   rÆ  r	   r	   r
   rÊ   c  s   

zPrefixed._parsec           	      C   sb   t  ¡ }| j ||||¡}| ¡ }t|ƒ}| jr!|| j ||¡7 }| j ||||¡ t	||ƒ |S r&   )
r»   r¼   r†   r×   rÕ   r0   r“  rD  rÛ   r>   )	rU   rÍ   r1   r˜   rÌ   rl  r`  r3   r2   r	   r	   r
   r×   n  s   
zPrefixed._buildc                 C   s   | j  ||¡| j ||¡ S r&   )rD  rÛ   r†   rÞ   r	   r	   r
   rÛ   y  rÑ  zPrefixed._sizeofc                 C   sD   t |ƒ}| j |||¡}| jr|| j ||¡8 }t |ƒ}|| | S r&   )rD   rD  rÊ   r“  rÛ   )rU   r1   r˜   rÌ   rq  r2   rr  r	   r	   r
   rà   |  s   zPrefixed._actualsizec                 C   s2   | j r| j ¡ nd}d| j |¡|| j |¡f S )Nr   z2restream(read_bytes(io, (%s)-(%s)), lambda io: %s))r“  rD  rÜ   rã   r†   )rU   rò   Úsubr	   r	   r
   r÷   „  s   zPrefixed._emitparsec                 C   s.   t d| j ||¡d�t dd| j ||¡d�gS )NrD  rE  r3   )rô   r�  r/  )r  rD  r.  r†   r1  r	   r	   r
   r'  ˆ  s   þzPrefixed._emitseqrÁ  )r   r   r   rK  rV   rÊ   r×   rÛ   rà   r÷   r'  rY  r	   r	   rR  r
   rI  C  s    rI  c                    sf   t ddtˆ ttjƒƒ dˆtj  ƒ}‡ ‡fdd„}||_‡ ‡fdd„}||_‡ ‡fdd„}||_|S )	a}  
    Prefixes an array with item count (as opposed to prefixed by byte count, see :class:`~construct.core.Prefixed`).

    :class:`~construct.core.VarInt` is recommended for new protocols, as it is more compact and never overflows.

    :param countfield: Construct instance, field used for storing the element count
    :param subcon: Construct instance, subcon used for storing each element

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises RangeError: consumed or produced too little elements

    Example::

        >>> d = Prefixed(VarInt, GreedyRange(Int32ul))
        >>> d.parse(b"\x08abcdefgh")
        [1684234849, 1751606885]

        >>> d = PrefixedArray(VarInt, Int32ul)
        >>> d.parse(b"\x02abcdefgh")
        [1684234849, 1751606885]
    r}   rI  c                    s   dˆ  | ¡ˆ   | ¡f S )Nz&ListContainer((%s) for i in range(%s))r^  r`  ©Ú
countfieldr†   r	   r
   r÷   ©  ru  z!PrefixedArray.<locals>._emitparsec                    s6   t |ƒ}ˆ  |||¡}t |ƒ}|| |ˆ ||¡  S r&   )rD   rÊ   rÛ   )rU   r1   r˜   rÌ   rq  rI  rr  r•  r	   r
   rà   ¬  s   z"PrefixedArray.<locals>._actualsizec                    s,   t dˆ  | |¡d�t dˆ | |¡ddd�gS )Nr–  rE  r3   r¾  )rô   r/  r¿  rÀ  rG  r”  r•  r	   r
   r'  ²  s   þzPrefixedArray.<locals>._emitseq)	r‰   rñ  Úlen_Úthisr}   rI  r÷   rà   r'  )r–  r†   r�  r÷   rà   r'  r	   r•  r
   ÚPrefixedArray�  s   þr™  c                       rs  )rA  aB  
    Restricts parsing to specified amount of bytes.

    Parsing reads `length` bytes, then defers to subcon using new BytesIO with said bytes. Building builds the subcon using new BytesIO, then writes said data and additional null bytes accordingly. Size is same as `length`, although negative amount raises an error as well.

    :param length: integer or context lambda, total amount of bytes (both data and padding)
    :param subcon: Construct instance

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises PaddingError: length is negative
    :raises PaddingError: subcon written more bytes than entire length (negative padding)

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = FixedSized(10, Byte)
        >>> d.parse(b'\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00')
        255
        >>> d.build(255)
        b'\xff\x00\x00\x00\x00\x00\x00\x00\x00\x00'
        >>> d.sizeof()
        10
    c                    ó   t t| ƒ |¡ || _d S r&   )rP  rA  rV   r2   )rU   r2   r†   rR  r	   r
   rV   Õ  rÅ  zFixedSized.__init__c                 C   sf   t | j|ƒ}|dk rtdƒ‚t||ƒ}| jtu r|S t| jƒtu r(| | jj	¡S | j 
t |¡||¡S ©Nr   rp  )r™   r2   r    r4   r†   rƒ  r/  rO  ré   r4  rÄ   r»   r¼   rÆ  r	   r	   r
   rÊ   Ù  s   

zFixedSized._parsec           
      C   s‚   t | j|ƒ}|dk rtdƒ‚t ¡ }| j ||||¡}| ¡ }|t|ƒ }	|	dk r3tdt|ƒ|f ƒ‚t	||ƒ t	|t
|	ƒƒ |S rs  )r™   r2   r    r»   r¼   r†   r×   rÕ   r0   r>   r2  )
rU   rÍ   r1   r˜   rÌ   r2   rl  r`  r3   r>  r	   r	   r
   r×   ä  s   
zFixedSized._buildc                 C   s    t | j|ƒ}|dk rtdƒ‚|S r›  )r™   r2   r    rÌ  r	   r	   r
   rÛ   ò  s   zFixedSized._sizeofc                 C   ó   d| j | j |¡f S )Nz+restream(read_bytes(io, %s), lambda io: %s))r2   r†   rã   rù   r	   r	   r
   r÷   ø  r;  zFixedSized._emitparsec                 C   s*   t ddt| jƒ dd¡i| j ||¡¤ŽS )Nr�  rL  rm   r	   )r  rS  r2   rv   r†   r(  r1  r	   r	   r
   r0  û  r|  zFixedSized._emitfulltyper‚  r	   r	   rR  r
   rA  »  s    rA  c                       sB   e Zd ZdZd‡ fdd„	Zdd„ Zd	d
„ Zdd„ Zdd„ Z‡  Z	S )rL  aQ  
    Restricts parsing to bytes preceding a null byte.

    Parsing reads one byte at a time and accumulates it with previous bytes. When term was found, (by default) consumes but discards the term. When EOF was found, (by default) raises same StreamError exception. Then subcon is parsed using new BytesIO made with said data. Building builds the subcon and then writes the term. Size is undefined.

    The term can be multiple bytes, to support string classes with UTF16/32 encodings.

    :param subcon: Construct instance
    :param term: optional, bytes, terminator byte-string, default is \x00 single null byte
    :param include: optional, bool, if to include terminator in resulting data, default is False
    :param consume: optional, bool, if to consume terminator or leave it in the stream, default is True
    :param require: optional, bool, if EOF results in failure or not, default is True

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises StreamError: encountered EOF but require is not disabled
    :raises PaddingError: terminator is less than 1 bytes in length

    Example::

        >>> d = NullTerminated(Byte)
        >>> d.parse(b'\xff\x00')
        255
        >>> d.build(255)
        b'\xff\x00'
    rQ  FTc                    ó,   t t| ƒ |¡ || _|| _|| _|| _d S r&   )rP  rL  rV   rK  ÚincludeÚconsumeÚrequire)rU   r†   rK  rž  rŸ  r   rR  r	   r
   rV     ó
   
zNullTerminated.__init__c                 C   sÄ   | j }t|ƒ}|dk rtdƒ‚d}	 zt||ƒ}W n ty&   | jr$‚ Y nw ||kr=| jr2||7 }| js<t|| dƒ n||7 }q| j	t
u rI|S t| j	ƒtu rW| | j	j¡S | j	 t |¡||¡S )NrK   z+NullTerminated term must be at least 1 byter8  )rK  r0   r    r4   r   r   rž  rŸ  rB   r†   rƒ  r/  rO  ré   r4  rÄ   r»   r¼   )rU   r1   r˜   rÌ   rK  r/  r3   rî  r	   r	   r
   rÊ   !  s4   üò
zNullTerminated._parsec                 C   s"   | j  ||||¡}t|| jƒ |S r&   )r†   r×   r>   rK  )rU   rÍ   r1   r˜   rÌ   r`  r	   r	   r
   r×   <  s   zNullTerminated._buildc                 C   rÎ   r&   rÝ   rÞ   r	   r	   r
   rÛ   A  rb  zNullTerminated._sizeofc                 C   s@   t | jƒdkr	t‚tdt| jƒ| j| j| jdœ| j 	||¡¤ŽS )NrK   )Ú
terminatorrž  rŸ  Ú	eos_errorr	   )
r0   rK  rÑ   r  r  rž  rŸ  r   r†   r(  r1  r	   r	   r
   r0  D  s   .zNullTerminated._emitfulltype)rQ  FTTrÈ  r	   r	   rR  r
   rL  ÿ  s    rL  c                       rÂ  )rB  aÀ  
    Restricts parsing to bytes except padding left of EOF.

    Parsing reads entire stream, then strips the data from right to left of null bytes, then parses subcon using new BytesIO made of said data. Building defers to subcon as-is. Size is undefined, because it reads till EOF.

    The pad can be multiple bytes, to support string classes with UTF16/32 encodings.

    :param subcon: Construct instance
    :param pad: optional, bytes, padding byte-string, default is \x00 single null byte

    :raises PaddingError: pad is less than 1 bytes in length

    Example::

        >>> d = NullStripped(Byte)
        >>> d.parse(b'\xff\x00\x00')
        255
        >>> d.build(255)
        b'\xff'
    rQ  c                    rÄ  r&   )rP  rB  rV   r>  )rU   r†   r>  rR  r	   r
   rV   `  rÅ  zNullStripped.__init__c           	      C   s  | j }t|ƒ}|dk rtdƒ‚t|ƒ}|dkr| |¡}nGt|ƒ| }t|ƒ}|r:|| d … |d |… kr:||8 }|| dkr^||| |… |kr^||8 }|| dkr^||| |… |ksJ|d |… }| jtu rk|S t| jƒtu ry| 	| jj
¡S | j t |¡||¡S )NrK   z(NullStripped pad must be at least 1 byter   )r>  r0   r    r7   rw   r†   rƒ  r/  rO  ré   r4  rÄ   r»   r¼   )	rU   r1   r˜   rÌ   r>  r/  r3   ÚtailunitrH   r	   r	   r
   rÊ   d  s(     ÿ
zNullStripped._parsec                 C   rU  r&   rV  rÚ   r	   r	   r
   r×   z  ro   zNullStripped._buildc                 C   rÎ   r&   rÝ   rÞ   r	   r	   r
   rÛ   }  rb  zNullStripped._sizeofc                 C   s4   t | jƒdkr	t‚tddt| jƒi| j ||¡¤ŽS )NrK   Ú	pad_rightr	   )r0   r>  rÑ   r  r  r†   r(  r1  r	   r	   r
   r0  €  s   "zNullStripped._emitfulltyperv  rÈ  r	   r	   rR  r
   rB  J  s    rB  c                       rM  )ÚRestreamDataa  
    Parses a field on external data (but does not build).

    Parsing defers to subcon, but provides it a separate BytesIO stream based on data provided by datafunc (a bytes literal or another BytesIO stream or Construct instances that returns bytes or context lambda). Building does nothing. Size is 0 because as far as other fields see it, this field does not produce or consume any bytes from the stream.

    :param datafunc: bytes or BytesIO or Construct instance (that parses into bytes) or context lambda, provides data for subcon to parse from
    :param subcon: Construct instance

    Can propagate any exception from the lambdas, possibly non-ConstructError.

    Example::

        >>> d = RestreamData(b"\x01", Int8ub)
        >>> d.parse(b"")
        1
        >>> d.build(0)
        b''

        >>> d = RestreamData(NullTerminated(GreedyBytes), Int16ub)
        >>> d.parse(b"\x01\x02\x00")
        0x0102
        >>> d = RestreamData(FixedSized(2, GreedyBytes), Int16ub)
        >>> d.parse(b"\x01\x02\x00")
        0x0102
    c                    s    t t| ƒ |¡ || _d| _d S ru  )rP  r¦  rV   Údatafuncr¡   )rU   r§  r†   rR  r	   r
   rV   ¡  r´  zRestreamData.__init__c                 C   s^   t | j|ƒ}t|tƒrt |¡}t|tjƒr|}t|tƒr't | |||¡¡}| j |||¡S r&   )	r™   r§  r:   r;   r»   r¼   rž   rÄ   r†   )rU   r1   r˜   rÌ   r3   rl  r	   r	   r
   rÊ   ¦  s   


zRestreamData._parsec                 C   r<  r&   r	   rÚ   r	   r	   r
   r×   °  rb  zRestreamData._buildc                 C   r†  rN   r	   rÞ   r	   r	   r
   rÛ   ³  rb  zRestreamData._sizeofc                 C   rœ  )Nzrestream(%r, lambda io: %s))r§  r†   rã   rù   r	   r	   r
   r÷   ¶  r;  zRestreamData._emitparserê  r	   r	   rR  r
   r¦  †  s    
r¦  c                       r6  )
r˜  a.  
    Transforms bytes between the underlying stream and the (fixed-sized) subcon.

    Parsing reads a specified amount (or till EOF), processes data using a bytes-to-bytes decoding function, then parses subcon using those data. Building does build subcon into separate bytes, then processes it using encoding bytes-to-bytes function, then writes those data into main stream. Size is reported as `decodeamount` or `encodeamount` if those are equal, otherwise its SizeofError.

    Used internally to implement :class:`~construct.core.Bitwise` :class:`~construct.core.Bytewise` :class:`~construct.core.ByteSwapped` :class:`~construct.core.BitsSwapped` .

    Possible use-cases include encryption, obfuscation, byte-level encoding.

    .. warning:: Remember that subcon must consume (or produce) an amount of bytes that is same as `decodeamount` (or `encodeamount`).

    .. warning:: Do NOT use seeking/telling classes inside Transformed context.

    :param subcon: Construct instance
    :param decodefunc: bytes-to-bytes function, applied before parsing subcon
    :param decodeamount: integer, amount of bytes to read
    :param encodefunc: bytes-to-bytes function, applied after building subcon
    :param encodeamount: integer, amount of bytes to write

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises StreamError: subcon build and encoder transformed more or less than `encodeamount` bytes, if amount is specified
    :raises StringError: building from non-bytes value, perhaps unicode

    Can propagate any exception from the lambdas, possibly non-ConstructError.

    Example::

        >>> d = Transformed(Bytes(16), bytes2bits, 2, bits2bytes, 2)
        >>> d.parse(b"\x00\x00")
        b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

        >>> d = Transformed(GreedyBytes, bytes2bits, None, bits2bytes, None)
        >>> d.parse(b"\x00\x00")
        b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    c                    r�  r&   )rP  r˜  rV   Ú
decodefuncÚdecodeamountÚ
encodefuncÚencodeamount)rU   r†   r¨  r©  rª  r«  rR  r	   r
   rV   ß  r¡  zTransformed.__init__c                 C   sz   t | jtd ƒƒrt|ƒ}t | jtƒrt|| jƒ}|  |¡}| jtu r$|S t| jƒt	u r2| 
| jj¡S | j t |¡||¡S r&   )r:   r©  r/  r7   rÉ  r4   r¨  r†   rƒ  rO  ré   r4  rÄ   r»   r¼   rj  r	   r	   r
   rÊ   æ  s   

zTransformed._parsec                 C   sj   t  ¡ }| j ||||¡}| ¡ }|  |¡}t| jtƒr.t	|ƒ| jkr.t
dt	|ƒ| jf ƒ‚t||ƒ |S )NzQencoding transformation produced wrong amount of bytes, %s instead of expected %s)r»   r¼   r†   r×   rÕ   rª  r:   r«  rÉ  r0   r   r>   rk  r	   r	   r
   r×   ò  s   

zTransformed._buildc                 C   s.   | j d u s
| jd u rt‚| j | jkr| jS t‚r&   )r©  r«  r   rÞ   r	   r	   r
   rÛ   ý  s
   zTransformed._sizeofrð  r	   r	   rR  r
   r˜  º  s    $r˜  c                       r6  )
r›  aE  
    Transforms bytes between the underlying stream and the (variable-sized) subcon.

    Used internally to implement :class:`~construct.core.Bitwise` :class:`~construct.core.Bytewise` :class:`~construct.core.ByteSwapped` :class:`~construct.core.BitsSwapped` .

    .. warning:: Remember that subcon must consume or produce an amount of bytes that is a multiple of encoding or decoding units. For example, in a Bitwise context you should process a multiple of 8 bits or the stream will fail during parsing/building.

    .. warning:: Do NOT use seeking/telling classes inside Restreamed context.

    :param subcon: Construct instance
    :param decoder: bytes-to-bytes function, used on data chunks when parsing
    :param decoderunit: integer, decoder takes chunks of this size
    :param encoder: bytes-to-bytes function, used on data chunks when building
    :param encoderunit: integer, encoder takes chunks of this size
    :param sizecomputer: function that computes amount of bytes outputed

    Can propagate any exception from the lambda, possibly non-ConstructError.
    Can also raise arbitrary exceptions in RestreamedBytesIO implementation.

    Example::

        Bitwise  <--> Restreamed(subcon, bits2bytes, 8, bytes2bits, 1, lambda n: n//8)
        Bytewise <--> Restreamed(subcon, bytes2bits, 1, bits2bytes, 8, lambda n: n*8)
    c                    ó2   t t| ƒ |¡ || _|| _|| _|| _|| _d S r&   )rP  r›  rV   ÚdecoderÚdecoderunitÚencoderÚencoderunitÚsizecomputer)rU   r†   r­  r®  r¯  r°  r±  rR  r	   r
   rV     ó   
zRestreamed.__init__c                 C   s4   t || j| j| j| jƒ}| j |||¡}| ¡  |S r&   )ÚRestreamedBytesIOr­  r®  r¯  r°  r†   rÄ   Úclose)rU   r1   r˜   rÌ   rl  rÍ   r	   r	   r
   rÊ   '  s   zRestreamed._parsec                 C   s6   t || j| j| j| jƒ}| j ||||¡}| ¡  |S r&   )r³  r­  r®  r¯  r°  r†   r×   r´  )rU   rÍ   r1   r˜   rÌ   rl  r`  r	   r	   r
   r×   -  s   zRestreamed._buildc                 C   s&   | j d u r	tdƒ‚|   | j ||¡¡S )Nz7Restreamed cannot calculate size without a sizecomputer)r±  r   r†   rÛ   rÞ   r	   r	   r
   rÛ   3  s   
zRestreamed._sizeofrð  r	   r	   rR  r
   r›    s    r›  c                       r6  )
Ú
ProcessXoraU  
    Transforms bytes between the underlying stream and the subcon.

    Used internally by KaitaiStruct compiler, when translating `process: xor` tags.

    Parsing reads till EOF, xors data with the pad, then feeds that data into subcon. Building first builds the subcon into separate BytesIO stream, xors data with the pad, then writes that data into the main stream. Size is the same as subcon, unless it raises SizeofError.

    :param padfunc: integer or bytes or context lambda, single or multiple bytes to xor data with
    :param subcon: Construct instance

    :raises StringError: pad is not integer or bytes

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = ProcessXor(0xf0 or b'\xf0', Int16ub)
        >>> d.parse(b"\x00\xff")
        0xf00f
        >>> d.sizeof()
        2
    c                    rš  r&   )rP  rµ  rV   Úpadfunc)rU   r¶  r†   rR  r	   r
   rV   R  rÅ  zProcessXor.__init__c                    s   t | j|ƒ‰ tˆ ttfƒstdƒ‚tˆ tƒr tˆ ƒdkr tˆ ƒ‰ t|ƒ}tˆ tƒr:ˆ dks:t	‡ fdd„t
|ƒD ƒƒ}tˆ tƒr`tˆ ƒdkrMˆ ttˆ ƒƒks`t	dd„ tt
|ƒt t
ˆ ƒ¡ƒD ƒƒ}| jtu rg|S t| jƒtu ru| | jj¡S | j t |¡||¡S )Nú%ProcessXor needs integer or bytes padrK   r   c                 3   ó   � | ]}|ˆ A V  qd S r&   r	   ©r^   rî  r=  r	   r
   re   _  ó   € z$ProcessXor._parse.<locals>.<genexpr>é@   c                 s   ó   � | ]	\}}||A V  qd S r&   r	   ©r^   rî  Úpr	   r	   r
   re   b  rf   )r™   r¶  r:   rÉ  r;   r   r0   r  r7   Úintegers2bytesrã  r2  r°  rÆ  Úcycler†   rƒ  r/  rO  ré   r4  rÄ   r»   r¼   rj  r	   r=  r
   rÊ   V  s"   

&
zProcessXor._parsec                    sè   t | j|ƒ‰ tˆ ttfƒstdƒ‚tˆ tƒr tˆ ƒdkr tˆ ƒ‰ t 	¡ }| j
 ||||¡}| ¡ }tˆ tƒrGˆ dksGt‡ fdd„t|ƒD ƒƒ}tˆ tƒrmtˆ ƒdkrZˆ ttˆ ƒƒksmtdd„ tt|ƒt tˆ ƒ¡ƒD ƒƒ}t||ƒ |S )Nr·  rK   r   c                 3   r¸  r&   r	   r¹  r=  r	   r
   re   t  rº  z$ProcessXor._build.<locals>.<genexpr>r»  c                 s   r¼  r&   r	   r½  r	   r	   r
   re   w  rf   )r™   r¶  r:   rÉ  r;   r   r0   r  r»   r¼   r†   r×   rÕ   r¿  rã  r2  r°  rÆ  rÀ  r>   rk  r	   r=  r
   r×   i  s    

&
zProcessXor._buildc                 C   rW  r&   rX  rÞ   r	   r	   r
   rÛ   {  rƒ   zProcessXor._sizeofrð  r	   r	   rR  r
   rµ  :  s    rµ  c                       sL   e Zd ZdZdd„ eddƒD ƒZ‡ fdd„Zdd	„ Zd
d„ Zdd„ Z	‡  Z
S )ÚProcessRotateLefta†  
    Transforms bytes between the underlying stream and the subcon.

    Used internally by KaitaiStruct compiler, when translating `process: rol/ror` tags.

    Parsing reads till EOF, rotates (shifts) the data *left* by amount in bits, then feeds that data into subcon. Building first builds the subcon into separate BytesIO stream, rotates *right* by negating amount, then writes that data into the main stream. Size is the same as subcon, unless it raises SizeofError.

    :param amount: integer or context lambda, shift by this amount in bits, treated modulo (group x 8)
    :param group: integer or context lambda, shifting is applied to chunks of this size in bytes
    :param subcon: Construct instance

    :raises RotationError: group is less than 1
    :raises RotationError: data length is not a multiple of group size

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = ProcessRotateLeft(4, 1, Int16ub)
        >>> d.parse(b'\x0f\xf0')
        0xf00f
        >>> d = ProcessRotateLeft(4, 2, Int16ub)
        >>> d.parse(b'\x0f\xf0')
        0xff00
        >>> d.sizeof()
        2
    c                    s$   i | ]‰ ˆ ‡ fd d„t dƒD ƒ“qS )c                    s$   g | ]}|ˆ > d @ |dˆ  ? B ‘qS )éÿ   r‹  r	   ©r^   r‚  ©Úamountr	   r
   r`   �  r|   z'ProcessRotateLeft.<dictcomp>.<listcomp>é   )r~  )r^   r	   rÄ  r
   r{   �  r|   zProcessRotateLeft.<dictcomp>rK   r‹  c                    s    t t| ƒ |¡ || _|| _d S r&   )rP  rÁ  rV   rÅ  Úgroup)rU   rÅ  rÇ  r†   rR  r	   r
   rV   Ÿ  r´  zProcessRotateLeft.__init__c                    sr  t | j|ƒ}t | j|ƒ‰ˆdk rtdƒ‚|ˆd  }|d ‰t|ƒ}t|ƒ‰t|ƒˆ dkr2tdƒ‚|dkr7nbˆdkrLtj| ‰t	‡fdd„ˆD ƒƒ}nM|d dkrq‡‡fdd	„t
ˆƒD ƒ‰t	‡‡fd
d„t
dt|ƒˆƒD ƒƒ}n(|d ‰ dˆ  ‰‡‡fdd	„t
ˆƒD ƒ‰t	‡ ‡‡‡fdd„t
dt|ƒˆƒD ƒƒ}| jtu r |S t| jƒtu r®| | jj¡S | j t |¡||¡S )NrK   ú)group size must be at least 1 to be validr‹  r   ú,data length must be a multiple of group sizec                 3   ó   � | ]}ˆ | V  qd S r&   r	   ©r^   Úa©Ú	translater	   r
   re   ·  rº  z+ProcessRotateLeft._parse.<locals>.<genexpr>c                    ó   g | ]}|ˆ  ˆ ‘qS r	   r	   rÃ  ©Úamount_bytesrÇ  r	   r
   r`   º  ra   z,ProcessRotateLeft._parse.<locals>.<listcomp>c                 3   ó&   � | ]}ˆD ]	}ˆ ||  V  qqd S r&   r	   ©r^   r‚  ry   ©Ú	data_intsÚindicesr	   r
   re   »  ra  c                    ó(   g | ]}|ˆ  ˆ |d  ˆ  ˆ f‘qS ©rK   r	   rÃ  rÐ  r	   r
   r`   À  ó   ( c                 3   óB   � | ]}ˆD ]\}}ˆ||  ˆ > d @ ˆ||  ˆ? B V  qqdS ©rÂ  Nr	   ©r^   r‚  Úk1Úk2©Úamount1Úamount2rÕ  Úindices_pairsr	   r
   re   Á  ó   €@ )r™   rÅ  rÇ  r#   r7   Úbytes2integersr0   rÁ  Úprecomputed_single_rotationsr¿  r~  r†   rƒ  r/  rO  ré   r4  rÄ   r»   r¼   )rU   r1   r˜   rÌ   rÅ  r3   r	   ©rà  rá  rÑ  rÕ  rÇ  rÖ  râ  rÎ  r
   rÊ   ¤  s6   
&(
zProcessRotateLeft._parsec           	         s\  t | j|ƒ}t | j|ƒ‰ˆdk rtdƒ‚| ˆd  }|d ‰t ¡ }| j ||||¡}| ¡ }t	|ƒ‰t
|ƒˆ dkr@tdƒ‚|dkrEnbˆdkrZtj| ‰t‡fdd„ˆD ƒƒ}nM|d dkr‡‡fdd	„tˆƒD ƒ‰t‡‡fd
d„tdt
|ƒˆƒD ƒƒ}n(|d ‰ dˆ  ‰‡‡fdd	„tˆƒD ƒ‰t‡ ‡‡‡fdd„tdt
|ƒˆƒD ƒƒ}t||ƒ |S )NrK   rÈ  r‹  r   rÉ  c                 3   rÊ  r&   r	   rË  rÍ  r	   r
   re   Þ  rº  z+ProcessRotateLeft._build.<locals>.<genexpr>c                    rÏ  r	   r	   rÃ  rÐ  r	   r
   r`   á  ra   z,ProcessRotateLeft._build.<locals>.<listcomp>c                 3   rÒ  r&   r	   rÓ  rÔ  r	   r
   re   â  ra  c                    r×  rØ  r	   rÃ  rÐ  r	   r
   r`   ç  rÙ  c                 3   rÚ  rÛ  r	   rÜ  rß  r	   r
   re   è  rã  )r™   rÅ  rÇ  r#   r»   r¼   r†   r×   rÕ   rä  r0   rÁ  rå  r¿  r~  r>   )	rU   rÍ   r1   r˜   rÌ   rÅ  rl  r`  r3   r	   ræ  r
   r×   É  s4   
&(
zProcessRotateLeft._buildc                 C   rW  r&   rX  rÞ   r	   r	   r
   rÛ   í  rƒ   zProcessRotateLeft._sizeof)r   r   r   rK  r~  rå  rV   rÊ   r×   rÛ   rY  r	   r	   rR  r
   rÁ    s    %$rÁ  c                       r6  )
ÚChecksumaP  
    Field that is build or validated by a hash of a given byte range. Usually used with :class:`~construct.core.RawCopy` .

    Parsing compares parsed subcon `checksumfield` with a context entry provided by `bytesfunc` and transformed by `hashfunc`. Building fetches the contect entry, transforms it, then writes is using subcon. Size is same as subcon.

    :param checksumfield: a subcon field that reads the checksum, usually Bytes(int)
    :param hashfunc: function that takes bytes and returns whatever checksumfield takes when building, usually from hashlib module
    :param bytesfunc: context lambda that returns bytes (or object) to be hashed, usually like this.rawcopy1.data

    :raises ChecksumError: parsing and actual checksum does not match actual data

    Can propagate any exception from the lambdas, possibly non-ConstructError.

    Example::

        import hashlib
        d = Struct(
            "fields" / RawCopy(Struct(
                Padding(1000),
            )),
            "checksum" / Checksum(Bytes(64),
                lambda data: hashlib.sha512(data).digest(),
                this.fields.data),
        )
        d.build(dict(fields=dict(value={})))

    ::

        import hashlib
        d = Struct(
            "offset" / Tell,
            "checksum" / Padding(64),
            "fields" / RawCopy(Struct(
                Padding(1000),
            )),
            "checksum" / Pointer(this.offset, Checksum(Bytes(64),
                lambda data: hashlib.sha512(data).digest(),
                this.fields.data)),
        )
        d.build(dict(fields=dict(value={})))
    c                    s*   t t| ƒ ¡  || _|| _|| _d| _d S ru  )rP  rç  rV   ÚchecksumfieldÚhashfuncÚ	bytesfuncr¡   )rU   rè  ré  rê  rR  r	   r
   rV     s
   
zChecksum.__init__c                 C   sj   | j  |||¡}|  |  |¡¡}||kr3tdt|tƒs|nt |¡t|tƒs+|f ƒ‚t |¡f ƒ‚|S )Nz$wrong checksum, read %r, computed %r)	rè  rÄ   ré  rê  r$   r:   r;   Úbinasciirä   )rU   r1   r˜   rÌ   Úhash1Úhash2r	   r	   r
   rÊ   #  s   þþzChecksum._parsec                 C   s&   |   |  |¡¡}| j ||||¡ |S r&   )ré  rê  rè  r×   )rU   rÍ   r1   r˜   rÌ   rí  r	   r	   r
   r×   ,  s   zChecksum._buildc                 C   rW  r&   )rè  rÛ   rÞ   r	   r	   r
   rÛ   1  rƒ   zChecksum._sizeofrð  r	   r	   rR  r
   rç  ñ  s    *	rç  c                       ó2   e Zd ZdZd	‡ fdd„	Zdd„ Zdd„ Z‡  ZS )
Ú
CompressedaC  
    Compresses and decompresses underlying stream when processing subcon. When parsing, entire stream is consumed. When building, puts compressed bytes without marking the end. This construct should be used with :class:`~construct.core.Prefixed` .

    Parsing and building transforms all bytes using a specified codec. Since data is processed until EOF, it behaves similar to `GreedyBytes`. Size is undefined.

    :param subcon: Construct instance, subcon used for storing the value
    :param encoding: string, any of module names like zlib/gzip/bzip2/lzma, otherwise any of codecs module bytes<->bytes encodings, each codec usually requires some Python version
    :param level: optional, integer between 0..9, although lzma discards it, some encoders allow different compression levels

    :raises ImportError: needed module could not be imported by ctor
    :raises StreamError: stream failed when reading until EOF

    Example::

        >>> d = Prefixed(VarInt, Compressed(GreedyBytes, "zlib"))
        >>> d.build(bytes(100))
        b'\x0cx\x9cc`\xa0=\x00\x00\x00d\x00\x01'

   Nc           	         sž   t t| ƒ |¡ || _|| _| jdkrdd l}|| _d S | jdkr*dd l}|| _d S | jdkr8dd l}|| _d S | jdkrFdd l	}|| _d S dd l
}|| _d S )NÚzlibr   ÚgzipÚbzip2Úlzma)rP  rï  rV   r4  Úlevelrð  Úlibrñ  Úbz2ró  Úcodecs)	rU   r†   r4  rô  rð  rñ  rö  ró  r÷  rR  r	   r
   rV   J  s"   








zCompressed.__init__c                 C   s&   | j dv r| j |¡S | j || j ¡S )N©rð  rñ  rò  ró  )r4  rõ  Ú
decompressré   rm  r	   r	   r
   r\  ^  s   
zCompressed._decodec                 C   sJ   | j dv r| jd u s| j dkr| j |¡S | j || j¡S | j || j ¡S )Nrø  ró  )r4  rô  rõ  Úcompressrç   rm  r	   r	   r
   r^  c  s
   
zCompressed._encoder&   ©r   r   r   rK  rV   r\  r^  rY  r	   r	   rR  r
   rï  5  s
    rï  c                       rî  )
Ú
Rebuffereda^  
    Caches bytes from underlying stream, so it becomes seekable and tellable, and also becomes blocking on reading. Useful for processing non-file streams like pipes, sockets, etc.

    .. warning:: Experimental implementation. May not be mature enough.

    :param subcon: Construct instance, subcon which will operate on the buffered stream
    :param tailcutoff: optional, integer, amount of bytes kept in buffer, by default buffers everything

    Can also raise arbitrary exceptions in its implementation.

    Example::

        Rebuffered(..., tailcutoff=1024).parse_stream(nonseekable_stream)
    Nc                    s"   t t| ƒ |¡ td |d�| _d S )N)Ú
tailcutoff)rP  rü  rV   ÚRebufferedBytesIOrl  )rU   r†   rý  rR  r	   r
   rV   |  rÛ  zRebuffered.__init__c                 C   s   || j _| j | j ||¡S r&   )rl  Ú	substreamr†   rÄ   rÒ   r	   r	   r
   rÊ   €  s   zRebuffered._parsec                 C   s   || j _| j || j ||¡S r&   )rl  rÿ  r†   r×   rÚ   r	   r	   r
   r×   „  s   zRebuffered._buildr&   rI  r	   r	   rR  r
   rü  l  s
    rü  c                       rG  )ÚLazya  
    Lazyfies a field.

    This wrapper allows you to do lazy parsing of individual fields inside a normal Struct (without using LazyStruct which may not work in every scenario). It is also used by KaitaiStruct compiler to emit `instances` because those are not processed greedily, and they may refer to other not yet parsed fields. Those are 2 entirely different applications but semantics are the same.

    Parsing saves the current stream offset and returns a lambda. If and when that lambda gets evaluated, it seeks the stream to then-current position, parses the subcon, and seeks the stream back to previous position. Building evaluates that lambda into an object (if needed), then defers to subcon. Size also defers to subcon.

    :param subcon: Construct instance

    :raises StreamError: requested reading negative amount, could not read enough bytes, requested writing different amount than actual data, or could not write all bytes
    :raises StreamError: stream is not seekable and tellable

    Example::

        >>> d = Lazy(Byte)
        >>> x = d.parse(b'\x00')
        >>> x
        <function construct.core.Lazy._parse.<locals>.execute>
        >>> x()
        0
        >>> d.build(0)
        b'\x00'
        >>> d.build(x)
        b'\x00'
        >>> d.sizeof()
        1
    c                    s   t t| ƒ |¡ d S r&   )rP  r   rV   rQ  rR  r	   r
   rV   ©  rš   zLazy.__init__c                    s    t ˆƒ‰‡ ‡‡‡‡fdd„}|S )Nc                     s0   t ˆƒ} tˆˆƒ ˆj ˆˆ ˆ¡}tˆ| ƒ |S r&   )rD   rB   r†   rÄ   )rG   rÍ   ©r˜   r@   rÌ   rU   r1   r	   r
   Úexecute®  s
   

zLazy._parse.<locals>.executerˆ  )rU   r1   r˜   rÌ   r  r	   r  r
   rÊ   ¬  s   zLazy._parsec                 C   s    t |ƒr|ƒ }| j ||||¡S r&   )r–   r†   r×   rÚ   r	   r	   r
   r×   ¶  s   zLazy._buildrI  r	   r	   rR  r
   r   Œ  s
    
r   c                   @   s\   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
eZdd„ Zdd„ ZdS )ÚLazyContainerró   c                 C   s(   || _ || _|| _|| _|| _|| _d S r&   )Ú_structÚ_streamÚ_offsetsÚ_valuesÚ_contextÚ_path)rU   r¦  r1   Úoffsetsr\  r˜   rÌ   r	   r	   r
   rV   ¿  s   
zLazyContainer.__init__c                 C   s   || j jv r
| | S t‚r&   )r  Ú_subconsindexesr|  r3  r	   r	   r
   rk  Ç  s   zLazyContainer.__getattr__c                 C   sf   t |tƒr| jj| }|| jv r| j| S t| j| j| ƒ | jj|  	| j| j
| j¡}|| j|< |S r&   )r:   r:  r  r  r  rB   r  r  rŒ   rÄ   r  r	  ©rU   rD  rþ  r	   r	   r
   rJ  Ì  s   



zLazyContainer.__getitem__c                 C   ó   t | jjƒS r&   )r0   r  rŒ   rT   r	   r	   r
   Ú__len__Ö  r�   zLazyContainer.__len__c                 C   r  r&   )Úiterr  r�  rT   r	   r	   r
   ÚkeysÙ  r�   zLazyContainer.keysc                    ó   ‡ fdd„ˆ j jD ƒS )Nc                 3   rÊ  r&   r	   ©r^   ry   rT   r	   r
   re   Ý  rº  z'LazyContainer.values.<locals>.<genexpr>©r  r�  rT   r	   rT   r
   r\  Ü  r;  zLazyContainer.valuesc                    r  )Nc                 3   s   � | ]	}|ˆ | fV  qd S r&   r	   r  rT   r	   r
   re   à  rf   z&LazyContainer.items.<locals>.<genexpr>r  rT   r	   rT   r
   r}   ß  r;  zLazyContainer.itemsc                 C   s   t  | |¡S r&   )r¿   Ú__eq__r;  r	   r	   r
   r  ä  r�   zLazyContainer.__eq__c                 C   s   dt | jƒt | jjƒf S )Nz,<LazyContainer: %s items cached, %s subcons>)r0   r  r  rŒ   rT   r	   r	   r
   r¨   ç  rV  zLazyContainer.__repr__N)r   r   r   rK  rV   rk  rJ  r  r  r\  r}   Ú__iter__r  r¨   r	   r	   r	   r
   r  ¼  s    
r  c                       rM  )r‹   a  
    Equivalent to :class:`~construct.core.Struct`, but when this class is parsed, most fields are not parsed (they are skipped if their size can be measured by _actualsize or _sizeof method). See its docstring for details.

    Fields are parsed depending on some factors:

    * Some fields like Int* Float* Bytes(5) Array(5,Byte) Pointer are fixed-size and are therefore skipped. Stream is not read.
    * Some fields like Bytes(this.field) are variable-size but their size is known during parsing when there is a corresponding context entry. Those fields are also skipped. Stream is not read.
    * Some fields like Prefixed PrefixedArray PascalString are variable-size but their size can be computed by partially reading the stream. Only first few bytes are read (the lengthfield).
    * Other fields like VarInt need to be parsed. Stream position that is left after the field was parsed is used.
    * Some fields may not work properly, due to the fact that this class attempts to skip fields, and parses them only out of necessity. Miscellaneous fields often have size defined as 0, and fixed sized fields are skippable.

    Note there are restrictions:

    * If a field like Bytes(this.field) references another field in the same struct, you need to access the referenced field first (to trigger its parsing) and then you can access the Bytes field. Otherwise it would fail due to missing context entry.
    * If a field references another field within inner (nested) or outer (super) struct, things may break. Context is nested, but this class was not rigorously tested in that manner.

    Building and sizeof are greedy, like in Struct.

    :param \*subcons: Construct instances, list of members, some can be anonymous
    :param \*\*subconskw: Construct instances, list of members (requires Python 3.6)
    c                    s€   t t| ƒ ¡  t|ƒtdd„ | ¡ D ƒƒ }t|Ž | _tdd„ | jD ƒƒ| _tdd„ t	| jƒD ƒƒ| _
tdd„ | jD ƒƒ| _d S )Nc                 s   rˆ  r&   r	   rx   r	   r	   r
   re     rf   z&LazyStruct.__init__.<locals>.<genexpr>c                 s   r‰  r&   rŠ  r‹  r	   r	   r
   re     r{  c                 s   s$   � | ]\}}|j r|j |fV  qd S r&   rŠ  rC  r	   r	   r
   re     s   €" c                 s   rŒ  r&   r�  r‹  r	   r	   r
   re     rŽ  )rP  r‹   rV   r¤  r}   r”   rŒ   r¿   r�  r¯  r  r�  r¡   r‘  rR  r	   r
   rV     s   
zLazyStruct.__init__c                 C   r”  r&   r•  r3  r	   r	   r
   rk  
  r–  zLazyStruct.__getattr__c           
      C   sä   t ||jd |j|j|j| j|| dd ¡d�	}|j d|¡|_t	|ƒ}d|i}i }t
| jƒD ];\}}z|| |||¡7 }t||ƒ W n  tya   | |||¡}	|	||< |jr[|	||j< t	|ƒ}Y nw |||d < q-t| |||||ƒS )Nr˜  r™  rš  r   rK   )r¿   rÃ   rÀ   rÁ   rÂ   r�  r  rt   rš  rD   r¯  rŒ   rà   rB   r   rÄ   rŸ   r  )
rU   r1   r˜   rÌ   r@   r
  r\  r‚  rŽ   rþ  r	   r	   r
   rÊ     s$   ,
ûzLazyStruct._parsec                 C   r�  r—  rž  rŸ  r	   r	   r
   r×   "  s*   ,




€þzLazyStruct._buildc                    r   )Nr˜  r™  rš  c                 3   r¡  r&   rß   r‹  r¢  r	   r
   re   ?  rf   z%LazyStruct._sizeof.<locals>.<genexpr>rz  r£  rÞ   r	   r¢  r
   rÛ   :  s   ,ÿzLazyStruct._sizeof)
r   r   r   rK  rV   rk  rÊ   r×   rÛ   rY  r	   r	   rR  r
   r‹   ë  s    r‹   c                   @   sH   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dS )ÚLazyListContainerró   c                 C   s.   || _ || _|| _|| _|| _|| _|| _d S r&   )Ú_subconr  Ú_countr  r  r  r	  )rU   r†   r1   rI  r
  r\  r˜   rÌ   r	   r	   r
   rV   G  s   
zLazyListContainer.__init__c                    sr   t |tƒr‡ fdd„t| ˆ j¡Ž D ƒS |ˆ jv rˆ j| S tˆ jˆ j| ƒ ˆ j	 
ˆ jˆ jˆ j¡}|ˆ j|< |S )Nc                    s   g | ]}ˆ | ‘qS r	   r	   rÃ  rT   r	   r
   r`   R  r€   z1LazyListContainer.__getitem__.<locals>.<listcomp>)r:   rG  r~  rÖ  r  r  rB   r  r  r  rÄ   r  r	  r  r	   rT   r
   rJ  P  s   



zLazyListContainer.__getitem__c                 C   s    |t jkr| j}|  t||ƒ¡S r&   )r»  Úmaxsizer  rJ  rG  )rU   ÚstartÚstopr	   r	   r
   Ú__getslice__Z  s   
zLazyListContainer.__getslice__c                 C   r¬  r&   )r  rT   r	   r	   r
   r  _  r­  zLazyListContainer.__len__c                    s   ‡ fdd„t ˆ jƒD ƒS )Nc                 3   rÊ  r&   r	   rÃ  rT   r	   r
   re   c  rº  z-LazyListContainer.__iter__.<locals>.<genexpr>)r~  r  rT   r	   rT   r
   r  b  ru  zLazyListContainer.__iter__c                    s.   t ˆƒt ˆ ƒkot‡ ‡fdd„tˆjƒD ƒƒS )Nc                 3   s    � | ]}ˆ| ˆ | kV  qd S r&   r	   rÃ  ©r<  rU   r	   r
   re   f  r{  z+LazyListContainer.__eq__.<locals>.<genexpr>)r0   r�  r~  r  r;  r	   r  r
   r  e  s   .zLazyListContainer.__eq__c                 C   s   dt | jƒ| jf S )Nz*<LazyListContainer: %s of %s items cached>)r0   r  r  rT   r	   r	   r
   r¨   h  rš   zLazyListContainer.__repr__N)r   r   r   rK  rV   rJ  r  r  r  r  r¨   r	   r	   r	   r
   r  D  s    	
r  c                       r6  )
Ú	LazyArrayaü  
    Equivalent to :class:`~construct.core.Array`, but the subcon is not parsed when possible (it gets skipped if the size can be measured by _actualsize or _sizeof method). See its docstring for details.

    Fields are parsed depending on some factors:

    * Some fields like Int* Float* Bytes(5) Array(5,Byte) Pointer are fixed-size and are therefore skipped. Stream is not read.
    * Some fields like Bytes(this.field) are variable-size but their size is known during parsing when there is a corresponding context entry. Those fields are also skipped. Stream is not read.
    * Some fields like Prefixed PrefixedArray PascalString are variable-size but their size can be computed by partially reading the stream. Only first few bytes are read (the lengthfield).
    * Other fields like VarInt need to be parsed. Stream position that is left after the field was parsed is used.
    * Some fields may not work properly, due to the fact that this class attempts to skip fields, and parses them only out of necessity. Miscellaneous fields often have size defined as 0, and fixed sized fields are skippable.

    Note there are restrictions:

    * If a field references another field within inner (nested) or outer (super) struct, things may break. Context is nested, but this class was not rigorously tested in that manner.

    Building and sizeof are greedy, like in Array.

    :param count: integer or context lambda, strict amount of elements
    :param subcon: Construct instance, subcon to process individual elements
    c                    rš  r&   )rP  r  rV   rI  )rU   rI  r†   rR  r	   r
   rV   ‚  rÅ  zLazyArray.__init__c              	   C   sÆ   | j }| j}t|ƒr||ƒ}d|kstd|f ƒ‚t|ƒ}d|i}i }t|ƒD ]1}	z|| |||¡7 }t||ƒ W n tyQ   | 	|||¡}
|
||	< t|ƒ}Y nw |||	d < q't
|||||||ƒS )Nr   rµ  rK   )r†   rI  r–   r   rD   r~  rà   rB   r   rÄ   r  )rU   r1   r˜   rÌ   rŽ   rI  r@   r
  r\  r‚  rþ  r	   r	   r
   rÊ   †  s(   ýzLazyArray._parsec           
      C   r·  r¸  r¹  rº  r	   r	   r
   r×   ›  s   zLazyArray._buildc              	   C   r»  ry  r¼  r½  r	   r	   r
   rÛ   «  s   €ÿzLazyArray._sizeofrð  r	   r	   rR  r
   r  l  s    r  c                       rG  )Ú	LazyBounda–  
    Field that binds to the subcon only at runtime (during parsing and building, not ctor). Useful for recursive data structures, like linked-lists and trees, where a construct needs to refer to itself (while it does not exist yet in the namespace).

    Note that it is possible to obtain same effect without using this class, using a loop. However there are usecases where that is not possible (if remaining nodes cannot be sized-up, and there is data following the recursive structure). There is also a significant difference, namely that LazyBound actually does greedy parsing while the loop does lazy parsing. See examples.

    To break recursion, use `If` field. See examples.

    :param subconfunc: parameter-less lambda returning Construct instance, can also return itself

    Example::

        d = Struct(
            "value" / Byte,
            "next" / If(this.value > 0, LazyBound(lambda: d)),
        )
        >>> print(d.parse(b"\x05\x09\x00"))
        Container:
            value = 5
            next = Container:
                value = 9
                next = Container:
                    value = 0
                    next = None

    ::

        d = Struct(
            "value" / Byte,
            "next" / GreedyBytes,
        )
        data = b"\x05\x09\x00"
        while data:
            x = d.parse(data)
            data = x.next
            print(x)
        # print outputs
        Container:
            value = 5
            next = \t\x00 (total 2)
        # print outputs
        Container:
            value = 9
            next = \x00 (total 1)
        # print outputs
        Container:
            value = 0
            next =  (total 0)
    c                    ru  r&   )rP  r  rV   Ú
subconfunc)rU   r   rR  r	   r
   rV   è  rv  zLazyBound.__init__c                 C   s   |   ¡ }| |||¡S r&   )r   rÄ   )rU   r1   r˜   rÌ   rŽ   r	   r	   r
   rÊ   ì  s   zLazyBound._parsec                 C   s   |   ¡ }| ||||¡S r&   )r   r×   )rU   rÍ   r1   r˜   rÌ   rŽ   r	   r	   r
   r×   ð  s   zLazyBound._buildrI  r	   r	   rR  r
   r  ¶  s
    1r  c                       r×  )ÚExprAdapteraJ  
    Generic adapter that takes `decoder` and `encoder` lambdas as parameters. You can use ExprAdapter instead of writing a full-blown class deriving from Adapter when only a simple lambda is needed.

    :param subcon: Construct instance, subcon to adapt
    :param decoder: lambda that takes (obj, context) and returns an decoded version of obj
    :param encoder: lambda that takes (obj, context) and returns an encoded version of obj

    Example::

        >>> d = ExprAdapter(Byte, obj_+1, obj_-1)
        >>> d.parse(b'\x04')
        5
        >>> d.build(5)
        b'\x04'
    c                    s0   t t| ƒ |¡ ‡ fdd„| _‡fdd„| _d S )Nc                    ó
   ˆ | |ƒS r&   r	   ©rÍ   ÚctxrÌ   )r­  r	   r
   r)   
  r  z&ExprAdapter.__init__.<locals>.<lambda>c                    r"  r&   r	   r#  ©r¯  r	   r
   r)     r  ©rP  r!  rV   r\  r^  )rU   r†   r­  r¯  rR  )r­  r¯  r
   rV     ó   zExprAdapter.__init__rÙ  r	   r	   rR  r
   r!  ø  ó    r!  c                       r×  )ÚExprSymmetricAdapteru  
    Macro around :class:`~construct.core.ExprAdapter`.

    :param subcon: Construct instance, subcon to adapt
    :param encoder: lambda that takes (obj, context) and returns both encoded version and decoded version of obj

    Example::

        >>> d = ExprSymmetricAdapter(Byte, obj_ & 0b00001111)
        >>> d.parse(b"Ã¿")
        15
        >>> d.build(255)
        b''
    c                    s0   t t| ƒ |¡ ‡ fdd„| _‡ fdd„| _d S )Nc                    r"  r&   r	   r#  r%  r	   r
   r)     r  z/ExprSymmetricAdapter.__init__.<locals>.<lambda>c                    r"  r&   r	   r#  r%  r	   r
   r)      r  r&  )rU   r†   r¯  rR  r%  r
   rV     r'  zExprSymmetricAdapter.__init__rÙ  r	   r	   rR  r
   r)    s    r)  c                       r×  )ÚExprValidatora  
    Generic adapter that takes `validator` lambda as parameter. You can use ExprValidator instead of writing a full-blown class deriving from Validator when only a simple lambda is needed.

    :param subcon: Construct instance, subcon to adapt
    :param validator: lambda that takes (obj, context) and returns a bool

    Example::

        >>> d = ExprValidator(Byte, obj_ & 0b11111110 == 0)
        >>> d.build(1)
        b'\x01'
        >>> d.build(88)
        ValidationError: object failed validation: 88

    c                    s"   t t| ƒ |¡ ‡ fdd„| _d S )Nc                    r"  r&   r	   r#  ©Ú	validatorr	   r
   r)   5  r  z(ExprValidator.__init__.<locals>.<lambda>)rP  r*  rV   rg  )rU   r†   r,  rR  r+  r
   rV   3  rÛ  zExprValidator.__init__rÙ  r	   r	   rR  r
   r*  #  r(  r*  c                    ó   t | ‡ fdd„ƒS )a7  
    Validates that the object is one of the listed values, both during parsing and building.

    .. note:: For performance, `valids` should be a set/frozenset.

    :param subcon: Construct instance, subcon to validate
    :param valids: collection implementing __contains__, usually a list or set

    :raises ValidationError: parsed or build value is not among valids

    Example::

        >>> d = OneOf(Byte, [1,2,3])
        >>> d.parse(b"\x01")
        1
        >>> d.parse(b"\xff")
        construct.core.ValidationError: object failed validation: 255
    c                    s   | ˆ v S r&   r	   ©rÍ   r$  ©Úvalidsr	   r
   r)   K  r�  zOneOf.<locals>.<lambda>©r*  )r†   r0  r	   r/  r
   ÚOneOf8  s   r2  c                    r-  )az  
    Validates that the object is none of the listed values, both during parsing and building.

    .. note:: For performance, `valids` should be a set/frozenset.

    :param subcon: Construct instance, subcon to validate
    :param invalids: collection implementing __contains__, usually a list or set

    :raises ValidationError: parsed or build value is among invalids

    c                    s   | ˆ vS r&   r	   r.  ©Úinvalidsr	   r
   r)   Z  r�  zNoneOf.<locals>.<lambda>r1  )r†   r4  r	   r3  r
   ÚNoneOfN  s   r5  c                    s   t |‡ fdd„ƒS )aÚ  
    Filters a list leaving only the elements that passed through the predicate.

    :param subcon: Construct instance, usually Array GreedyRange Sequence
    :param predicate: lambda that takes (obj, context) and returns a bool

    Can propagate any exception from the lambda, possibly non-ConstructError.

    Example::

        >>> d = Filter(obj_ != 0, Byte[:])
        >>> d.parse(b"\x00\x02\x00")
        [2]
        >>> d.build([0,1,0,2,0])
        b'\x01\x02'
    c                    s   ‡ ‡fdd„| D ƒS )Nc                    s   g | ]	}ˆ|ˆ ƒr|‘qS r	   r	   )r^   r+   )r$  rÊ  r	   r
   r`   n  s    z,Filter.<locals>.<lambda>.<locals>.<listcomp>r	   r.  rÐ  )r$  r
   r)   n  r€   zFilter.<locals>.<lambda>)r)  )rÊ  r†   r	   rÐ  r
   ÚFilter]  s   r6  c                       s2   e Zd ZdZd
‡ fdd„	Zdd„ Zdd	„ Z‡  ZS )ÚSlicinga¢  
    Adapter for slicing a list. Works with GreedyRange and Sequence.

    :param subcon: Construct instance, subcon to slice
    :param count: integer, expected number of elements, needed during building
    :param start: integer for start index (or None for entire list)
    :param stop: integer for stop index (or None for up-to-end)
    :param step: integer, step (or 1 for every element)
    :param empty: object, value to fill the list with, during building

    Example::

        d = Slicing(Array(4,Byte), 4, 1, 3, empty=0)
        assert d.parse(b"\x01\x02\x03\x04") == [2,3]
        assert d.build([2,3]) == b"\x00\x02\x03\x00"
        assert d.sizeof() == 4
    rK   Nc                    r¬  r&   )rP  r7  rV   rI  r  r  ÚstepÚempty)rU   r†   rI  r  r  r8  r9  rR  r	   r
   rV   ƒ  r²  zSlicing.__init__c                 C   s   || j | j| j… S r&   )r  r  r8  ra  r	   r	   r
   r\  Š  rš   zSlicing._decodec                 C   sb   | j d u r|S | jd u r| jg| j }||| j d | j…< |S | jg| j }||| j | j| j…< |S r&   )r  r  r9  rI  r8  ©rU   rÍ   r˜   rÌ   r!  r	   r	   r
   r^  Œ  s   

þzSlicing._encode)rK   Nrû  r	   r	   rR  r
   r7  q  s
    r7  c                       rî  )
ÚIndexingaM  
    Adapter for indexing a list (getting a single item from that list). Works with Range and Sequence and their lazy equivalents.

    :param subcon: Construct instance, subcon to index
    :param count: integer, expected number of elements, needed during building
    :param index: integer, index of the list to get
    :param empty: object, value to fill the list with, during building

    Example::

        d = Indexing(Array(4,Byte), 4, 2, empty=0)
        assert d.parse(b"\x01\x02\x03\x04") == 3
        assert d.build(3) == b"\x00\x00\x03\x00"
        assert d.sizeof() == 4
    Nc                    s&   t t| ƒ |¡ || _|| _|| _d S r&   )rP  r;  rV   rI  rD  r9  )rU   r†   rI  rD  r9  rR  r	   r
   rV   ¨  s   
zIndexing.__init__c                 C   s
   || j  S r&   )rD  ra  r	   r	   r
   r\  ­  rŠ  zIndexing._decodec                 C   s   | j g| j }||| j< |S r&   )r9  rI  rD  r:  r	   r	   r
   r^  ¯  s   
zIndexing._encoder&   rû  r	   r	   rR  r
   r;  ˜  s
    r;  r&   r†  rv  )Òr¦  r»   rë  rÆ  r  r  r»  ÚosÚtempfilerå   Ú	importlibrê   Úconstruct.libÚconstruct.exprÚconstruct.versionr/   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r,   r4   r7   r>   rB   rD   rI   rL   rM   rp   r   r‚   r”   r•   r™   rœ   r¶   rž   rN  r[  rd  rf  ri  rn  rt  rƒ  rž  r¡  r¢  rÁ  rÔ  rÝ  rà  rá  ræ  ré  rë  rí  rï  rñ  rò  rô  rõ  rö  r÷  rø  rù  rú  rû  rü  rý  rþ  rÿ  r   r  r  r  r  ÚByteÚShortÚIntÚLongr  r  r  r  r	  r
  ÚSingleÚDoubler¼  r  r  r  r  r  r  r  r  r  r1  r5  r7  rC  rJ  rN  rO  rP  r  rW  rF  rX  r_  rp  rr  rƒ  r‡   rˆ   rH  rÃ  rÉ  r…   r„   rá  rä  rë  rñ  rõ  rö  rû  r‰   r   r  r  r6  r8  r>  rŠ   rH  rK  rR  rQ  rX  rf  rg  rm  rl  rw  r}  r4  r~  r�  r‚  r‡  rJ  rŠ  r‹  r�  r’  rI  r™  rA  rL  rB  r¦  r˜  r›  rµ  rÁ  rç  rï  rü  r   r  r‹   r¤  r  r  r  r!  r)  r*  r2  r5  r6  r7  r;  r	   r	   r	   r
   Ú<module>   sø  `   K>(+JRU







































5

üS
^-  
M@X>@4+/0,$zDF<: ,:=I.5'SFF;1$$"6L,DK<4K5ErD7 0/Y(JB'