U
    
W[Z                  )   @   s  d Z ddlmZmZ ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlmZ ddlZddlmZmZ e	jdk rdZndZe	jd	krdZndZe	jd
krdZndZe dkrdZndZdd Zepe Zd}ddZdd Zdd Zz
ej W n ek
r   de_Y nX zeejd W n* eeej fk
rR   ee_ee_Y nX e!Z"erd["[[e#Z#e$Z$zddl%m&Z& W n e'k
r   e&Z&Y nX d~ddZ(ze)Z)W n ek
r   dd Z)Y nX dd Z*ere+Z,e-Z.ne,Z,e.Z.e,fddZ/dd  Z0d!d" Z1erd#d$ Z2ne3d% d&e2_ er8dd'lm4Z5 ndd(lm6Z5 ernd)d* Z7d+d, Z8dd-d.Z9d/d0 Z:nd1d* Z7d2d, Z8e;Z9d3d0 Z:d4e7_ d5e8_ d6e:_ ze<Z=W n ek
r   e+Z=Y nX zdd7lm>Z> W n e'k
r   e?Z>Y nX zdd8lm@Z@ W n e'k
r   eZ@Y nX er\ddlAmBZC dd9lDmEZE dd:lAmFZG dd;lAmHZI dd<lJmKZL n4ddlMZCdd9lNmEZE dd:lOmFZG dd;lOmHZI ddlLZLerd=d> ZPd?d@ ZQdAdB ZReSZSeSZTeUZVn0dCd> ZPdDd@ ZQdEdB ZReTZSeTZTddFlWmVZV eV dGeP_ dHeQ_ dIeR_ dJdK ZXdLdM ZYdNdO ZZddPl[m\Z\ ddQl]m^Z^ ddRl_m`Z` e^e\dSdTdUddVdWdX errddYlambZc ddZlamdZe ndd[lamfZc dd\lamgZe d]d^ Zhzdd_l	miZi W n e'k
r   eiZiY nX d`da ZjerekZlemZnnelZlenZndbdc Zoere
j
Zpne
jqZpzdddlrmsZs W n" e'k
r,   dddl_msZs Y nX ddedfZtd$ddgdhdidddXd djd0dkd*d,d.dldmdndBd>d@dodpdqdMdrdsdtdudKdvdwd^dadcdxdydzd{dfd|g)ZudS )a)  
Compatibility module to provide backwards compatibility for useful Python
features.

This is mainly for use of internal Twisted code. We encourage you to use
the latest version of Python directly from your code, if possible.

@var unicode: The type of Unicode strings, C{unicode} on Python 2 and C{str}
    on Python 3.

@var NativeStringIO: An in-memory file-like object that operates on the native
    string type (bytes in Python 2, unicode in Python 3).

@var urllib_parse: a URL-parsing module (urlparse on Python 2, urllib.parse on
    Python 3)
    )absolute_importdivisionN)
MethodType)
TextIOBaseIOBase)   r   FT)r      r   )r      r   ZPyPyc                  C   s"   t jdd} | dkrdS dS dS )a-  
    Returns whether or not we should enable the new-style conversion of
    old-style classes. It inspects the environment for C{TWISTED_NEWSTYLE},
    accepting an empty string, C{no}, C{false}, C{False}, and C{0} as falsey
    values and everything else as a truthy value.

    @rtype: L{bool}
    ZTWISTED_NEWSTYLE )r
   ZnoZfalseFalse0FTN)osenvironget)value r   7/usr/lib/python3/dist-packages/twisted/python/compat.py_shouldEnableNewStyle=   s    	r   c                 C   s$   t  }t| d D ]
}|j}q|S )a  
    In Python 3, L{inspect.currentframe} does not take a stack-level argument.
    Restore that functionality from Python 2 so we don't have to re-implement
    the C{f_back}-walking loop in places where it's called.

    @param n: The number of stack levels above the caller to walk.
    @type n: L{int}

    @return: a frame, n levels up the stack from the caller.
    @rtype: L{types.FrameType}
       )inspectcurrentframerangef_back)nfxr   r   r   r   Q   s    r   c           	      C   s  |st d| tjkr t|S | ttddkrd|kr^|ddksV|ddkr^t d|dd }|d}|d}d|d	 k}t|d
| ks|dkrt d|dkrdS |r@dgd
t| | |  }|	dr||dd< n4|
dr
||dd< n|d}||||d < t|d
| krZt dnt|d
| krZt d|r|d	 ddkr|t dt|d	 }td|}dd |D |d	d< dd |D }tjd| S tdddS )a,  
    Emulator of L{socket.inet_pton}.

    @param af: An address family to parse; C{socket.AF_INET} or
        C{socket.AF_INET6}.
    @type af: L{int}

    @param addr: An address.
    @type addr: native L{str}

    @return: The binary packed version of the passed address.
    @rtype: L{bytes}
    z-illegal IP address string passed to inet_ptonAF_INET6%r   r   :r
   .   r   zSyntactically invalid addressz                r   ::N   z!HHc                 S   s   g | ]}t |d d qS r#   Nhex.0r   r   r   r   
<listcomp>   s     zinet_pton.<locals>.<listcomp>c                 S   s   g | ]}t |d qS )   )intr(   r   r   r   r*      s     !8Ha   (Address family not supported by protocol)r-   )
ValueErrorsocketAF_INETZ	inet_atongetattrcountindexsplitlen
startswithendswithstructunpackZpackerror)	afaddrpartsZelidedZipv4ComponentZzerosidxZrawipv4Zunpackedipv4r   r   r   	inet_ptond   sH    

$




rA   c                 C   s>  | t jkrt |S | t jkr.t|dkr4tdtd|}d  }}tdD ]N}|| sv|d krl|}d}|d7 }qP|d k	rPd }|d ks||kr|}|}d }qP|d k	r|d ks||kr|}|}dd |D }|d k	rd	g|||| < |d d	kr|	dd	 |d
 d	kr$|	t|d d	 d
|S t ddd S )Nr+   zaddress length incorrectr-   r!   r   r   c                 S   s   g | ]}t |d d qS r%   r&   r(   r   r   r   r*      s     zinet_ntop.<locals>.<listcomp>r
   r    r   r.   r/   )r1   r2   Z	inet_ntoar   r7   r0   r:   r;   r   insertjoinr<   )r=   r>   r?   ZcurBaseZbestBaseiZcurLenZbestLenr   r   r   	inet_ntop   s>    



rE   r   r"   )reducec              	   C   sF   |dkr|}t | d}| }W 5 Q R X t|| d}t||| dS )az  
    Execute a Python script in the given namespaces.

    Similar to the execfile builtin, but a namespace is mandatory, partly
    because that's a sensible thing to require, and because otherwise we'd
    have to do some frame hacking.

    This is a compatibility implementation for Python 3 porting, to avoid the
    use of the deprecated builtin C{execfile} function.
    Nrbexec)openreadcompilerH   )filenameglobalslocalsZfinsourcecoder   r   r   execfile   s    rQ   c                 C   s    | |k rdS | |krdS dS dS )z
        Compare two objects.

        Returns a negative number if C{a < b}, zero if they are equal, and a
        positive number if C{a > b}.
        r    r   r   Nr   )abr   r   r   cmp   s
    rT   c                 C   s`   t s| S dd }dd }dd }dd }d	d
 }dd }|| _|| _|| _|| _|| _|| _| S )z
    Class decorator that ensures support for the special C{__cmp__} method.

    On Python 2 this does nothing.

    On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class,
    relying on C{__cmp__} to implement their comparisons.
    c                 S   s   |  |}|tkr|S |dkS Nr   Z__cmp__NotImplementedselfothercr   r   r   __eq__  s    
zcomparable.<locals>.__eq__c                 S   s   |  |}|tkr|S |dkS rU   rV   rX   r   r   r   __ne__"  s    
zcomparable.<locals>.__ne__c                 S   s   |  |}|tkr|S |dk S rU   rV   rX   r   r   r   __lt__)  s    
zcomparable.<locals>.__lt__c                 S   s   |  |}|tkr|S |dkS rU   rV   rX   r   r   r   __le__0  s    
zcomparable.<locals>.__le__c                 S   s   |  |}|tkr|S |dkS rU   rV   rX   r   r   r   __gt__7  s    
zcomparable.<locals>.__gt__c                 S   s   |  |}|tkr|S |dkS rU   rV   rX   r   r   r   __ge__>  s    
zcomparable.<locals>.__ge__)_PY3r^   r`   r_   ra   r\   r]   )klassr\   r]   r^   r_   r`   ra   r   r   r   
comparable  s    
rd   c                 C   s   t | trtS t | trtS t| dd}ddl}t | |j|jfrN|rJtS tS t	st | t
rl|dk	rhtS tS ddlm}m} ddlm} t | |||frtS |S )a[  
    Determine the type which will be returned from the given file object's
    read() and accepted by its write() method as an argument.

    In other words, determine whether the given file is 'opened in text mode'.

    @param fileIshObject: Any object, but ideally one which resembles a file.
    @type fileIshObject: L{object}

    @param default: A default value to return when the type of C{fileIshObject}
        cannot be determined.
    @type default: L{type}

    @return: There are 3 possible return values:

            1. L{unicode}, if the file is unambiguously opened in text mode.

            2. L{bytes}, if the file is unambiguously opened in binary mode.

            3. L{basestring}, if we are on python 2 (the L{basestring} type
               does not exist on python 3) and the file is opened in binary
               mode, but has an encoding and can therefore accept both bytes
               and text reliably for writing, but will return L{bytes} from
               read methods.

            4. The C{default} parameter, if the given type is not understood.

    @rtype: L{type}
    encodingNr   )	InputType
OutputTypeStringIO)
isinstancer   unicoder   bytesr3   codecsStreamReaderStreamWriterrb   file
basestring	cStringIOrf   rg   ri   )ZfileIshObjectdefaultre   rm   rf   rg   ri   r   r   r   ioTypeW  s(    


rt   c                 C   s`   t | ttfstd|  tr>t | tr2| dS | d nt | trR| dS | d | S )a	  
    Convert C{bytes} or C{unicode} to the native C{str} type, using ASCII
    encoding if conversion is necessary.

    @raise UnicodeError: The input string is not ASCII encodable/decodable.
    @raise TypeError: The input is neither C{bytes} nor C{unicode}.
    z%r is neither bytes nor unicodeascii)rj   rl   rk   	TypeErrorrb   decodeencodesr   r   r   nativeString  s    




r{   c                 C   s<   t | tr| d}n
| d}t| t|kr4| S |S dS )a  
    Some functions, such as C{os.path.join}, operate on string arguments which
    may be bytes or text, and wish to return a value of the same type.  In
    those cases you may wish to have a string constant (in the case of
    C{os.path.join}, that constant would be C{os.path.sep}) involved in the
    parsing or processing, that must be of a matching type in order to use
    string operations on it.  L{_matchingString} will take a constant string
    (either L{bytes} or L{unicode}) and convert it to the same type as the
    input string.  C{constantString} should contain only characters from ASCII;
    to ensure this, it will be encoded or decoded regardless.

    @param constantString: A string literal used in processing.
    @type constantString: L{unicode} or L{bytes}

    @param inputString: A byte string or text string provided by the user.
    @type inputString: L{unicode} or L{bytes}

    @return: C{constantString} converted into the same type as C{inputString}
    @rtype: the type of C{inputString}
    ru   N)rj   rl   rw   rx   type)ZconstantStringZinputStringZ	otherTyper   r   r   _matchingString  s    

r}   c                 C   s   |  |d S N)with_traceback)Z	exception	tracebackr   r   r   reraise  s    r   zZdef reraise(exception, traceback):
        raise exception.__class__, exception, tracebackaZ  
Re-raise an exception, with an optional traceback, in a way that is compatible
with both Python 2 and Python 3.

Note that on Python 3, re-raised exceptions will be mutated, with their
C{__traceback__} attribute being set.

@param exception: The exception instance.
@param traceback: The traceback to use, or L{None} indicating a new traceback.
rh   )BytesIOc                 c   s(   t t| D ]}| ||d  V  qd S )Nr   )r   r7   )originalBytesrD   r   r   r   	iterbytes  s    r   c                 C   s   d|   dS )Nz%dru   )rx   rD   r   r   r   
intToBytes  s    r   c                 C   s0   t | }|dkr||d S ||||  S dS )a  
        Return a copy of the given bytes-like object.

        If an offset is given, the copy starts at that offset. If a size is
        given, the copy will only be of that length.

        @param object: C{bytes} to be copied.

        @param offset: C{int}, starting index of copy.

        @param size: Optional, if an C{int} is given limit the length of copy
            to this size.
        N)
memoryview)objectoffsetsizeZviewr   r   r   lazyByteSlice  s    r   c                 C   s   t | tstd| dS )Nz*Can only convert text to bytes on Python 3ru   )rj   rk   rv   rx   ry   r   r   r   networkString
  s    
r   c                 C   s   | S r~   r   )r   r   r   r   r     s    c                 C   s   d|  S )Ns   %dr   r   r   r   r   r     s    c                 C   s    t | tstd| d | S )Nz'Can only pass-through bytes on Python 2ru   )rj   strrv   rw   ry   r   r   r   r     s    

a  
Return an iterable wrapper for a C{bytes} object that provides the behavior of
iterating over C{bytes} on Python 2.

In particular, the results of iteration are the individual bytes (rather than
integers as on Python 3).

@param originalBytes: A C{bytes} object that will be wrapped.
z
Convert the given integer into C{bytes}, as ASCII-encoded Arab numeral.

In other words, this is equivalent to calling C{bytes} in Python 2 on an
integer.

@param i: The C{int} to convert to C{bytes}.
@rtype: C{bytes}
a  
Convert the native string type to C{bytes} if it is not already C{bytes} using
ASCII encoding if conversion is necessary.

This is useful for sending text-like bytes that are constructed using string
interpolation.  For example, this is safe on Python 2 and Python 3:

    networkString("Hello %d" % (n,))

@param s: A native string to convert to bytes if necessary.
@type s: C{str}

@raise UnicodeError: The input string is not ASCII encodable/decodable.
@raise TypeError: The input is neither C{bytes} nor C{unicode}.

@rtype: C{bytes}
)InstanceType)FileType)escape)quote)unquote)	cookiejarc                 C   s   |   S r~   itemsdr   r   r   	iteritemsh  s    r   c                 C   s   |   S r~   )valuesr   r   r   r   
itervaluesl  s    r   c                 C   s   t |  S r~   )listr   r   r   r   r   r   p  s    r   c                 C   s   |   S r~   )r   r   r   r   r   r   w  s    c                 C   s   |   S r~   )r   r   r   r   r   r   {  s    c                 C   s   |   S r~   r   r   r   r   r   r     s    )izipzM
Return an iterable of the items of C{d}.

@type d: L{dict}
@rtype: iterable
zN
Return an iterable of the values of C{d}.

@type d: L{dict}
@rtype: iterable
zG
Return a list of the items of C{d}.

@type d: L{dict}
@rtype: L{list}
c                 C   s   t rt|  S |  S dS )zV
    Return a list of the keys of C{d}.

    @type d: L{dict}
    @rtype: L{list}
    N)rb   r   keysr   r   r   r   _keys  s    r   c                  C   sD   t sttjS t } tj D ] \}}tj|| tj|< q| S )z
    Return a L{dict} of L{os.environ} where all text-strings are encoded into
    L{bytes}.

    This function is POSIX only; environment variables are always text strings
    on Windows.
    )rb   dictr   r   r   encodevalue	encodekey)targetr   yr   r   r   bytesEnviron  s    
r   c                 C   s$   | j | }trt||S t||| S )aj  
    Construct a bound method.

    @param cls: The class that the method should be bound to.
    @type cls: L{types.ClassType} or L{type}.

    @param name: The name of the method.
    @type name: native L{str}

    @param self: The object that the method is bound to.
    @type self: any object

    @return: a bound method
    @rtype: L{types.MethodType}
    )__dict__rb   _MethodType)clsnamerY   funcr   r   r   _constructMethod  s    

r   )Version)deprecatedModuleAttribute)OrderedDictZTwisted   r   z$Use collections.OrderedDict instead.ztwisted.python.compatr   )encodebytes)decodebytes)encodestring)decodestringc                 C   s   t rt| gS t| S dS )z
    Like L{chr} but always works on ASCII, returning L{bytes}.

    @param i: The ASCII code point to return.
    @type i: L{int}

    @rtype: L{bytes}
    N)rb   rl   chrr   r   r   r   	_bytesChr  s    	
r   )internc                 C   s2   t | tr*trtd| f q.| dS n| S dS )az  
    Coerce ASCII-only byte strings into unicode for Python 2.

    In Python 2 C{unicode(b'bytes')} returns a unicode string C{'bytes'}. In
    Python 3, the equivalent C{str(b'bytes')} will return C{"b'bytes'"}
    instead. This function mimics the behavior for Python 2. It will decode the
    byte string as ASCII. In Python 3 it simply raises a L{TypeError} when
    passing a byte string. Unicode strings are returned as-is.

    @param s: The string to coerce.
    @type s: L{bytes} or L{unicode}

    @raise UnicodeError: The input L{bytes} is not ASCII decodable.
    @raise TypeError: The input is L{bytes} on Python 3.
    zExpected str not %r (bytes)ru   N)rj   rl   rb   rv   rw   ry   r   r   r   _coercedUnicode  s
    
r   c                 C   s4   t | tstd| f tr$t| S dt|  S dS )a  
    Provide a repr for a byte string that begins with 'b' on both
    Python 2 and 3.

    @param bytestring: The string to repr.
    @type bytestring: L{bytes}

    @raise TypeError: The input is not L{bytes}.

    @return: The repr with a leading 'b'.
    @rtype: L{bytes}
    zExpected bytes not %rrS   N)rj   rl   rv   rb   repr)Z
bytestringr   r   r   
_bytesRepr$  s
    
r   )Sequencec                 K   sB   d|krt jdtdd | dkr2d|kr2|d} |r:tt| S )a  
    Provide a backwards-compatible way to get async param value that does not
    cause a syntax error under Python 3.7.

    @param isAsync: isAsync param value (should default to None)
    @type isAsync: L{bool}

    @param kwargs: keyword arguments of the caller (only async is allowed)
    @type kwargs: L{dict}

    @raise TypeError: Both isAsync and async specified.

    @return: Final isAsync param value
    @rtype: L{bool}
    asyncz:'async' keyword argument is deprecated, please use isAsyncr#   )
stacklevelN)warningswarnDeprecationWarningpoprv   bool)ZisAsynckwargsr   r   r   _get_async_paramF  s     
r   	frozensetrF   setNativeStringIOrk   
StringTyper   r   r   xrangeurllib_parser   urlquote
urlunquote	cookielib_b64encodebytes_b64decodebytesr   unichr	raw_input	_tokenizer   )r   )N)r   N)N)v__doc__Z
__future__r   r   r   r   platformr1   r:   systokenizetypesr   r   r   ior   r   version_inforb   Z	_PY35PLUSZ	_PY37PLUSZpython_implementationZ_PYPYr   Z_EXPECT_NEWSTYLEr   rA   rE   r   AttributeError	NameErrorr<   r   Zadictr   r   	functoolsrF   ImportErrorrQ   rT   rd   r   rk   r,   Zlongrt   r{   r}   r   rH   ri   r   r   r   r   r   r   bufferrq   r   r   r   r   Zurllib.parseparser   Zhtmlr   r   r   r   r   Zhttpr   r   ZurlparseZcgiZurllibr   r   r   r   r   zipr   	itertoolsr   r   r   Zincrementalr   Ztwisted.python.deprecater   collectionsr   base64r   r   r   r   r   r   r   r   r   r   r   inputr   r   r   generate_tokensZcollections.abcr   r   __all__r   r   r   r   <module>   s  




?#


A= 









