
    0Fie                        d dl mZ d dlZd dlZd dlmZmZmZ d dlm	Z	m
Z
 d dlZd dlmZ ej                            ej                            d                    Zd dD             Zd	ed
<   d	ed<   	 d dlZd1dZn# e$ r d1dZY nw xY wd2dZefd3dZd4dZd4dZe
d	d	dd5d%            Ze
d	d&d6d)            Zd	d	dd*Zd7d-Zej        d.z  Zd8d0ZdS )9    )annotationsN)
CollectionIterableSequence)Literaloverloadnbyteszdistributed.comm.shardc                    i | ]}d |z  d	S )z
max_%s_leni ).0xs     :lib/python3.11/site-packages/distributed/protocol/utils.py
<dictcomp>r      s,       &'\A	      )strbinarraymapextFstrict_map_keyrawnintreturn
memoryviewc                :    t          j        | fd          j        S )Nu1)dtype)numpyemptydatar   s    r   
host_arrayr$      s    {A4t,,,11r   c                :    t          t          |                     S N)r   	bytearrayr#   s    r   r$   r$   #   s    )A,,'''r   buffers(Iterable[bytes | bytearray | memoryview]c                    d | D             }t          t          d |D                                 }d}|D ].}|                    d          ||||j        z   <   ||j        z  }/|S )Nc                ,    g | ]}t          |          S r   )r   )r   bufs     r   
<listcomp>z+host_array_from_buffers.<locals>.<listcomp>*   s    
.
.
.s:c??
.
.
.r   c              3  $   K   | ]}|j         V  d S r&   r	   )r   mvs     r   	<genexpr>z*host_array_from_buffers.<locals>.<genexpr>+   s$      11r111111r   r   B)r$   sumcastr
   )r(   mvsoutoffsetr/   s        r   host_array_from_buffersr7   '   s     /
.g
.
.
.C
S11S11111
2
2CF  +-773<<FVbi''(")Jr   framebytes | memoryviewlist[memoryview]c                     |pt           }t                       j        |k    r gS  j         j        z  }| j        z   fdt	          d|          D             S )z
    Split a frame into a list of frames of maximum size

    This helps us to avoid passing around very large bytestrings.

    Examples
    --------
    >>> frame_split_size([b'12345', b'678'], n=3)  # doctest: +SKIP
    [b'123', b'45', b'678']
    c                *    g | ]}||z            S r   r   )r   ir8   items_per_shards     r   r-   z$frame_split_size.<locals>.<listcomp>I   s(    VVVqE!a/))*VVVr   r   )BIG_BYTES_SHARD_SIZEr   r
   itemsizerange)r8   r   nitemsr>   s   `  @r   frame_split_sizerC   3   su     	
!!AuE|qw\U^+F5>)OVVVVVE!V_4U4UVVVVr   frames*Collection[bytes | bytearray | memoryview]bytesc                x    t          |           }t          t          |           }t          j        d| d|g|R  S )NQ)lenr   r
   structpack)rD   nframesnbytes_framess      r   pack_frames_preluderN   L   s>    &kkG''M;~7~~~w?????r   c                L    d                     t          |           g|           S )zPack frames into a byte-like object

    This prepends length information to the front of the bytes-like object

    See Also
    --------
    unpack_frames
    r   )joinrN   )rD   s    r   pack_framesrQ   R   s'     88(00:6:;;;r   )	remainderpartialbbytes | bytearray | memoryviewrR   boolrS   Literal[False]c                   d S r&   r   rT   rR   rS   s      r   unpack_framesrZ   ^   	     Cr   )rR   Literal[True]"tuple[list[memoryview], list[int]]c                   d S r&   r   rY   s      r   rZ   rZ   h   r[   r   c                  t          |           } d}t          j        |          }t          j        ||           \  }t          j        | | | |          }g }|d|z   z  }| j        }	d}
g }|D ]Z}|r2||	k    r,|                    |t          |          d                     n%||z   }
|                    | ||
                    |
}[|
|	k    sJ |r|                    | |d                    |r||fS |S )a  Unpack bytes into a sequence of frames

    This assumes that length information is at the front of the bytestring,
    as performed by pack_frames

    Parameters
    ----------
    b:
        packed frames, as returned by :func:`pack_frames`
    remainder:
        If True, return one extra frame at the end which is the continuation of a
        stream created by concatenating multiple calls to :func:`pack_frames`.
        This last frame will be empty at the end of the stream.
    partial:
        If True, allow for b to contain less frames than what the preamble indicates;
        return a tuple of ([frames so far], [lengths of missing frames])

    See Also
    --------
    pack_frames
    rH      r   N)r   rJ   calcsizeunpack_fromr
   extendrI   append)rT   rR   rS   fmtfmt_sizen_frameslengthsrD   startnbendmissing_lengthslengths                r   rZ   rZ   r   s2   , 	1A
Cs##H$S!,,KX H!3c!3!3QAAGFH%E	
B
CO   	u{{""73v;;==#9:::Efnac	l###"9999 !ai    &&r   r4   Sequence[memoryview]c           
     n   | st          t                                S t          |           dk    r| d         S | d         }t          |t                     st	          dt          |                     |j        }|j        }d}d}t          |           D ]\  }}t          |t                     s!t	          | dt          |                     |j	        dk    rH|j        |urt          | d|j        d|          |j        st          | d          |j        dk    rt          | d|j         d	          |j        |k    rt          | d
|j         d|           t          |          }|dk    r|}n(||z   }	||	k    rt          d| d|	dd||	z
   d          ||j	        z  }|dk    rt          |          dk    sJ |S |dk    s
J d            t          |                              d          }
t          |
          }||z
  }|
|||z                                |          S )a  
    Zero-copy "concatenate" a sequence of contiguous memoryviews.

    Returns a new memoryview which slices into the underlying buffer
    to extract out the portion equivalent to all of ``mvs`` being concatenated.

    All the memoryviews must:
    * Share the same underlying buffer (``.obj``)
    * When merged, cover a continuous portion of that buffer with no gaps
    * Have the same strides
    * Be 1-dimensional
    * Have the same format
    * Be contiguous

    Raises ValueError if these conditions are not met.
    r`   r   zExpected memoryview; got z: expected memoryview; got z#: memoryview has different buffer: z vs z: memoryview non-contiguousz: memoryview has z dimensions, not 1z: inconsistent format: zmemoryview z2 does not start where the previous ends. Expected r   z	, starts z byte(s) away.z#Underlying buffer is null pointer?!r1   )r   r'   rI   
isinstance	TypeErrortypeobjformat	enumerater
   
ValueError
contiguousndimaddress_of_memoryviewr3   )r4   firstrs   rt   first_start_addrr
   r=   r/   
start_addrexpected_addrbase_mvbase_start_addrstart_indexs                r   merge_memoryviewsr      s   "  ')++&&&
3xx1}}1vFEeZ(( CADKKAABBB
)C\FF3  2"j)) 	IqGGT"XXGGHHH9>>6NNNNsNN   } 	@>>>???7a<<OOBGOOOPPP9QQ")QQQQRRR*2..
q  ),v5M]** e! e e -de e:D}:Te e e   	"){{5zzQq   "G   oo""3''G+G44O"_4K;v!556;;FCCCr   r`   r/   c                   	 t                               |           }t          j        |          S # t          $ r Y nw xY w	 ddl}n!# t          $ r t          d|  d          w xY w|                    |           j	        d         d         S )z
    Get the pointer to the first byte of a memoryview's data.

    If the memoryview is read-only, NumPy must be installed.
    r   Nz+Cannot get address of read-only memoryview z since NumPy is not installed.r"   )
one_byte_carrfrom_bufferctypes	addressofrq   r    ImportErrorrv   asarray__array_interface__)r/   carrnps      r   ry   ry      s    	&((,, %%%    
 	
 
 
 
\"\\\
 
 	

 ::b>>-f5a88s   0 
==A A$)r   r   r   r   )r(   r)   r   r   )r8   r9   r   r   r   r:   )rD   rE   r   rF   )rT   rU   rR   rV   rS   rW   r   r:   )rT   rU   rR   rV   rS   r\   r   r]   )r4   rn   r   r   )r/   r   r   r   ) 
__future__r   r   rJ   collections.abcr   r   r   typingr   r   daskdistributed.utilsr
   utilsparse_bytesconfiggetr?   msgpack_optsr    r$   r   r7   rC   rN   rQ   rZ   r   c_byter   ry   r   r   r   <module>r      sf   " " " " " "   : : : : : : : : : : $ $ $ $ $ $ $ $  $ $ $ $ $ $z--dkoo>V.W.WXX  +P   "' U (
 LLL2 2 2 2 2  ( ( (( ( ( ( ( ((	 	 	 	 )=W W W W W2@ @ @ @	< 	< 	< 	< 
 #	     
 
      
 #( 3 3 3 3 3lGD GD GD GDT ! 9  9  9  9  9  9s   4A= =	B	B	