o
    'h%                     @  sv	  U d Z ddl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
mZ ddlmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- dd	l.m/Z/ dd
l0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@mAZAmBZB ddlCmDZD ddlEmFZF ddlGmHZH ddlImJZJ ddlKmLZL ddlMmNZNmOZO ddlPmQZQ ddlRmSZS erddlTmUZU ddlVmWZWmXZX z
ddlYmZZZ dZ[W n e\y   dZ[Y nw g dZ]dZ^dZ_dZ`d Zad!Zbd"Zcd#Zdd$Zed%Zfd&Zgd'Zhd(Zid)Zjd*Zkd+Zld,Zmd-Znd.Zod/Zpd0Zqd1Zresd2jtZuesd3jvZwesd3jtZxesd4jtZyesd5jtZzesd6jtZ{d)d;d<Z|d*dBdCZ}d+dJdKZ~d,dPdQZd-dSdTZd.dWdXZd/dYdZZd0d\d]Zd1d^d_Zd2dadbZd3dddeZd4dgdhZd5djdkZd6dmdnZd7dpdqZd8dsdtZd9dvdwZd:dydzZd;d|d}Zd<ddZi ee^eee_eee`eeeaeeebeeecdd eedeeeeeeefeeegdd eeheeeieeejeeekeeeleeeme~eeneeeoeeepeeeqdd eerdd iZded< e[rN	d=d>ddZn		d=d>ddZe!deeef dZ	d=d?ddZ		d@dAddZdBddZe[reZjZesd2jZesd3jZesd4jZesd5jZesd6jZedd edD ZdCddZdDddZdDddZdEddZdFddZdGddZdHddZdIddZdJddZdKddZdLddZdMddZdNddÄZdOddńZdPddȄZdQdd˄ZdRdd̈́ZdSddЄZdTddӄZdUddՄZdVddׄZdVddلZdWdd܄ZdRddބZdRddZi eeeeejee8eeeeeeeeeeeeeedee	jee,eeDee/ee<eeFeeHeeJeeLeeNeeOeeQee>eejeiZi ZeD ]Zeedree eej< qedd eD Z		dXdYddZɐdZddZ	d[d\ddZe[reZjZedZde1fd]ddZe$d^d_ddZe$d`ddZ	d^daddZϐdbddZe[reZjZe$d^dcddZe$ddddZ	d^deddZѐdfdd	ZҐdgddZe[r3eZjZӐdhddZԐdiddZe$d^djddZe$dkddZ	d^dlddZe$	d^dmddZe$dnddZ	d^doddZאdpdd ZG d!d" d"eZِdqd#d$Zڐdrd%d&Zeed'rejeېd( dS dS (s  av  BSON (Binary JSON) encoding and decoding.

The mapping from Python types to BSON types is as follows:

=======================================  =============  ===================
Python Type                              BSON Type      Supported Direction
=======================================  =============  ===================
None                                     null           both
bool                                     boolean        both
int [#int]_                              int32 / int64  py -> bson
:class:`bson.int64.Int64`                int64          both
float                                    number (real)  both
str                                      string         both
list                                     array          both
dict                                     object         both
:class:`~bson.son.SON`                   object         both
:py:class:`~collections.abc.Mapping`     object         py -> bson
:class:`~bson.raw_bson.RawBSONDocument`  object         both [#raw]_
datetime.datetime [#dt]_ [#dt2]_         UTC datetime   both
:class:`~bson.datetime_ms.DatetimeMS`    UTC datetime   both [#dt3]_
:class:`~bson.regex.Regex`               regex          both
compiled re [#re]_                       regex          py -> bson
:class:`~bson.binary.Binary`             binary         both
:py:class:`uuid.UUID` [#uuid]_           binary         both
:class:`~bson.objectid.ObjectId`         oid            both
:class:`~bson.dbref.DBRef`               dbref          both
:class:`~bson.dbref.DBRef`               dbpointer      bson -> py
None                                     undefined      bson -> py
:class:`~bson.code.Code`                 code           both
str                                      symbol         bson -> py
bytes [#bytes]_                          binary         both
:class:`~bson.timestamp.Timestamp`       timestamp      both
:class:`~bson.decimal128.Decimal128`     decimal128     both
:class:`~bson.min_key.MinKey`            min key        both
:class:`~bson.max_key.MaxKey`            max key        both
=======================================  =============  ===================

.. [#int] A Python int will be saved as a BSON int32 or BSON int64 depending
   on its size. A BSON int32 will always decode to a Python int. A BSON
   int64 will always decode to a :class:`~bson.int64.Int64`.
.. [#raw] Decoding a bson object to :class:`~bson.raw_bson.RawBSONDocument` can be
   optionally configured via :attr:`~bson.codec_options.CodecOptions.document_class`.
.. [#dt] datetime.datetime instances are encoded with millisecond precision so
   the microsecond field is truncated.
.. [#dt2] all datetime.datetime instances are encoded as UTC. By default, they
   are decoded as *naive* but timezone aware datetimes are also supported.
   See :doc:`/examples/datetimes` for examples.
.. [#dt3] To enable decoding a bson UTC datetime to a :class:`~bson.datetime_ms.DatetimeMS`
   instance see :ref:`handling-out-of-range-datetimes`.
.. [#uuid] For :py:class:`uuid.UUID` encoding and decoding behavior see :doc:`/examples/uuid`.
.. [#re] :class:`~bson.regex.Regex` instances and regular expression
   objects from ``re.compile()`` are both saved as BSON regular expressions.
   BSON regular expressions are decoded as :class:`~bson.regex.Regex`
   instances.
.. [#bytes] The bytes type is encoded as BSON binary with
   subtype 0. It will be decoded back to bytes.
    )annotationsN)utf_8_decode)utf_8_encode)abc)IOTYPE_CHECKINGAnyBinaryIOCallable	GeneratorIteratorMappingMutableMappingNoReturnOptionalSequenceTupleTypeTypeVarUnioncastoverload)ALL_UUID_SUBTYPESCSHARP_LEGACYJAVA_LEGACYOLD_UUID_SUBTYPESTANDARDUUID_SUBTYPEBinaryUuidRepresentation)Code)DEFAULT_CODEC_OPTIONSCodecOptionsDatetimeConversion_raw_document_class)EPOCH_AWAREEPOCH_NAIVE
DatetimeMS_datetime_to_millis_millis_to_datetime)DBRef)
Decimal128)InvalidBSONInvalidDocumentInvalidStringData)Int64MaxKeyMinKeyObjectId)Regex)RE_TYPESON)	Timestamp)utcRawBSONDocument)_DocumentType_ReadableBuffer)_cbsonTF)<r   r   r   r   r   r   r   r   r    r!   r"   r*   r+   r,   r-   r.   r/   r1   r3   r5   r6   r7   r8   r9   r:   r%   r&   BSONNUMBSONSTRBSONOBJBSONARRBSONBINBSONUNDBSONOIDBSONBOOBSONDATBSONNULBSONRGXBSONREFBSONCODBSONSYMBSONCWSBSONINTBSONTIMBSONLONBSONDECBSONMINBSONMAXget_data_and_viewgen_list_nameencodedecode
decode_alldecode_iterdecode_file_iteris_validBSONhas_cr#   r'                              	   
                                 z<dz<iz<iBz<qz<IIdatar   returnTuple[Any, memoryview]c                 C  s.   t | ttfr| t| fS t| }| |fS N)
isinstancebytes	bytearray
memoryviewtobytes)rt   view r~   I/var/www/html/olx_land/venv/lib/python3.10/site-packages/bson/__init__.pyrU      s   rU   element_typeintelement_namestrr   c                 C  s   t dt|  |)zUnknown type helper.z\Detected unknown BSON type {!r} for fieldname '{}'. Are you using the latest driver version?)r,   formatchrrW   )r   r   r~   r~   r   _raise_unknown_type   s   r   _viewpositiondummy0dummy1dummy2Tuple[int, int]c                 C     t | |d |d fS )z"Decode a BSON int32 to python int.r      )_UNPACK_INT_FROMrt   r   r   r   r   r   r~   r~   r   _get_int     r   r}   optsCodecOptions[Any]Tuple[str, int]c                 C  s.   |  d|}t||| |jdd |d fS )z'Decode a BSON 'C' string to python str.    Tr      )index_utf_8_decodeunicode_decode_error_handler)rt   r}   r   r   endr~   r~   r   _get_c_string  s   "r   Tuple[float, int]c                 C  r   )z%Decode a BSON double to python float.r      )_UNPACK_FLOAT_FROMr   r~   r~   r   
_get_float  r   r   obj_enddummyc                 C  st   t | |d }|d7 }|dk s|| |k rtd|| d }| | dkr)tdt||| |jdd |d fS )z#Decode a BSON string to python str.r   r   r   zinvalid string lengthzinvalid end of stringT)r   r,   r   r   )rt   r}   r   r   r   r   lengthr   r~   r~   r   _get_string  s   "r   c              
   C  s   z	t | |d }W n tjy } ztt|dd}~ww || d }||kr,td| | dkr6td|dkrB||krBtd||fS )z+Validate and return a BSON document's size.r   Nr   zinvalid object lengthbad eoo)r   structerrorr,   r   )rt   r   r   obj_sizeexcr   r~   r~   r   _get_object_size(  s   r   Tuple[Any, int]c           	      C  s   t | ||\}}t|jr|| ||d  ||| fS t| ||d ||}||7 }t|dtrWd|v rWt|dttdfrWt|	d|	dd|	dd||fS ||fS )zEDecode a BSON subdocument to opts.document_class or bson.dbref.DBRef.r   r   z$refz$idz$dbN)
r   r$   document_class_elements_to_dictrx   getr   typer*   pop)	rt   r}   r   r   r   r   r   r   objr~   r~   r   _get_object9  s   
 (r   c                 C  s  t | |d }|| d }| | dkrtd|d7 }|d8 }g }|j}	| j}
t}|jj}||k rs| | }|
d|d }z|| | |||||\}}W n tyY   t|| Y nw |rk|	t
|}|durk||}|	| ||k s1||d kr}td||d fS )z#Decode a BSON array to python list.r   r   r   r   r   Nzbad array length)r   r,   appendr   _ELEMENT_GETTERtype_registry_decoder_mapKeyErrorr   r   r   )rt   r}   r   r   r   r   sizer   resultr   r   getterdecoder_mapr   valuecustom_decoderr~   r~   r   
_get_arrayN  s<   r   $Tuple[Union[Binary, uuid.UUID], int]c                 C  s  t | |\}}|d7 }|dkr&t| |d }|d7 }||d kr$td|}|| }	|dk s2|	|kr6td|tv rf|j}
t| ||	 |}|
tjks[|tkrS|
t	ks[|t
kr_|
t	kr_||	fS ||
|	fS |dkrt| ||	 }||	fS t| ||	 |}||	fS )z:Decode a BSON binary to bson.binary.Binary or python UUID.      r   r   z,invalid binary (st 2) - lengths don't match!zbad binary object length)_UNPACK_LENGTH_SUBTYPE_FROMr   r,   r   uuid_representationr   r   UNSPECIFIEDr   r   r   as_uuid)rt   r   r   r   r   r   r   subtypelength2r   uuid_repbinary_valuer   r~   r~   r   _get_binaryx  s0   
r   Tuple[ObjectId, int]c                 C  s   |d }t | || |fS )z1Decode a BSON ObjectId to bson.objectid.ObjectId.   r4   rt   r   r   r   r   r   r   r~   r~   r   _get_oid  s   r   Tuple[bool, int]c                 C  s@   |d }| || }|dkrd|fS |dkrd|fS t d| )z.Decode a BSON true/false to python True/False.r   r   Fr_   Tzinvalid boolean value: %r)r,   )rt   r   r   r   r   r   r   boolean_byter~   r~   r   _get_boolean  s   r   0Tuple[Union[datetime.datetime, DatetimeMS], int]c                 C  s   t t| |d ||d fS )z3Decode a BSON datetime to python datetime.datetime.r   r   )r)   _UNPACK_LONG_FROM)rt   r   r   r   r   r   r~   r~   r   	_get_date  s   r   Tuple[Code, int]c                 C  s"   t | |||||\}}t||fS )z%Decode a BSON code to bson.code.Code.)r   r    )rt   r}   r   r   r   r   coder~   r~   r   	_get_code  s   r   _obj_endc           	      C  s`   |t | |d  }t| ||d |||\}}t| |||||\}}||kr)tdt|||fS )z-Decode a BSON code_w_scope to bson.code.Code.r   r   z+scope outside of javascript code boundaries)r   r   r   r,   r    )	rt   r}   r   r   r   r   code_endr   scoper~   r~   r   _get_code_w_scope  s   r   Tuple[Regex[Any], int]c           	      C  s6   t | |||\}}t | |||\}}t||}||fS )zCDecode a BSON regex to bson.regex.Regex or a python pattern object.)r   r6   )	rt   r}   r   r   r   r   pattern
bson_flagsbson_rer~   r~   r   
_get_regex  s   
r   Tuple[DBRef, int]c                 C  s:   t | |||||\}}t| |||||\}}t|||fS )z7Decode (deprecated) BSON DBPointer to bson.dbref.DBRef.)r   r   r*   )rt   r}   r   r   r   r   
collectionoidr~   r~   r   _get_ref  s   r   Tuple[Timestamp, int]c                 C  s    t | |\}}t|||d fS )z4Decode a BSON timestamp to bson.timestamp.Timestamp.r   )_UNPACK_TIMESTAMP_FROMr9   )rt   r   r   r   r   r   inc	timestampr~   r~   r   _get_timestamp  s   r   Tuple[Int64, int]c                 C  s   t t| |d |d fS )z(Decode a BSON int64 to bson.int64.Int64.r   r   )r/   r   r   r~   r~   r   
_get_int64  s   r   Tuple[Decimal128, int]c                 C  s   |d }t | || |fS )z7Decode a BSON decimal128 to bson.decimal128.Decimal128.   )r+   from_bidr   r~   r~   r   _get_decimal128  s   r   c                 C     d |fS rw   r~   uvwxyzr~   r~   r   <lambda>      r   c                 C  r   rw   r~   r   r~   r~   r   r     r   c                 C  
   t  |fS rw   r2   r   r~   r~   r   r        
 c                 C  r   rw   r0   r   r~   r~   r   r     r   z)dict[int, Callable[..., Tuple[Any, int]]]r   	raw_arrayboolTuple[str, Any, int]c              	   C  s   t dt| ||||S )Nr   )r   r?   _element_to_dict)rt   r}   r   r   r   r   r~   r~   r   r     s   r   c                 C  s   | | }|d7 }t | |||\}}|r0|ttkr0t| |t| \}}	||||	d  |	d fS zt| | |||||\}
}W n tyM   t|| Y nw |jj	rc|jj	
t|
}|durc||
}
||
|fS )z Decode a single key, value pair.r   N)r   ordrC   r   lenr   r   r   r   r   r   r   )rt   r}   r   r   r   r   r   r   _r   r   r   r~   r~   r   r   '  s$   	
_T)boundCodecOptions[RawBSONDocument]r   c                 C  s(   t | \} }ttt| ||||||dS )Nr   )rU   r   r  r   )rt   r   r   r   r   r   r}   r~   r~   r   _raw_to_dictH  s   r  c           
      C  s^   |du r|  }|d }||k r%t| |||||d\}}	}|	||< ||k s||kr-td|S )z#Decode a BSON document into result.Nr   r  bad object or element length)r   r   r,   )
rt   r}   r   r   r   r   r   r   keyr   r~   r~   r   r   V  s   
r   CodecOptions[_DocumentType]r=   c                 C  s   t | \} }z"t|jr|| |W S t| dt| \}}tdt| |d||W S  ty0     tyG   t	
 \}}}tt||dw )z'Decode a BSON string to document_class.r   r=   r   N)rU   r$   r   r   r  r   r   r,   	Exceptionsysexc_infor   with_traceback)rt   r   r}   r  r   	exc_valueexc_tbr~   r~   r   _bson_to_dictm  s   
r  c                 c  s"    | ]}t |d  dV  qdS ) utf8N)r   rW   ).0ir~   r~   r   	<genexpr>  s     r    Generator[bytes, None, None]c                  c  s2    t E dH  td} 	 tt| d dV  q)zGenerate "keys" for encoded lists in the sequence
    b"0 ", b"1 ", b"2 ", ...

    The first 1000 keys are returned from a pre-built cache. All
    subsequent keys are generated on the fly.
    Nr  Tr  r  )_LIST_NAMES	itertoolscountr   nextrW   )counterr~   r~   r   rV     s   

rV   stringUnion[str, bytes]ry   c                 C  sn   t | tr'd| v rtdzt| dd | d W S  ty&   td|  dw d| v r/tdt| d d S )z8Make a 'C' string, checking for embedded NUL characters.r   z;BSON keys / regex patterns must not contain a NUL characterNT,strings in documents must be valid UTF-8: %rr  r   )rx   ry   r-   r   UnicodeErrorr.   _utf_8_encoder  r~   r~   r   _make_c_string_check  s    

r$  c                 C  sN   t | trzt| dd | d W S  ty   td|  dw t| d d S )zMake a 'C' string.NTr   r   r   )rx   ry   r   r!  r.   r"  r#  r~   r~   r   _make_c_string  s   

r%  c                 C  s    d| v rt dt| d d S )z*Make a 'C' string suitable for a BSON key.r  z*BSON keys must not contain a NUL characterr   r   )r-   r"  r#  r~   r~   r   
_make_name  s   r&  namer   floatc                 C  s   d|  t | S )zEncode a float.r_   )_PACK_FLOATr'  r   r   r   r~   r~   r   _encode_float  s   r+  c                 C  s   d|  t t| d | S )zEncode a python bytes.rc   r   )	_PACK_INTr  r*  r~   r~   r   _encode_bytes  s   r-  
check_keysc                   sZ   t |rd|  tt|j S d fdd| D }d|  tt|d  | d S )zEncode a mapping type.ra       c                   s   g | ]\}}t || qS r~   )_element_to_bson)r  r	  valr.  r   r~   r   
<listcomp>      z#_encode_mapping.<locals>.<listcomp>r   r   )r$   r   ry   rawjoinitemsr,  r  r'  r   r.  r   rt   r~   r2  r   _encode_mapping  s    r9  r*   c                 C  s   t d|  d }t|d }|td|j||7 }|td|j||7 }|jdur1|td|j||7 }|j D ]\}}|t||||7 }q6|d7 }t	t|| |||d < t
|S )	zEncode bson.dbref.DBRef.ra   s       r   s   $ref s   $id Ns   $db r   )rz   r  _name_value_to_bsonr   iddatabase_DBRef__kwargsr7  r0  r,  ry   )r'  r   r.  r   bufbeginr	  r1  r~   r~   r   _encode_dbref  s   
r@  Sequence[Any]c                   sB   t  d fdd|D }d|  tt|d  | d S )zEncode a list/tuple.r/  c                   s   g | ]}t t| qS r~   )r:  r  )r  itemr.  lnamer   r~   r   r3    r4  z _encode_list.<locals>.<listcomp>rb   r   r   )rV   r6  r,  r  r8  r~   rC  r   _encode_list  s    rE  c                 C  s,   t |d }d|  tt|d  | d S )zEncode a python str.r   r`   r   r   )r"  r,  r  )r'  r   r   r   bvaluer~   r~   r   _encode_text  s    rG  r   c                 C  s8   |j }|dkrtt|| }d|  tt|| | S )zEncode bson.binary.Binary.r   rc   )r   r,  r  _PACK_LENGTH_SUBTYPE)r'  r   r   r   r   r~   r~   r   _encode_binary  s   rI  	uuid.UUIDc                 C  s"   |j }tj||d}t| |||S )zEncode uuid.UUID.)r   )r   r   	from_uuidrI  )r'  r   r   r   r   binvalr~   r~   r   _encode_uuid  s   rM  r5   c                 C     d|  |j  S )zEncode bson.objectid.ObjectId.re   )binary)r'  r   r   r   r~   r~   r   _encode_objectid      rP  c                 C  s   d|  |rdpd S )z%Encode a python boolean (True/False).rf   r_   r   r~   r*  r~   r~   r   _encode_bool  s   rR  datetime.datetimec                 C     t |}d|  t| S zEncode datetime.datetime.rg   )r(   
_PACK_LONGr'  r   r   r   millisr~   r~   r   _encode_datetime
     rY  r'   c                 C  rT  rU  )r   rV  rW  r~   r~   r   _encode_datetime_ms  rZ  r[  c                 C     d|  S )zEncode python None.rh   r~   r'  r   r   r   r~   r~   r   _encode_none     r^  
Regex[Any]c                 C  s   |j }|tjkrd|  t|j d S |dkr"d|  t|j d S d}|tj@ r-|d7 }|tj@ r6|d7 }|tj@ r?|d7 }|tj@ rH|d	7 }|tj@ rQ|d
7 }|tj	@ rZ|d7 }|d7 }d|  t|j | S )z*Encode a python regex or bson.regex.Regex.ri   s   u r   r   r/     i   l   m   s   u   x)
flagsreUNICODEr$  r   
IGNORECASELOCALE	MULTILINEDOTALLVERBOSE)r'  r   r   r   rg  sflagsr~   r~   r   _encode_regex  s(   






rp  r    c                 C  sn   t |}t|}|jdu rd|  t| | S t|jd|d}td| t| }d|  | t| | | S )zEncode bson.code.Code.Nrk   Fr   rm   )r%  r  r   r,  _dict_to_bson)r'  r   r   r   cstringcstrlenr   full_lengthr~   r~   r   _encode_code5  s   
ru  c                 C  sV   d|  kr
dkrn nd|  t | S z	d|  t| W S  tjy*   tddw )zEncode a python int.i   irn   rp   &BSON can only handle up to 8-byte intsN)r,  rV  r   r   OverflowErrorr*  r~   r~   r   _encode_int@  s   
rx  c                 C  s   d|  t |j|j S )z Encode bson.timestamp.Timestamp.ro   )_PACK_TIMESTAMPr   timer*  r~   r~   r   _encode_timestampK  s   r{  c                 C  s.   z	d|  t | W S  tjy   tddw )zEncode a bson.int64.Int64.rp   rv  N)rV  r   r   rw  r*  r~   r~   r   _encode_longP  s
   
r|  r+   c                 C  rN  )z"Encode bson.decimal128.Decimal128.rq   )bidr*  r~   r~   r   _encode_decimal128X  rQ  r~  c                 C  r\  )zEncode bson.min_key.MinKey.rr   r~   r]  r~   r~   r   _encode_minkey]  r_  r  c                 C  r\  )zEncode bson.max_key.MaxKey.rs   r~   r]  r~   r~   r   _encode_maxkeyb  r_  r  _type_markerc                 c  s    | ]}|V  qd S rw   r~   )r  tr~   r~   r   r    s    in_custom_callin_fallback_callc                 C  sX  d}zt t| | |||W S  ty   Y n ty'   t|ts# d}Y nw t|dd}t|trH|tv rHt| }|t t|< || |||S |sf|jj	rf|jj	
t|}	|	durft| |	|||ddS tD ]}
|st||
rt |
 }|t t|< || |||  S qh|jj}|s|durt| ||||ddS |rtdtd|d	t|)
z!Encode a single name, value pair.FTr  N)r  )r  rv  zcannot encode object: z, of type: )	_ENCODERSr   r   rw  rx   r   getattr_MARKERSr   _encoder_mapr   r:  _BUILT_IN_TYPES_fallback_encoderr-   )r'  r   r.  r   r  r  was_integer_overflowmarkerfunccustom_encoderbasefallback_encoderr~   r~   r   r:    sF   


r:  r	  c                 C  sd   t | tstd| |r'| drtd| dd| v r'td| dt| }t||||S )z Encode a single key, value pair.z.documents must have only string keys, key was $zkey z must not start with '$'.z must not contain '.')rx   r   r-   
startswithr&  r:  )r	  r   r.  r   r'  r~   r~   r   r0    s   

r0  doc	top_levelc           	      C  s   t | r
tt| jS zIg }|rd| v r|td| d || |  D ].\}}|r-|dkrQz|t|||| W q# tyP } ztd|  d| |d}~ww q#W n t	yb   t
d| dw d|}tt|d | d	 S )
zEncode a document to BSON._ids   _id zInvalid document z | Nz)encoder expected a mapping type but got: r/  r   r   )r$   r   ry   r5  r   r:  r7  r0  r-   AttributeError	TypeErrorr6  r,  r  )	r  r.  r   r  elementsr	  r   errencodedr~   r~   r   rq    s*   
rq  z1codec_options must be an instance of CodecOptionsdocumentMapping[str, Any]codec_optionsc                 C  s   t |tstt| ||S )a  Encode a document to BSON.

    A document can be any mapping type (like :class:`dict`).

    Raises :class:`TypeError` if `document` is not a mapping type,
    or contains keys that are not instances of :class:`str`. Raises
    :class:`~bson.errors.InvalidDocument` if `document` cannot be
    converted to :class:`BSON`.

    :param document: mapping type representing a document
    :param check_keys: check if keys start with '$' or
        contain '.', raising :class:`~bson.errors.InvalidDocument` in
        either case
    :param codec_options: An instance of
        :class:`~bson.codec_options.CodecOptions`.

    .. versionadded:: 3.9
    )rx   r"   _CODEC_OPTIONS_TYPE_ERRORrq  )r  r.  r  r~   r~   r   rW     s   
rW   r>   Nonedict[str, Any]c                 C     d S rw   r~   rt   r  r~   r~   r   rX         rX   c                 C  r  rw   r~   r  r~   r~   r   rX   %  r  %Optional[CodecOptions[_DocumentType]]$Union[dict[str, Any], _DocumentType]c                 C  s&   |pt }t|tsttdt| |S )a  Decode BSON to a document.

    By default, returns a BSON document represented as a Python
    :class:`dict`. To use a different :class:`MutableMapping` class,
    configure a :class:`~bson.codec_options.CodecOptions`::

        >>> import collections  # From Python standard library.
        >>> import bson
        >>> from bson.codec_options import CodecOptions
        >>> data = bson.encode({'a': 1})
        >>> decoded_doc = bson.decode(data)
        <type 'dict'>
        >>> options = CodecOptions(document_class=collections.OrderedDict)
        >>> decoded_doc = bson.decode(data, codec_options=options)
        >>> type(decoded_doc)
        <class 'collections.OrderedDict'>

    :param data: the BSON to decode. Any bytes-like object that implements
        the buffer protocol.
    :param codec_options: An instance of
        :class:`~bson.codec_options.CodecOptions`.

    .. versionadded:: 3.9
    r  )r!   rx   r"   r  r   r  )rt   r  r   r~   r~   r   rX   *  s   
list[_DocumentType]c                 C  s  t | \} }t| }g }d}|d }t|j}zO||k rdt| |d }|| |k r-td|| d }	| |	 dkr=td|rO||| ||	d  | n|t| ||d |	| ||7 }||k s|W S  tyn     ty   t	
 \}
}}tt||dw )z)Decode a BSON data to multiple documents.r   r   zinvalid object sizer   r   N)rU   r  r$   r   r   r,   r   r   r  r  r  r   r  )rt   r   r}   data_lendocsr   r   use_rawr   r   r  r  r  r~   r~   r   _decode_allL  s4   
 r  list[dict[str, Any]]c                 C  r  rw   r~   r  r~   r~   r   rY   n  r  rY   c                 C  r  rw   r~   r  r~   r~   r   rY   s     0Union[list[dict[str, Any]], list[_DocumentType]]c                 C  s*   |du r	t | tS t|tstt | |S )a+  Decode BSON data to multiple documents.

    `data` must be a bytes-like object implementing the buffer protocol that
    provides concatenated, valid, BSON-encoded documents.

    :param data: BSON data
    :param codec_options: An instance of
        :class:`~bson.codec_options.CodecOptions`.

    .. versionchanged:: 3.9
       Supports bytes-like objects that implement the buffer protocol.

    .. versionchanged:: 3.0
       Removed `compile_re` option: PyMongo now always represents BSON regular
       expressions as :class:`~bson.regex.Regex` objects. Use
       :meth:`~bson.regex.Regex.try_compile` to attempt to convert from a
       BSON regular expression to a Python regular expression object.

       Replaced `as_class`, `tz_aware`, and `uuid_subtype` options with
       `codec_options`.
    N)r  r!   rx   r"   r  r  r~   r~   r   rY   z  s
   


rawdocfieldsc                 C  sv   t |jri }n| }|  D ](\}}||v r4|| dkr)t| j|| ||< qt||| |||< q|||< q|S )Nr   )r$   r   r7  r  r5  _decode_selective)r  r  r  r  r	  r   r~   r~   r   r    s   



r  Union[memoryview, bytes]c                 C  s   d}t | }t||t|\}}|d7 }g }|j}||d k rO|| dkr/|d7 }|| dks%|d7 }t|||\}}|||||   ||7 }||d k s||krWtdd|S )Nr   r   r   r  r/  )r{   r   r  r   r,   r6  )rt   r   r}   r  r   buffersr   r   r~   r~   r   _array_of_documents_to_buffer  s$   
r  c                 C  sP   |  d}|s	dS dD ]}| |}|sqt|}|r!|g||< qg ||< qdS )z=Convert raw array of documents to a stream of BSON documents.cursorN)
firstBatch	nextBatch)r   r  )r  r  r	  batchrt   r~   r~   r   &_convert_raw_document_lists_to_streams  s   


r  c                 C  sZ   |j js	t| |S |st| |jddS ddlm} |j|dd}t| |}t|||gS )aW  Decode BSON data to a single document while using user-provided
    custom decoding logic.

    `data` must be a string representing a valid, BSON-encoded document.

    :param data: BSON data
    :param codec_options: An instance of
        :class:`~bson.codec_options.CodecOptions` with user-specified type
        decoders. If no decoders are found, this method is the same as
        ``decode_all``.
    :param fields: Map of document namespaces where data that needs
        to be custom decoded lives or None. For example, to custom decode a
        list of objects in 'field1.subfield1', the specified value should be
        ``{'field1': {'subfield1': 1}}``. If ``fields``  is an empty map or
        None, this method is the same as ``decode_all``.

    :return: Single-member list containing the decoded document.

    .. versionadded:: 3.8
    N)r   r   r;   )r   r   )r   r   rY   with_optionsbson.raw_bsonr<   r  r  )rt   r  r  r<   internal_codec_options_docr~   r~   r   _decode_all_selective  s   

r  Iterator[dict[str, Any]]c                 C  r  rw   r~   r  r~   r~   r   rZ     r  rZ   Iterator[_DocumentType]c                 C  r  rw   r~   r  r~   r~   r   rZ     r  8Union[Iterator[dict[str, Any]], Iterator[_DocumentType]]c                 c  sr    |pt }t|tstd}t| d }||k r7t| |d }| |||  }||7 }t||V  ||k sdS dS )a  Decode BSON data to multiple documents as a generator.

    Works similarly to the decode_all function, but yields one document at a
    time.

    `data` must be a string of concatenated, valid, BSON-encoded
    documents.

    :param data: BSON data
    :param codec_options: An instance of
        :class:`~bson.codec_options.CodecOptions`.

    .. versionchanged:: 3.0
       Replaced `as_class`, `tz_aware`, and `uuid_subtype` options with
       `codec_options`.

    .. versionadded:: 2.8
    r   r   N)r!   rx   r"   r  r  r   r  )rt   r  r   r   r   r   r  r~   r~   r   rZ     s   
file_objUnion[BinaryIO, IO[bytes]]c                 C  r  rw   r~   r  r  r~   r~   r   r[   5  r  r[   c                 C  r  rw   r~   r  r~   r~   r   r[   <  r  c                 c  sf    |pt }	 | d}|sdS t|dkrtdt|dd d }|| td| }t||V  q)a  Decode bson data from a file to multiple documents as a generator.

    Works similarly to the decode_all function, but reads from the file object
    in chunks and parses bson in chunks, yielding one document at a time.

    :param file_obj: A file object containing BSON data.
    :param codec_options: An instance of
        :class:`~bson.codec_options.CodecOptions`.

    .. versionchanged:: 3.0
       Replaced `as_class`, `tz_aware`, and `uuid_subtype` options with
       `codec_options`.

    .. versionadded:: 2.8
    Tr   zcut off in middle of objsizer   N)r!   readr  r,   r   maxr  )r  r  r   	size_datar   r  r~   r~   r   r[   C  s   
bsonc                 C  sB   t | tstdt|  zt| t W dS  ty    Y dS w )a  Check that the given string represents valid :class:`BSON` data.

    Raises :class:`TypeError` if `bson` is not an instance of
    :class:`bytes`. Returns ``True``
    if `bson` is valid :class:`BSON`, ``False`` otherwise.

    :param bson: the data to be validated
    z:BSON data must be an instance of a subclass of bytes, not TF)rx   ry   r  r   r  r!   r  )r  r~   r~   r   r\   c  s   
	
r\   c                   @  s2   e Zd ZdZedefdddZefdddZdS )r]   zBSON (Binary JSON) data.

    .. warning:: Using this class to encode and decode BSON adds a performance
       cost. For better performance use the module level functions
       :func:`encode` and :func:`decode` instead.
    Fcls
Type[BSON]r  r  r.  r   r  r   ru   c                 C  s   | t |||S )a  Encode a document to a new :class:`BSON` instance.

        A document can be any mapping type (like :class:`dict`).

        Raises :class:`TypeError` if `document` is not a mapping type,
        or contains keys that are not instances of
        :class:`str'. Raises :class:`~bson.errors.InvalidDocument`
        if `document` cannot be converted to :class:`BSON`.

        :param document: mapping type representing a document
        :param check_keys: check if keys start with '$' or
            contain '.', raising :class:`~bson.errors.InvalidDocument` in
            either case
        :param codec_options: An instance of
            :class:`~bson.codec_options.CodecOptions`.

        .. versionchanged:: 3.0
           Replaced `uuid_subtype` option with `codec_options`.
        )rW   )r  r  r.  r  r~   r~   r   rW   ~  s   zBSON.encoder  c                 C  s
   t | |S )a  Decode this BSON data.

        By default, returns a BSON document represented as a Python
        :class:`dict`. To use a different :class:`MutableMapping` class,
        configure a :class:`~bson.codec_options.CodecOptions`::

            >>> import collections  # From Python standard library.
            >>> import bson
            >>> from bson.codec_options import CodecOptions
            >>> data = bson.BSON.encode({'a': 1})
            >>> decoded_doc = bson.BSON(data).decode()
            <type 'dict'>
            >>> options = CodecOptions(document_class=collections.OrderedDict)
            >>> decoded_doc = bson.BSON(data).decode(codec_options=options)
            >>> type(decoded_doc)
            <class 'collections.OrderedDict'>

        :param codec_options: An instance of
            :class:`~bson.codec_options.CodecOptions`.

        .. versionchanged:: 3.0
           Removed `compile_re` option: PyMongo now always represents BSON
           regular expressions as :class:`~bson.regex.Regex` objects. Use
           :meth:`~bson.regex.Regex.try_compile` to attempt to convert from a
           BSON regular expression to a Python regular expression object.

           Replaced `as_class`, `tz_aware`, and `uuid_subtype` options with
           `codec_options`.
        )rX   )selfr  r~   r~   r   rX     s   
 zBSON.decodeN)
r  r  r  r  r.  r   r  r   ru   r]   )r  r   ru   r  )__name__
__module____qualname____doc__classmethodr!   rW   rX   r~   r~   r~   r   r]   v  s    r]   c                   C  s   t S )zIs the C extension installed?)_USE_Cr~   r~   r~   r   r^     r  r^   c                   C  s   t j rt j  dS dS )z!Releases the ObjectID lock child.N)r5   	_inc_locklockedreleaser~   r~   r~   r   _after_fork  s   
r  register_at_fork)after_in_child)rt   r   ru   rv   )r   r   r   r   ru   r   )rt   r   r   r   r   r   r   r   r   r   r   r   ru   r   )
rt   r   r}   r   r   r   r   r   ru   r   )rt   r   r   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r}   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r   r   r   r   ru   r   )rt   r   r}   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r}   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r}   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r}   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r}   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r}   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r   r   r   r   r   r   r   r   r   r   ru   r   )F)rt   r   r}   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r   r   r   r   r   r  r   r  r   r   ru   r  )NF)rt   r   r}   r   r   r   r   r   r   r   r   r   r   r   ru   r   )rt   r   r   r
  ru   r=   )ru   r  )r  r  ru   ry   )r  r   ru   ry   )
r'  ry   r   r(  r   r   r   r   ru   ry   )
r'  ry   r   ry   r   r   r   r   ru   ry   )
r'  ry   r   r   r.  r   r   r   ru   ry   )
r'  ry   r   r*   r.  r   r   r   ru   ry   )
r'  ry   r   rA  r.  r   r   r   ru   ry   )
r'  ry   r   r   r   r   r   r   ru   ry   )
r'  ry   r   r   r   r   r   r   ru   ry   )
r'  ry   r   rJ  r   r   r   r   ru   ry   )
r'  ry   r   r5   r   r   r   r   ru   ry   )
r'  ry   r   r   r   r   r   r   ru   ry   )
r'  ry   r   rS  r   r   r   r   ru   ry   )
r'  ry   r   r'   r   r   r   r   ru   ry   )
r'  ry   r   r   r   r   r   r   ru   ry   )
r'  ry   r   r`  r   r   r   r   ru   ry   )
r'  ry   r   r    r   r   r   r   ru   ry   )
r'  ry   r   r   r   r   r   r   ru   ry   )
r'  ry   r   r   r   r   r   r   ru   ry   )
r'  ry   r   r+   r   r   r   r   ru   ry   )FF)r'  ry   r   r   r.  r   r   r   r  r   r  r   ru   ry   )
r	  r   r   r   r.  r   r   r   ru   ry   )T)
r  r   r.  r   r   r   r  r   ru   ry   )r  r  r.  r   r  r   ru   ry   rw   )rt   r>   r  r  ru   r  )rt   r>   r  r
  ru   r=   )rt   r>   r  r  ru   r  )rt   r>   r   r
  ru   r  )rt   r>   r  r  ru   r  )rt   r>   r  r
  ru   r  )rt   r>   r  r  ru   r  )r  r   r  r   r  r
  ru   r=   )rt   r  ru   ry   )r  r   ru   r  )rt   r   r  r
  r  r   ru   r  )rt   ry   r  r  ru   r  )rt   ry   r  r
  ru   r  )rt   ry   r  r  ru   r  )r  r  r  r  ru   r  )r  r  r  r
  ru   r  )r  r  r  r  ru   r  )r  ry   ru   r   )ru   r   )ru   r  )r  
__future__r   datetimer  osrh  r   r  uuidcodecsr   r   r   r"  collectionsr   _abctypingr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   bson.binaryr   r   r   r   r   r   r   r   	bson.coder    bson.codec_optionsr!   r"   r#   r$   bson.datetime_msr%   r&   r'   r(   r)   
bson.dbrefr*   bson.decimal128r+   bson.errorsr,   r-   r.   
bson.int64r/   bson.max_keyr1   bson.min_keyr3   bson.objectidr5   
bson.regexr6   bson.sonr7   r8   bson.timestampr9   bson.tz_utilr:   r  r<   bson.typingsr=   r>   r  r?   r  ImportError__all__r@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   Structunpack_fromr   unpack_UNPACK_INTr   r   r   r   rU   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   __annotations__r   r   r  r  r   r  packr)  r,  rH  rV  ry  tupleranger  rV   r$  r%  r&  r+  r-  r9  r@  rE  rG  rI  rM  rP  rR  rY  r[  r^  rp  ru  rx  r{  r|  r~  r  r  r   ry   dictr(  r   listr   UUIDr  r  _typhasattrr  r  r:  r0  rq  r  r  rW   rX   r  rY   r  r  r  r  rZ   r[   r\   r]   r^   r  r  r~   r~   r~   r   <module>   s"  9P(
?*%
		
		
	
D"!-# G