o
    Á¿iA  ã                   @   s   d Z ddlZG dd„ dƒZdS )zt
Async version of gunicorn/http/unreader.py for ASGI workers.

Provides async reading with pushback buffer support.
é    Nc                   @   s<   e Zd ZdZddd„Zddd„Zdd	„ Zd
d„ Zdd„ ZdS )ÚAsyncUnreaderzµAsync socket reader with pushback buffer support.

    This class wraps an asyncio StreamReader and provides the ability
    to "unread" data back into a buffer for re-parsing.
    é    c                 C   s   || _ t ¡ | _|| _dS )zInitialize the async unreader.

        Args:
            reader: asyncio.StreamReader instance
            max_chunk: Maximum bytes to read at once
        N)ÚreaderÚioÚBytesIOÚbufÚ	max_chunk)Úselfr   r   © r
   úJ/home/ubuntu/.local/lib/python3.10/site-packages/gunicorn/asgi/unreader.pyÚ__init__   s   

zAsyncUnreader.__init__Nc                 Ã   s  |durt |tƒstdƒ‚|dur|dkrdS |dk rd}| j dtj¡ |du r;| j ¡ r;| j ¡ }t 	¡ | _|S |du rH|  
¡ I dH }|S | j ¡ |k rq|  
¡ I dH }|sd| j ¡ }t 	¡ | _|S | j |¡ | j ¡ |k sO| j ¡ }t 	¡ | _| j ||d… ¡ |d|… S )a  Read data from the stream, using buffered data first.

        Args:
            size: Number of bytes to read. If None, returns all buffered
                  data or reads a single chunk.

        Returns:
            bytes: Data read from buffer or stream
        Nz&size parameter must be an int or long.r   ó    )Ú
isinstanceÚintÚ	TypeErrorr   Úseekr   ÚSEEK_ENDÚtellÚgetvaluer   Ú_read_chunkÚwrite)r	   ÚsizeÚretÚchunkÚdatar
   r
   r   Úread    s8   €




ú

zAsyncUnreader.readc                 Ã   s.   z| j  | j¡I dH W S  ty   Y dS w )z0Read a chunk of data from the underlying stream.Nr   )r   r   r   Ú	Exception)r	   r
   r
   r   r   M   s   €ÿzAsyncUnreader._read_chunkc                 C   s(   |r| j  dtj¡ | j  |¡ dS dS )zkPush data back into the buffer for re-reading.

        Args:
            data: bytes to push back
        r   N)r   r   r   r   r   )r	   r   r
   r
   r   ÚunreadT   s   þzAsyncUnreader.unreadc                 C   s8   | j  ¡ }| j  dtj¡ | j  ¡ dk}| j  |¡ |S )z-Check if there's data in the pushback buffer.r   )r   r   r   r   r   )r	   ÚposÚhas_datar
   r
   r   Úhas_buffered_data^   s
   
zAsyncUnreader.has_buffered_data)r   )N)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r   r    r
   r
   r
   r   r      s    

-
r   )r$   r   r   r
   r
   r
   r   Ú<module>   s   