
    ,i[                    P   U d dl mZ d dlZd dlmZmZ d dlmZmZ ddl	m
Z
mZ ddlmZ ddlmZmZ eg ee   f   Zd	ed
<   eg ef   Zd	ed<    ede      Z ede      Z G d d      Zej0                   G d de             Zej0                   G d de             Zej6                  j9                  dd      e_        ej6                  j9                  dd      e_        dd	 	 	 	 	 	 	 d$dZd%dZ	 	 	 	 d&dZd'dZ  G d d      Z! G d de      Z" G d  d!e      Z#d(d"Z$d)d#Z%y)*    )annotationsN)	AwaitableCallable)	TypeAliasTypeVar   )_core_utilStapledStream)ReceiveStream
SendStreamr   	AsyncHookSyncHookSendStreamT)boundReceiveStreamTc                  P    e Zd Zd
dZd
dZd
dZddZddZddZdddZ	ddd	Z
y)_UnboundedByteQueuec                    t               | _        d| _        t        j                         | _        t        j                  d      | _        y )NFz%another task is already fetching data)		bytearray_data_closedr	   
ParkingLot_lotr
   ConflictDetector_fetch_lockselfs    k/var/www/system.tvplus.app.br/jogos/scrap/venv/lib/python3.12/site-packages/trio/testing/_memory_streams.py__init__z_UnboundedByteQueue.__init__   s8    [
$$&	 113
    c                F    d| _         | j                  j                          y NT)r   r   
unpark_allr   s    r    closez_UnboundedByteQueue.close$   s    		r"   c                B    t               | _        | j                          y N)r   r   r&   r   s    r    close_and_wipez"_UnboundedByteQueue.close_and_wipe(   s    [


r"   c                    | j                   rt        j                  d      | xj                  |z  c_        | j                  j                          y )Nzvirtual connection closed)r   r	   ClosedResourceErrorr   r   r%   r   datas     r    putz_UnboundedByteQueue.put,   s9    <<++,GHH

d
		r"   c                T    |y t        j                  |      }|dk  rt        d      y )N   max_bytes must be >= 1)operatorindex
ValueErrorr   	max_bytess     r    _check_max_bytesz$_UnboundedByteQueue._check_max_bytes2   s1    NN9-	q=566 r"   c                    | j                   s| j                  sJ |t        | j                        }| j                  r$| j                  d | }| j                  d |= |sJ |S t               S r(   )r   r   lenr   )r   r6   chunks      r    	_get_implz_UnboundedByteQueue._get_impl9   sc    ||tzz))DJJI::JJz	*E

:I:&L5L;r"   Nc                    | j                   5  | j                  |       | j                  s| j                  st        j
                  | j                  |      cd d d        S # 1 sw Y   y xY wr(   )r   r7   r   r   r	   
WouldBlockr;   r5   s     r    
get_nowaitz_UnboundedByteQueue.get_nowaitE   sS     	-!!),<<

&&&>>),		- 	- 	-s   A
A!!A*c                H  K   | j                   5  | j                  |       | j                  s/| j                  s#| j                  j                          d {    nt        j                          d {    | j                  |      cd d d        S 7 ;7  # 1 sw Y   y xY wwr(   )	r   r7   r   r   r   parkr	   
checkpointr;   r5   s     r    getz_UnboundedByteQueue.getL   s      	-!!),<<

iinn&&&&&(((>>),	- 	- '(	- 	-sA   B"ABBB3B4B
B"BBBB"returnNoner-   zbytes | bytearray | memoryviewrD   rE   )r6   
int | NonerD   rE   r6   rG   rD   r   r(   )__name__
__module____qualname__r!   r&   r)   r.   r7   r;   r>   rB    r"   r    r   r      s*    
7
--r"   r   c                  b    e Zd ZdZ	 	 	 d
	 	 	 	 	 	 	 ddZddZddZddZddZdddZ	ddd	Z
y)MemorySendStreama  An in-memory :class:`~trio.abc.SendStream`.

    Args:
      send_all_hook: An async function, or None. Called from
          :meth:`send_all`. Can do whatever you like.
      wait_send_all_might_not_block_hook: An async function, or None. Called
          from :meth:`wait_send_all_might_not_block`. Can do whatever you
          like.
      close_hook: A synchronous function, or None. Called from :meth:`close`
          and :meth:`aclose`. Can do whatever you like.

    .. attribute:: send_all_hook
                   wait_send_all_might_not_block_hook
                   close_hook

       All of these hooks are also exposed as attributes on the object, and
       you can change them at any time.

    Nc                    t        j                  d      | _        t               | _        || _        || _        || _        y )N!another task is using this stream)r
   r   _conflict_detectorr   	_outgoingsend_all_hook"wait_send_all_might_not_block_hook
close_hook)r   rS   rT   rU   s       r    r!   zMemorySendStream.__init__l   s=     #("8"8/#
 -.*2T/$r"   c                H  K   | j                   5  t        j                          d{    t        j                          d{    | j                  j	                  |       | j
                  | j                          d{    ddd       y7 h7 N7 # 1 sw Y   yxY ww)z}Places the given data into the object's internal buffer, and then
        calls the :attr:`send_all_hook` (if any).

        N)rQ   r	   rA   rR   r.   rS   r,   s     r    send_allzMemorySendStream.send_allz   s      $$ 	+""$$$""$$$NNt$!!-((***	+ 	+$$ +	+ 	+P   B"BBBB>BBB	B"BBBBB"c                H  K   | j                   5  t        j                          d{    t        j                          d{    | j                  j	                  d       | j
                  | j                          d{    ddd       y7 h7 N7 # 1 sw Y   yxY ww)znCalls the :attr:`wait_send_all_might_not_block_hook` (if any), and
        then returns immediately.

        Nr"   )rQ   r	   rA   rR   r.   rT   r   s    r    wait_send_all_might_not_blockz.MemorySendStream.wait_send_all_might_not_block   s      $$ 	@""$$$""$$$NNs#66B==???	@ 	@$$ @	@ 	@rX   c                r    | j                   j                          | j                  | j                          yy)z^Marks this stream as closed, and then calls the :attr:`close_hook`
        (if any).

        N)rR   r&   rU   r   s    r    r&   zMemorySendStream.close   s-     	??&OO 'r"   c                h   K   | j                          t        j                          d{    y7 wz!Same as :meth:`close`, but async.Nr&   r	   rA   r   s    r    aclosezMemorySendStream.aclose   !     

      (202c                T   K   | j                   j                  |       d{   S 7 w)a  Retrieves data from the internal buffer, blocking if necessary.

        Args:
          max_bytes (int or None): The maximum amount of data to
              retrieve. None (the default) means to retrieve all the data
              that's present (but still blocks until at least one byte is
              available).

        Returns:
          If this stream has been closed, an empty bytearray. Otherwise, the
          requested data.

        N)rR   rB   r5   s     r    get_datazMemorySendStream.get_data   s#      ^^''	2222   (&(c                8    | j                   j                  |      S )zRetrieves data from the internal buffer, but doesn't block.

        See :meth:`get_data` for details.

        Raises:
          trio.WouldBlock: if no data is available to retrieve.

        )rR   r>   r5   s     r    get_data_nowaitz MemorySendStream.get_data_nowait   s     ~~((33r"   )NNN)rS   AsyncHook | NonerT   rg   rU   SyncHook | NonerD   rE   rF   rC   r(   rH   )rI   rJ   rK   __doc__r!   rW   rZ   r&   r_   rc   rf   rL   r"   r    rN   rN   V   s\    , +/?C&*	%'% -=% $	%
 
%+@"!
3 	4r"   rN   c                  R    e Zd ZdZ	 	 d		 	 	 	 	 d
dZdddZddZddZddZddZ	y)MemoryReceiveStreama  An in-memory :class:`~trio.abc.ReceiveStream`.

    Args:
      receive_some_hook: An async function, or None. Called from
          :meth:`receive_some`. Can do whatever you like.
      close_hook: A synchronous function, or None. Called from :meth:`close`
          and :meth:`aclose`. Can do whatever you like.

    .. attribute:: receive_some_hook
                   close_hook

       Both hooks are also exposed as attributes on the object, and you can
       change them at any time.

    Nc                    t        j                  d      | _        t               | _        d| _        || _        || _        y )NrP   F)r
   r   rQ   r   	_incomingr   receive_some_hookrU   )r   rn   rU   s      r    r!   zMemoryReceiveStream.__init__   s<    
 #("8"8/#
 -.!2$r"   c                  K   | j                   5  t        j                          d{    t        j                          d{    | j                  rt        j                  | j
                  | j                          d{    | j                  j                  |       d{   }| j                  rt        j                  |cddd       S 7 7 7 R7 1# 1 sw Y   yxY ww)zCalls the :attr:`receive_some_hook` (if any), and then retrieves
        data from the internal buffer, blocking if necessary.

        N)rQ   r	   rA   r   r+   rn   rm   rB   )r   r6   r-   s      r    receive_somez MemoryReceiveStream.receive_some   s      $$ 	""$$$""$$$||///%%1,,...
 ++I66D||///	 	$$ /
 7	 	sb   C&CCCC?CC"C&C'!C
C&CCCCC#C&c                    d| _         | j                  j                          | j                  | j                          yy)zfDiscards any pending data from the internal buffer, and marks this
        stream as closed.

        TN)r   rm   r)   rU   r   s    r    r&   zMemoryReceiveStream.close   s4    
 %%'??&OO 'r"   c                h   K   | j                          t        j                          d{    y7 wr]   r^   r   s    r    r_   zMemoryReceiveStream.aclose	  r`   ra   c                :    | j                   j                  |       y)z.Appends the given data to the internal buffer.N)rm   r.   r,   s     r    put_datazMemoryReceiveStream.put_data  s    4 r"   c                8    | j                   j                          y)z2Adds an end-of-file marker to the internal buffer.N)rm   r&   r   s    r    put_eofzMemoryReceiveStream.put_eof  s    r"   )NN)rn   rg   rU   rh   rD   rE   r(   rH   rC   rF   )
rI   rJ   rK   ri   r!   rp   r&   r_   rt   rv   rL   r"   r    rk   rk      sI    $ /3&*%+% $% 
	%.!
!r"   rk   z._memory_streams )r6   c                   	 | j                  |      }	 |s|j                          y|j	                  |       	 y# t        j                  $ r Y yw xY w# t        j
                  $ r t        j                  d      dw xY w)a  Take data out of the given :class:`MemorySendStream`'s internal buffer,
    and put it into the given :class:`MemoryReceiveStream`'s internal buffer.

    Args:
      memory_send_stream (MemorySendStream): The stream to get data from.
      memory_receive_stream (MemoryReceiveStream): The stream to put data into.
      max_bytes (int or None): The maximum amount of data to transfer in this
          call, or None to transfer all available data.

    Returns:
      True if it successfully transferred some data, or False if there was no
      data to transfer.

    This is used to implement :func:`memory_stream_one_way_pair` and
    :func:`memory_stream_pair`; see the latter's docstring for an example
    of how you might use it yourself.

    FzMemoryReceiveStream was closedNT)rf   r	   r=   rv   rt   r+   BrokenResourceError)memory_send_streammemory_receive_streamr6   r-   s       r    memory_stream_pumpr|      s    0!11)<T!))+
  "**40    $$ T''(HItSTs   : A A AA*A=c                 n    t               t               dfddfd} | _        _        fS )uQ  Create a connected, pure-Python, unidirectional stream with infinite
    buffering and flexible configuration options.

    You can think of this as being a no-operating-system-involved
    Trio-streamsified version of :func:`os.pipe` (except that :func:`os.pipe`
    returns the streams in the wrong order – we follow the superior convention
    that data flows from left to right).

    Returns:
      A tuple (:class:`MemorySendStream`, :class:`MemoryReceiveStream`), where
      the :class:`MemorySendStream` has its hooks set up so that it calls
      :func:`memory_stream_pump` from its
      :attr:`~MemorySendStream.send_all_hook` and
      :attr:`~MemorySendStream.close_hook`.

    The end result is that data automatically flows from the
    :class:`MemorySendStream` to the :class:`MemoryReceiveStream`. But you're
    also free to rearrange things however you like. For example, you can
    temporarily set the :attr:`~MemorySendStream.send_all_hook` to None if you
    want to simulate a stall in data transmission. Or see
    :func:`memory_stream_pair` for a more elaborate example.

    c                     t                y r(   )r|   )recv_streamsend_streams   r    $pump_from_send_stream_to_recv_streamzHmemory_stream_one_way_pair.<locals>.pump_from_send_stream_to_recv_streama  s    ;4r"   c                    K             y wr(   rL   )r   s   r    *async_pump_from_send_stream_to_recv_streamzNmemory_stream_one_way_pair.<locals>.async_pump_from_send_stream_to_recv_streame  s     ,.s   	rC   )rN   rk   rS   rU   )r   r   r   r   s    @@@r    memory_stream_one_way_pairr   F  s=    0 #$K%'K5/ !KKAK##r"   c                b     |        \  }} |        \  }}t        ||      }t        ||      }||fS r(   r   )one_way_pair
pipe1_send
pipe1_recv
pipe2_send
pipe2_recvstream1stream2s          r    _make_stapled_pairr   m  s?     *^J
)^J
J
3GJ
3GGr"   c                      t        t              S )a  Create a connected, pure-Python, bidirectional stream with infinite
    buffering and flexible configuration options.

    This is a convenience function that creates two one-way streams using
    :func:`memory_stream_one_way_pair`, and then uses
    :class:`~trio.StapledStream` to combine them into a single bidirectional
    stream.

    This is like a no-operating-system-involved, Trio-streamsified version of
    :func:`socket.socketpair`.

    Returns:
      A pair of :class:`~trio.StapledStream` objects that are connected so
      that data automatically flows from one to the other in both directions.

    After creating a stream pair, you can send data back and forth, which is
    enough for simple tests::

       left, right = memory_stream_pair()
       await left.send_all(b"123")
       assert await right.receive_some() == b"123"
       await right.send_all(b"456")
       assert await left.receive_some() == b"456"

    But if you read the docs for :class:`~trio.StapledStream` and
    :func:`memory_stream_one_way_pair`, you'll see that all the pieces
    involved in wiring this up are public APIs, so you can adjust to suit the
    requirements of your tests. For example, here's how to tweak a stream so
    that data flowing from left to right trickles in one byte at a time (but
    data flowing from right to left proceeds at full speed)::

        left, right = memory_stream_pair()
        async def trickle():
            # left is a StapledStream, and left.send_stream is a MemorySendStream
            # right is a StapledStream, and right.recv_stream is a MemoryReceiveStream
            while memory_stream_pump(left.send_stream, right.recv_stream, max_bytes=1):
                # Pause between each byte
                await trio.sleep(1)
        # Normally this send_all_hook calls memory_stream_pump directly without
        # passing in a max_bytes. We replace it with our custom version:
        left.send_stream.send_all_hook = trickle

    And here's a simple test using our modified stream objects::

        async def sender():
            await left.send_all(b"12345")
            await left.send_eof()

        async def receiver():
            async for data in right:
                print(data)

        async with trio.open_nursery() as nursery:
            nursery.start_soon(sender)
            nursery.start_soon(receiver)

    By default, this will print ``b"12345"`` and then immediately exit; with
    our trickle stream it instead sleeps 1 second, then prints ``b"1"``, then
    sleeps 1 second, then prints ``b"2"``, etc.

    Pro-tip: you can insert sleep calls (like in our example above) to
    manipulate the flow of data across tasks... and then use
    :class:`MockClock` and its :attr:`~MockClock.autojump_threshold`
    functionality to keep your test suite running quickly.

    If you want to stress test a protocol implementation, one nice trick is to
    use the :mod:`random` module (preferably with a fixed seed) to move random
    numbers of bytes at a time, and insert random sleeps in between them. You
    can also set up a custom :attr:`~MemoryReceiveStream.receive_some_hook` if
    you want to manipulate things on the receiving side, and not just the
    sending side.

    )r   r   rL   r"   r    memory_stream_pairr   z  s    Z 899r"   c                  N    e 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d	Z
y)_LockstepByteQueuec                    t               | _        d| _        d| _        d| _        t        j                         | _        t        j                  d      | _
        t        j                  d      | _        y )NFzanother task is already sendingz!another task is already receiving)r   r   _sender_closed_receiver_closed_receiver_waitingr	   r   _waitersr
   r   _send_conflict_detector_receive_conflict_detectorr   s    r    r!   z_LockstepByteQueue.__init__  sa    [
# %!&((*','='=-(
$ +0*@*@/+
'r"   c                8    | j                   j                          y r(   )r   r%   r   s    r    _something_happenedz&_LockstepByteQueue._something_happened  s      "r"   c                   K   	  |       rn<| j                   s| j                  rn#| j                  j                          d {    Dt	        j
                          d {    y 7 "7 wr(   )r   r   r   r@   r	   rA   )r   fns     r    	_wait_forz_LockstepByteQueue._wait_for  s]     t""d&;&;--$$&&&      ' s$   A A)A%A)A' A)'A)c                2    d| _         | j                          y r$   )r   r   r   s    r    close_senderz_LockstepByteQueue.close_sender  s    "  "r"   c                2    d| _         | j                          y r$   )r   r   r   s    r    close_receiverz!_LockstepByteQueue.close_receiver  s     $  "r"   c                   K    j                   5   j                  rt        j                   j                  rt        j
                   j                  rJ  xj                  |z  c_         j                           j                   fd       d {     j                  rt        j                   j                  r j                  rt        j
                  d d d        y 7 Q# 1 sw Y   y xY ww)Nc                 "     j                   dk(  S Nr"   r   r   s   r    <lambda>z-_LockstepByteQueue.send_all.<locals>.<lambda>  s    s): r"   )	r   r   r	   r+   r   ry   r   r   r   r,   s   ` r    rW   z_LockstepByteQueue.send_all  s     )) 	0""///$$///zz!>JJ$J$$&..!:;;;""///zzd33///	0 	0 <	0 	0s0   C3BC'C%AC'	C3%C''C0,C3c                f   K    j                   5   j                  rt        j                   j                  r&t        j
                          d {    	 d d d        y  j                   fd       d {     j                  rt        j                  	 d d d        y 7 P7 ,# 1 sw Y   y xY ww)Nc                      j                   S r(   )r   r   s   r    r   zB_LockstepByteQueue.wait_send_all_might_not_block.<locals>.<lambda>	  s    )?)? r"   )r   r   r	   r+   r   rA   r   r   s   `r    rZ   z0_LockstepByteQueue.wait_send_all_might_not_block  s     )) 	0""///$$&&(((	0 	0 ..!?@@@""/// #	0 	0 )@	0 	0sM   B1A B%B!B%	B1B%6B#7 B%	B1!B%#B%%B.*B1Nc                H   K    j                   5  |%t        j                  |      }|dk  rt        d       j                  rt
        j                  d _         j                          	  j                   fd       d {    d _         j                  rt
        j                   j                  r9 j                  d | } j                  d |=  j                          |cd d d        S  j                  sJ 	 d d d        y7 # d _        w xY w# 1 sw Y   y xY ww)Nr0   r1   Tc                 "     j                   dk7  S r   r   r   s   r    r   z1_LockstepByteQueue.receive_some.<locals>.<lambda>  s    TZZ3-> r"   Fr"   )r   r2   r3   r4   r   r	   r+   r   r   r   r   r   )r   r6   gots   `  r    rp   z_LockstepByteQueue.receive_some  s    ,, 	$$NN95	q=$%=>>$$///%)D"$$&/nn%>???).&$$///zz jj),JJz	z*((*3	 	6 ****9	 	 @).&	 	sT   D"AD,D
DD
AD&
D"0D?	D"D

	DDDD"rC   )r   zCallable[[], bool]rD   rE   rF   r(   r6   rG   rD   zbytes | bytearray)rI   rJ   rK   r!   r   r   r   r   rW   rZ   rp   rL   r"   r    r   r     s*    
#
!##0	0r"   r   c                  4    e Zd ZddZddZddZd	dZddZy)
_LockstepSendStreamc                    || _         y r(   _lbqr   lbqs     r    r!   z_LockstepSendStream.__init__.  	    	r"   c                8    | j                   j                          y r(   )r   r   r   s    r    r&   z_LockstepSendStream.close1  s    		 r"   c                h   K   | j                          t        j                          d {    y 7 wr(   r^   r   s    r    r_   z_LockstepSendStream.aclose4  !     

   ra   c                V   K   | j                   j                  |       d {    y 7 wr(   )r   rW   r,   s     r    rW   z_LockstepSendStream.send_all8  s     ii  &&&s   )')c                T   K   | j                   j                          d {    y 7 wr(   )r   rZ   r   s    r    rZ   z1_LockstepSendStream.wait_send_all_might_not_block;  s     ii55777s   (&(Nr   r   rD   rE   rC   rF   )rI   rJ   rK   r!   r&   r_   rW   rZ   rL   r"   r    r   r   -  s    !!'8r"   r   c                  .    e Zd ZddZddZddZdd	dZy)
_LockstepReceiveStreamc                    || _         y r(   r   r   s     r    r!   z_LockstepReceiveStream.__init__@  r   r"   c                8    | j                   j                          y r(   )r   r   r   s    r    r&   z_LockstepReceiveStream.closeC  s    		  "r"   c                h   K   | j                          t        j                          d {    y 7 wr(   r^   r   s    r    r_   z_LockstepReceiveStream.acloseF  r   ra   Nc                T   K   | j                   j                  |       d {   S 7 wr(   )r   rp   r5   s     r    rp   z#_LockstepReceiveStream.receive_someJ  s!     YY++I6666rd   r   rC   r(   r   )rI   rJ   rK   r!   r&   r_   rp   rL   r"   r    r   r   ?  s    #!7r"   r   c                 B    t               } t        |       t        |       fS )a  Create a connected, pure Python, unidirectional stream where data flows
    in lockstep.

    Returns:
      A tuple
      (:class:`~trio.abc.SendStream`, :class:`~trio.abc.ReceiveStream`).

    This stream has *absolutely no* buffering. Each call to
    :meth:`~trio.abc.SendStream.send_all` will block until all the given data
    has been returned by a call to
    :meth:`~trio.abc.ReceiveStream.receive_some`.

    This can be useful for testing flow control mechanisms in an extreme case,
    or for setting up "clogged" streams to use with
    :func:`check_one_way_stream` and friends.

    In addition to fulfilling the :class:`~trio.abc.SendStream` and
    :class:`~trio.abc.ReceiveStream` interfaces, the return objects
    also have a synchronous ``close`` method.

    )r   r   r   )r   s    r    lockstep_stream_one_way_pairr   N  s"    . 
Cs#%;C%@@@r"   c                      t        t              S )a  Create a connected, pure-Python, bidirectional stream where data flows
    in lockstep.

    Returns:
      A tuple (:class:`~trio.StapledStream`, :class:`~trio.StapledStream`).

    This is a convenience function that creates two one-way streams using
    :func:`lockstep_stream_one_way_pair`, and then uses
    :class:`~trio.StapledStream` to combine them into a single bidirectional
    stream.

    )r   r   rL   r"   r    lockstep_stream_pairr   i  s      :;;r"   )rz   rN   r{   rk   r6   rG   rD   bool)rD   z,tuple[MemorySendStream, MemoryReceiveStream])r   z0Callable[[], tuple[SendStreamT, ReceiveStreamT]]rD   z]tuple[StapledStream[SendStreamT, ReceiveStreamT], StapledStream[SendStreamT, ReceiveStreamT]])rD   zqtuple[StapledStream[MemorySendStream, MemoryReceiveStream], StapledStream[MemorySendStream, MemoryReceiveStream]])rD   z tuple[SendStream, ReceiveStream])rD   zYtuple[StapledStream[SendStream, ReceiveStream], StapledStream[SendStream, ReceiveStream]])&
__future__r   r2   collections.abcr   r   typingr   r   rw   r	   r
   _highlevel_genericr   abcr   r   objectr   __annotations__r   r   r   r   finalrN   rk   rJ   replacer|   r   r   r   r   r   r   r   r   rL   r"   r    <module>r      su   "  / %  . +If$5 56	9 6r6z*) *m:6)?<- <-~ o4z o4 o4d J- J J\ /99AA   "5!?!?!G!G"   !	#(#.# 	#
 
#L$$N
B

M:j[ [|8* 8$7] 7A6<r"   