
    h.                     
   d 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Zddl	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lmZmZmZ ddlmZ ddlm Z  dd	l!m"Z"m#Z#m$Z$ dd
l%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= 	 ddl>m?Z? dZ@ej                  j                  de=      ZCej                  j                  d      ZEdZFdZGdZHdZIdZJdZKdZLdZMdZNdZOd ZPd!ZQd"ZRd#ZSd$ZTd%ZUd&ZVd'ZWd(ZXd)ZYd*ZZ ej                  d+      j                  Z] ej                  d,      j                  Z_ ej                  d,      j                  Z` ej                  d-      j                  Za ej                  d.      j                  Zb ej                  d/      j                  Zce0rdZdd0 Zed1 ZfegehfZind2Zdd3 Zed4 ZfegfZi ej                         d5k(  rd6 Zknd7 Zkd8 Zld9 Zmd: Znd; Zod< Zpd= Zqd> Zrd? Zsd@ ZtdA ZudB ZvdC ZwdD ZxdE ZydF ZzdG Z{dH Z|dI Z}dJ Z~i  eeeF      eo eeeG      ep eeeH      er eeeI      es eeeJ      et eeeK      dK  eeeL      eu eeeM      ev eeeN      ew eeeO      dL  eeeP      ez eeeQ      e{ eeeR      ex eeeS      ep eeeT      ey eeeU      em eeeV      e| eeeW      e} eeeX      e~ eeeY      dM  eeeZ      dN iZe@rdO ZndP ZdQ ZddRZdS Ze@re?j                  Z ej                  d+      j                  Z ej                  d,      j                  Z ej                  d-      j                  Z ej                  d.      j                  Z ej                  d/      j                  Z edT  edU      D              ZdV ZdW ZdX Ze0rdY ZneZdZ Ze0rd[ Znd\ Zd] Zd^ Zd_ Zd` Zda Zdb Zdc Zdd Zde Zdf Zdg Zdh Zdi Zdj Zdk Zdl Zdm Zdn Zi eeegeej                  eeeeeeeeee2eee ed      eejV                  eeee&eeeeee(ee*ee,ee6ee9ee8ee;eeee ee.jX                  eiZeeeeeeeeedo	Ze0seee<    edp eD              Z	 	 ddqZdr ZddsZe@re?jf                  Zdt Zdu Z edv      ZdefdwZefdxZefdyZe@re?jt                  Zdz Zd{ Zefd|Zefd}Zd~ Z G d deg      Zd Zy# eA$ r dZ@Y Ww xY w)a  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
long                                     int64          py -> bson
`bson.int64.Int64`                       int64          both
float                                    number (real)  both
string                                   string         py -> bson
unicode                                  string         both
list                                     array          both
dict / `SON`                             object         both
datetime.datetime [#dt]_ [#dt2]_         date           both
`bson.regex.Regex`                       regex          both
compiled re [#re]_                       regex          py -> bson
`bson.binary.Binary`                     binary         both
`bson.objectid.ObjectId`                 oid            both
`bson.dbref.DBRef`                       dbref          both
None                                     undefined      bson -> py
unicode                                  code           bson -> py
`bson.code.Code`                         code           py -> bson
unicode                                  symbol         bson -> py
bytes (Python 3) [#bytes]_               binary         both
=======================================  =============  ===================

Note that, when using Python 2.x, to save binary data it must be wrapped as
an instance of `bson.binary.Binary`. Otherwise it will be saved as a BSON
string and retrieved as unicode. Users of Python 3.x can use the Python bytes
type.

.. [#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`.
.. [#dt] datetime.datetime instances will be rounded to the nearest
   millisecond when saved
.. [#dt2] all datetime.datetime instances are treated as *naive*. clients
   should always use UTC.
.. [#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 from Python 3.x is encoded as BSON binary with
   subtype 0. In Python 3.x it will be decoded back to bytes. In Python 2.x
   it will be decoded to an instance of :class:`~bson.binary.Binary` with
   subtype 0.
    N)utf_8_decodeutf_8_encode)BinaryUuidRepresentationALL_UUID_SUBTYPESOLD_UUID_SUBTYPEJAVA_LEGACYCSHARP_LEGACY
UUIDLegacyUUID_SUBTYPE)Code)CodecOptionsDEFAULT_CODEC_OPTIONS_raw_document_class)DBRef)
Decimal128)InvalidBSONInvalidDocumentInvalidStringData)Int64MaxKeyMinKeyObjectId)abcbPY3	iteritems	text_typestring_typereraise)Regex)SONRE_TYPE)	Timestamp)utc)_cbsonTF                           	   
                                 z<dz<iz<iBz<qz<IIc                     t        |       S N)ordelement_types    P/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/bson/__init__.py
_maybe_ordrE      s    <      c                 4    t        |       j                         S r@   )chrencoderB   s    rD   _elt_to_hexrJ      s    < ''))rF       c                     | S r@    rB   s    rD   rE   rE          rF   c                     | S r@   rM   rB   s    rD   rJ   rJ      rN   rF   Jythonc                 d    t        | t              r| | fS t        |       j                         } | | fS r@   
isinstance_supported_buffer_types
memoryviewtobytes)datas    rD   get_data_and_viewrX      s4    d34:$'')TzrF   c                 v    t        | t              r| t        |       fS t        |       }|j                         |fS r@   rR   )rW   views     rD   rX   rX      s8    d34D)))$||~t##rF   c                 8    t        dt        |       d|d      )zUnknown type helper.zDetected unknown BSON type z for fieldname 'z+'. Are you using the latest driver version?)r   rJ   )rC   element_names     rD   _raise_unknown_typer]      s!    
%l3\C D DrF   c                 *    t        | |      d   |dz   fS )z"Decode a BSON int32 to python int.r      )_UNPACK_INT_FROMrW   rZ   positiondummy0dummy1dummy2s         rD   _get_intrf      s    D(+A.1<<rF   c                 j    | j                  d|      }t        ||| |j                  d      d   |dz   fS )z2Decode a BSON 'C' string to python unicode string.rK   Tr      )index_utf_8_decodeunicode_decode_error_handler)rW   rZ   rb   optsends        rD   _get_c_stringrn      sK    
**Wh
'Chs+::DBBCEFIAgN NrF   c                 *    t        | |      d   |dz   fS )z%Decode a BSON double to python float.r      )_UNPACK_FLOAT_FROMra   s         rD   
_get_floatrr      s    dH-a0(Q,>>rF   c                     t        | |      d   }|dz  }|dk  s||z
  |k  rt        d      ||z   dz
  }| |   t        k7  rt        d      t        ||| |j                  d      d   |dz   fS )z.Decode a BSON string to python unicode string.r   r_   rh   zinvalid string lengthzinvalid end of stringT)r`   r   _OBJENDrj   rk   )rW   rZ   rb   obj_endrl   dummylengthrm   s           rD   _get_stringrx      s    dH-a0FMHzWx'&0122
V
a
CCyG122hs+::DBBCEFIAgN NrF   c                    	 t        | |      d   }||z   dz
  }| |   t
        k7  rt        d      ||k\  rt        d      |dk(  r||k7  rt        d      ||fS # t        j                  $ r}t        t	        |            d}~ww xY w)z+Validate and return a BSON document's size.r   Nrh   bad eoozinvalid object length)r`   structerrorr   strrt   )rW   rb   ru   obj_sizeexcrm   s         rD   _get_object_sizer      s    $#D(3A6 X

!CCyG)$$
g~1221}W,122S= << $#c(##$s   A B,B  Bc                 B   t        | ||      \  }}t        |j                        r|j                  | ||dz    |      ||z   fS t        | ||dz   ||      }||z  }d|v r?t	        |j                  d      |j                  dd      |j                  dd      |      |fS ||fS )zEDecode a BSON subdocument to opts.document_class or bson.dbref.DBRef.rh   r_   z$refz$idNz$db)r   r   document_class_elements_to_dictr   pop)	rW   rZ   rb   ru   rl   rv   r~   rm   objs	            rD   _get_objectr      s    $T8W=MHc4../##D#'$:DA8#% 	% D$1c4
@CH}cggfoswwud';ggeT*C12:< 	<=rF   c                    t        | |      d   }||z   dz
  }| |   t        k7  rt        d      |dz  }|dz  }g }|j                  }	| j                  }
t
        }|j                  j                  }||k  rY| |   } |
d|      dz   }	  ||   | |||||      \  }}|r$|j                  t                    }| ||      } |	       ||k  rY||dz   k7  rt        d      ||dz   fS # t        $ r t        ||       Y ew xY w)z#Decode a BSON array to python list.r   rh   rz   r_   rK   zbad array length)r`   rt   r   appendri   _ELEMENT_GETTERtype_registry_decoder_mapKeyErrorr]   gettype)rW   rZ   rb   ru   rl   r\   sizerm   resultr   ri   getterdecoder_maprC   valuecustom_decoders                   rD   
_get_arrayr      s=   D(+A.D
T/A
CCyG)$$MH1HCF ]]FJJEF$$11K
S.H~(+a/	<2f\2dHgt\COE8
 (__T%[9N)&u-u S." 37,--8a<  	<l;	<s   C' 'C?>C?c                    t        | |      \  }}|dz  }|dk(  r)t        | |      d   }|dz  }||dz
  k7  rt        d      |}||z   }	|dk  s|	|kD  rt        d      |t        v r|j                  }
t        | ||	 |      }|
t        j                  k(  r||	fS |t        k(  rt        j                  }
n#|
t        j                  k(  rt        j                  }
|j                  |
      |	fS t        r|dk(  r	| ||	 }||	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   STANDARDPYTHON_LEGACYas_uuidr   )rW   rZ   rb   ru   rl   rd   rw   subtypelength2rm   r   binary_valuer   s                rD   _get_binaryr   &  sJ   1$AOFGMH!|"4215Afqj LMM
V
CzS7]455 ##"66d8C0':"4"@"@@$$l""4"="= $6$?$?? #5"B"B##$78#== w!|Xc" #: tHS)73#:rF   c                 ,    |dz   }t        | ||       |fS )z1Decode a BSON ObjectId to bson.objectid.ObjectId.   r   rW   rZ   rb   rc   rd   re   rm   s          rD   _get_oidr   M  s"    
R-CD#&',,rF   c                 V    |dz   }| || }|dk(  rd|fS |dk(  rd|fS t        d|z        )z.Decode a BSON true/false to python True/False.rh   rK   Fr*   Tzinvalid boolean value: %r)r   )rW   rZ   rb   rc   rd   re   rm   boolean_bytes           rD   _get_booleanr   S  sL    
Q,C%Lwcz		 Sy
1L@
AArF   c                 >    t        t        | |      d   |      |dz   fS )z3Decode a BSON datetime to python datetime.datetime.r   rp   )_millis_to_datetime_UNPACK_LONG_FROM)rW   rZ   rb   rc   rl   rd   s         rD   	_get_dater   ^  s.    $)!,d45=\B BrF   c                 B    t        | |||||      \  }}t        |      |fS )z%Decode a BSON code to bson.code.Code.)rx   r   )rW   rZ   rb   ru   rl   r\   codes          rD   	_get_coder   d  s)     tXwlSND(:xrF   c                     |t        | |      d   z   }t        | ||dz   |||      \  }}t        | |||||      \  }}||k7  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`   rx   r   r   r   )	rW   rZ   rb   ru   rl   r\   code_endr   scopes	            rD   _get_code_w_scoper   j  sw    *4:1==H dHqL(D,@ND(!$h$UOE88GHHeh&&rF   c                 f    t        | |||      \  }}t        | |||      \  }}t        ||      }||fS )zCDecode a BSON regex to bson.regex.Regex or a python pattern object.)rn   r$   )	rW   rZ   rb   rc   rl   rd   pattern
bson_flagsbson_res	            rD   
_get_regexr   u  sC    %dD(DAGX(tXtDJGZ(GHrF   c                 j    t        | |||||      \  }}t        | |||||      \  }}t        ||      |fS )z7Decode (deprecated) BSON DBPointer to bson.dbref.DBRef.)rx   r   r   )rW   rZ   rb   ru   rl   r\   
collectionoids           rD   _get_refr   }  sH    &dHgt\;JT47D,OMCS!8++rF   c                 B    t        | |      \  }}t        ||      |dz   fS )z4Decode a BSON timestamp to bson.timestamp.Timestamp.rp   )_UNPACK_TIMESTAMP_FROMr'   )rW   rZ   rb   rc   rd   re   inc	timestamps           rD   _get_timestampr     s(    +D(;NCY$hl22rF   c                 <    t        t        | |      d         |dz   fS )z(Decode a BSON int64 to bson.int64.Int64.r   rp   )r   r   ra   s         rD   
_get_int64r     s#    "421561DDrF   c                 @    |dz   }t        j                  | ||       |fS )z7Decode a BSON decimal128 to bson.decimal128.Decimal128.   )r   from_bidr   s          rD   _get_decimal128r     s(    
R-CtHS12C77rF   c                 
    d |fS r@   rM   uvwxyzs         rD   <lambda>r     
    4) rF   c                 
    d |fS r@   rM   r   s         rD   r   r     r   rF   c                     t               |fS r@   r   r   s         rD   r   r         68Q- rF   c                     t               |fS r@   r   r   s         rD   r   r     r   rF   c                 2    t        j                  | |||      S r@   )r)   _element_to_dict)rW   rZ   rb   ru   rl   s        rD   r   r     s    &&tXwEErF   c                 B   | |   }|dz  }t        | |||      \  }}	 t        |   | |||||      \  }}|j                  j
                  r8|j                  j
                  j                  t                    }| ||      }||fS # t        $ r t        ||       Y jw xY w)z Decode a single key, value pair.rh   )rn   r   r   r]   r   r   r   r   )	rW   rZ   rb   ru   rl   rC   r\   r   r   s	            rD   r   r     s    H~A!.tT8T!Jh	<-l;D$<CT<HJOE8 **!//<<@@eMN)&u-UH,,  	<l;	<s   B BBc                 >    t        |       \  } }t        | |||||      S r@   )rX   r   )rW   rb   ru   rl   r   rZ   s         rD   _raw_to_dictr     s%    "4(JD$T47D&IIrF   c                     ||j                         }|dz
  }||k  rt        | ||||      \  }}}|||<   ||k  r||k7  rt        d      |S )z#Decode a BSON document into result.rh   zbad object or element length)r   r   r   )	rW   rZ   rb   ru   rl   r   rm   keyr   s	            rD   r   r     sk    ~$$&
A+C
S./dHgtTUHs S. 7899MrF   c                 @   t        |       \  } }	 t        |j                        r|j                  | |      S t        | dt	        |             \  }}t        | |d||      S # t        $ r  t        $ r, t        j                         \  }}}t        t        ||       Y yw xY w)z'Decode a BSON string to document_class.r   r_   N)rX   r   r   r   lenr   r   	Exceptionsysexc_infor#   )rW   rl   rZ   _rm   	exc_valueexc_tbs          rD   _bson_to_dictr     s    "4(JD$
0t223&&tT22!$3t953 tQT::  0"||~9fY/0s   &A 'A ;BBc              #   J   K   | ]  }t        t        |            d z     yw)rK   N)r   r}   ).0is     rD   	<genexpr>r     s     =AAc!fI'=s   !#  c               #      K   t         D ]  } |   t        j                  d      }	 t        t	        t        |                  dz    #w)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.
    r   rK   )_LIST_NAMES	itertoolscountr   r}   next)namecounters     rD   gen_list_namer     sM       
 ood#G
DM"#g-- s   A	Ac                     t        | t              r"d| v rt        d      	 t        | dd       | dz   S d| v rt        d      t        |       d   dz   S # t        $ r t        d| z        w xY w)z8Make a 'C' string, checking for embedded NUL characters.rK   ;BSON keys / regex patterns must not contain a NUL characterNT,strings in documents must be valid UTF-8: %r r   )rS   bytesr   rj   UnicodeErrorr   _utf_8_encodestrings    rD   _make_c_string_checkr     s    &% f! #< = =	:&$-G##
 V! #< = =V$Q''11  	:# %028%9 : :	:s   A A+c                     t        | t              r	 t        | dd       | dz   S t        |       d   dz   S # t        $ r t	        d| z        w xY w)zMake a 'C' string.NTrK   r   r   )rS   r   rj   r   r   r   r   s    rD   _make_c_stringr     sj    &% 	:&$-G##
 V$Q''11	  	:# %028%9 : :	:s	   5 Ac                 B    d| v rt        d      t        |       d   dz   S )z*Make a 'C' string suitable for a BSON key.r   r   r   rK   )r   r   r   s    rD   
_make_namer  (  s3     V! #< = =V$Q''11rF   c                 $    d| z   t        |      z   S )zEncode a float.r*   )_PACK_FLOATr   r   rc   rd   s       rD   _encode_floatr  4  s    T>K...rF   c                 B    d| z   t        t        |            z   dz   |z   S )zEncode a python bytes.r.   rK   )	_PACK_INTr   r  s       rD   _encode_bytesr  :  s&     ~	#e* 55?%GGrF   c                     	 t        |dd       d| z   t        t	        |      dz         z   |z   dz   S # t        $ r t        d|      w xY w)z!Encode a python str (python 2.x).NTz*strings in documents must be valid UTF-8: r+   rh   rK   )rj   r   r   r  r   r  s       rD   r  r  ?  sa    	<%t, ~	#e*q. 99EAGKK  	<#38%; < <	<s	   2 A
c                     t        |      rd| z   |j                  z   S dj                  t        |      D cg c]  \  }}t	        ||||       c}}      }d| z   t        t        |      dz         z   |z   dz   S c c}}w )zEncode a mapping type.r,   rF   r   rK   )r   rawjoinr    _element_to_bsonr  r   )r   r   
check_keysrl   r   valrW   s          rD   _encode_mappingr  I  s    5!~		))88%.u%57!c &c3
DA 7 8DT>Ic$i!m44t;gEE7s   A:
c                    t        d| z   dz         }t        |      dz
  }|t        d|j                  ||      z  }|t        d|j                  ||      z  }|j
                  |t        d|j
                  ||      z  }t        |j                        D ]  \  }}|t        ||||      z  } |dz  }t        t        |      |z
        |||dz    t        |      S )zEncode bson.dbref.DBRef.r,   s       r_   s   $ref s   $id s   $db rK   )	bytearrayr   _name_value_to_bsonr   iddatabaser    _DBRef__kwargsr  r  r   )r   r   r  rl   bufbeginr   r  s           rD   _encode_dbrefr  R  s    
GdN%88
9CHqLE{$//TC CCz$xxT; ;C~~!"
D: 	:e223 <SS*d;;< 7NC$SX%56Ceai:rF   c                     t               }dj                  |D cg c]  }t        t        |      |||       c}      }d| z   t	        t        |      dz         z   |z   dz   S c c}w )zEncode a list/tuple.rF   r-   r   rK   )r   r  r  r   r  r   )r   r   r  rl   lnameitemrW   s          rD   _encode_listr  f  sl    OE88!&( )ed)3T; ( )D T>Ic$i!m44t;gEE(s   A"c                 d    t        |      d   }d| z   t        t        |      dz         z   |z   dz   S )z8Encode a python unicode (python 2.x) / str (python 3.x).r   r+   rh   rK   )r   r  r   r  s       rD   _encode_textr  o  s7    % #ET>Ic%j1n55=GGrF   c                     |j                   }|dk(  rt        t        |            |z   }d| z   t        t        |      |      z   |z   S )zEncode bson.binary.Binary.r   r.   )r   r  r   _PACK_LENGTH_SUBTYPE)r   r   rc   rd   r   s        rD   _encode_binaryr"  u  sE    mmG!|#e*%-T>0UWEEMMrF   c                 d    |j                   }t        j                  ||      }t        | |||      S )zEncode uuid.UUID.)r   )r   r   	from_uuidr"  )r   r   rv   rl   r   binvals         rD   _encode_uuidr&  }  s2    22e9LMF$t44rF   c                 &    d| z   |j                   z   S )zEncode bson.objectid.ObjectId.r0   )binaryr  s       rD   _encode_objectidr)    s    T>ELL((rF   c                 "    d| z   |xr dxs dz   S )z%Encode a python boolean (True/False).r1   r*   rK   rM   r  s       rD   _encode_boolr+    s    T>U.w9'::rF   c                 :    t        |      }d| z   t        |      z   S )zEncode datetime.datetime.r2   )_datetime_to_millis
_PACK_LONG)r   r   rc   rd   milliss        rD   _encode_datetimer0    s      'FT>Jv...rF   c                     d| z   S )zEncode python None.r3   rM   r   rc   rd   re   s       rD   _encode_noner3        T>rF   c                 ,   |j                   }|dk(  rd| z   t        |j                        z   dz   S |t        j                  k(  rd| z   t        |j                        z   dz   S d}|t        j
                  z  r|dz  }|t        j                  z  r|dz  }|t        j                  z  r|dz  }|t        j                  z  r|d	z  }|t        j                  z  r|d
z  }|t        j                  z  r|dz  }|dz  }d| z   t        |j                        z   |z   S )z*Encode a python regex or bson.regex.Regex.r   r4   rK   s   u rF      i   l   m   s   u   x)
flagsr   r   reUNICODE
IGNORECASELOCALE	MULTILINEDOTALLVERBOSE)r   r   rc   rd   r<  sflagss         rD   _encode_regexrE    s   KKEz~ 4U]] CCgMM	"**	~ 4U]] CChNN2== dNF299dNF2<<dNF299dNF2::dNF2::dNF'~ 4U]] CCfLLrF   c                    t        |      }t        |      }|j                  d| z   t        |      z   |z   S t	        |j                  d|d      }t        d|z   t        |      z         }d| z   |z   t        |      z   |z   |z   S )zEncode bson.code.Code.r6   Frp   r8   )r   r   r   r  _dict_to_bson)r   r   rv   rl   cstringcstrlenr   full_lengths           rD   _encode_coderK    s    U#G'lG{{~	' 22W<<%++udE:EAK#e*45KT>K')G*<<wFNNrF   c                     d|cxk  rdk  rn nd| z   t        |      z   S 	 d| z   t        |      z   S # t        j                  $ r t	        d      w xY w)zEncode a python int.i   ir9   r;   &BSON can only handle up to 8-byte ints)r  r.  r{   r|   OverflowErrorr  s       rD   _encode_intrO    s^    e)z)~	% 000	JT>Ju$555|| 	J HII	Js	   2 Ac                 N    d| z   t        |j                  |j                        z   S )z Encode bson.timestamp.Timestamp.r:   )_PACK_TIMESTAMPr   timer  s       rD   _encode_timestamprS    s     T>OEIIuzzBBBrF   c                 j    	 d| z   t        |      z   S # t        j                  $ r t        d      w xY w)z!Encode a python long (python 2.x)r;   rM  )r.  r{   r|   rN  r  s       rD   _encode_longrU    s=    F~
5 111<< FDEEFs    2c                 &    d| z   |j                   z   S )z"Encode bson.decimal128.Decimal128.r<   )bidr  s       rD   _encode_decimal128rX    s    T>EII%%rF   c                     d| z   S )zEncode bson.min_key.MinKey.r=   rM   r2  s       rD   _encode_minkeyrZ    r4  rF   c                     d| z   S )zEncode bson.max_key.MaxKey.r>   rM   r2  s       rD   _encode_maxkeyr\    r4  rF   )	r                  d         c              #       K   | ]  }|  y wr@   rM   )r   ts     rD   r   r     s     -a-s   c                    	 t        t        |         | |||      S # t        $ r Y nw xY wt        |dd      }t	        |t
              r.|t        v r&t        |   }|t         t        |      <    || |||      S |s\|j                  j                  rF|j                  j                  j                  t        |            }|t        |  ||      ||d      S t        D ]6  }	t	        ||	      st         |	   }|t         t        |      <    || |||      c S  |j                  j                  }
|s|
t        |  |
|      ||d      S t        d|dt        |            )z!Encode a single name, value pair._type_markerNT)in_custom_call)in_fallback_callzcannot encode object: z, of type: )	_ENCODERSr   r   getattrrS   int_MARKERSr   _encoder_mapr   r  _BUILT_IN_TYPES_fallback_encoderr   )r   r   r  rl   ri  rj  markerfunccustom_encoderbasefallback_encoders              rD   r  r    sp   e%dE:tDD  UND1F&#6X#5!%	$u+D%T22 d00==++88<<T%[I%&nU+Z#% %   7eT"T?D%)Id5k"eZ667 ));; 0 <""5):t!# 	# 38$u+FH Hs    	((c                     t        | t              st        d|       |r3| j                  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 '.')rS   r"   r   
startswithr  r  )r   r   r  rl   r   s        rD   r  r  Q  sm    c;'.14 5 	5>>#!c"KLL#:!3"HIIc?DtUJ==rF   c           	         t        |       r| j                  S 	 g }|r$d| v r |j                  t        d| d   ||             t	        |       D ]*  \  }}|r|dk7  s|j                  t        ||||             , 	 dj                  |      }t        t        |      dz         |z   dz   S # t        $ r t        d|       w xY w)zEncode a document to BSON._ids   _id z)encoder expected a mapping type but got: rF   r   rK   )r   r  r   r  r    r  AttributeError	TypeErrorr  r  r   )docr  rl   	top_levelelementsr   r   encodeds           rD   rG  rG  `  s    3ww
P#OO/
CJ0:DB C%cN 	DLS%u 0e1;T!C D	D hhx GS\A%&07::	  PNOOPs   A B( B( (C c                    | dz  dz   dz  }| |z
  dz  }|dz  }|j                   rGt        t        j                  ||      z   }|j                  r|j                  |j                        }|S t        t        j                  ||      z   S )z1Convert milliseconds since epoch UTC to datetime.r   )secondsmicroseconds)tz_awareEPOCH_AWAREdatetime	timedeltatzinfo
astimezoneEPOCH_NAIVE)r/  rl   diffr  microsdts         rD   r   r   v  s    d]d"d*D}%GD[F}}8--g;AC C;;t{{+B	X//=CE E 	ErF   c                     | j                         | | j                         z
  } t        t        j                  | j	                               dz  | j
                  dz  z         S )z1Convert datetime to milliseconds since epoch UTC.r   )	utcoffsetrm  calendartimegm	timetuplemicrosecond)dtms    rD   r-  r-    sR    
}}"CMMO#xs}}/$6$&' ( (rF   z1codec_options must be an instance of CodecOptionsc                 H    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:`basestring` (:class:`str` in python 3). Raises
    :class:`~bson.errors.InvalidDocument` if `document` cannot be
    converted to :class:`BSON`.

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

    .. versionadded:: 3.9
    )rS   r   _CODEC_OPTIONS_TYPE_ERRORrG  )documentr  codec_optionss      rD   rI   rI     s#    * m\2'':}==rF   c                 F    t        |t              st        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'>

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

    .. versionadded:: 3.9
    )rS   r   r  r   )rW   r  s     rD   decoder    s!    4 m\2''}--rF   c           	      \   t        |       \  } }t        |t              st        t	        |       }g }d}|dz
  }t        |j                        }	 ||k  rt        | |      d   }||z
  |k  rt        d      ||z   dz
  }	| |	   t        k7  rt        d      |r(|j                  |j                  | ||	dz    |             n!|j                  t        | ||dz   |	|             ||z  }||k  r|S # t        $ r  t        $ r, t        j                         \  }
}}t        t        ||       Y yw xY w)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.

    :Parameters:
      - `data`: BSON data
      - `codec_options` (optional): 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`.

    .. versionchanged:: 2.7
       Added `compile_re` option. If set to False, PyMongo represented BSON
       regular expressions as :class:`~bson.regex.Regex` objects instead of
       attempting to compile BSON regular expressions as Python native
       regular expressions, thus preventing errors for some incompatible
       patterns, see `PYTHON-500`_.

    .. _PYTHON-500: https://jira.mongodb.org/browse/PYTHON-500
    r   rh   zinvalid object sizerz   r_   N)rX   rS   r   r  r   r   r   r`   r   rt   r   r   r   r   r   r#   )rW   r  rZ   data_lendocsrb   rm   use_rawr~   ru   r   r   r   s                rD   
decode_allr    sV   @ #4(JD$m\2''4yHDH
Q,C!-">">?G0n'h7:H("X-!"788)A-GG}'!),,!00Xgk2MCD -d.2.6l.5.;	= >
  H# n$   0"||~9fY/0s   BC- +C- -;D+*D+c                     t        |j                        ri }n|j                         }t        |       D ]G  \  }}||v r9||   dk(  rt        | j                  |      |   ||<   /t        |||   |      ||<   C|||<   I |S )Nrh   )r   r   r    r   r  _decode_selective)rawdocfieldsr  r  r   r   s         rD   r  r    s    =778  **,' 
U&=c{a(]CCHC,UF3KOCCH JrF   c                     |j                   j                  st        | |      S |st        | |j                  d            S ddlm} |j                  |d      }t        | |      }t        |||      gS )a  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.

    :Parameters:
      - `data`: BSON data
      - `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``.
      - `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``.

    :Returns:
      - `document_list`: Single-member list containing the decoded document.

    .. versionadded:: 3.8
    N)r   r   )RawBSONDocument)r   r   )r   r   r  with_optionsbson.raw_bsonr  r   r  )rW   r  r  r  internal_codec_options_docs         rD   _decode_all_selectiver  )  s}    . &&33$..$ : : : NOO .*77&d 8 <56DdFM;<<rF   c              #      K   t        |t              st        d}t        |       dz
  }||k  r1t	        | |      d   }| |||z    }||z  }t        ||       ||k  r0yyw)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.

    :Parameters:
      - `data`: BSON data
      - `codec_options` (optional): 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   rh   N)rS   r   r  r   r`   r   )rW   r  rb   rm   r~   r  s         rD   decode_iterr  N  ss     ( m\2''H
d)a-C
S.#D(3A6H!45HHm44 S.s   AA A c              #      K   	 | j                  d      }|syt        |      dk7  rt        d      t        |d      d   dz
  }|| j                  t	        d|            z   }t        ||       lw)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.

    :Parameters:
      - `file_obj`: A file object containing BSON data.
      - `codec_options` (optional): 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_   zcut off in middle of objsizer   N)readr   r   r`   maxr   )file_objr  	size_datar~   r  s        rD   decode_file_iterr  o  sy     " MM!$	^q <==#Iq1!4q8x}}SH-=>>Hm44 s   A.A0c                 z    t        | t              st        d      	 t        | t               y# t
        $ r Y yw xY w)a:  Check that the given string represents valid :class:`BSON` data.

    Raises :class:`TypeError` if `bson` is not an instance of
    :class:`str` (:class:`bytes` in python 3). Returns ``True``
    if `bson` is valid :class:`BSON`, ``False`` otherwise.

    :Parameters:
      - `bson`: the data to be validated
    z4BSON data must be an instance of a subclass of bytesTF)rS   r   r~  r   r   r   )bsons    rD   is_validr    s?     dE"NOOd12 s   . 	::c                   0    e Zd ZdZedefd       ZefdZy)BSONzBSON (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.
    Fc                 (     | t        |||            S )aj  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:`basestring` (:class:`str` in python 3). Raises
        :class:`~bson.errors.InvalidDocument` if `document` cannot be
        converted to :class:`BSON`.

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

        .. versionchanged:: 3.0
           Replaced `uuid_subtype` option with `codec_options`.
        )rI   )clsr  r  r  s       rD   rI   zBSON.encode  s    0 6(J>??rF   c                     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'>

        :Parameters:
          - `codec_options` (optional): 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`.

        .. versionchanged:: 2.7
           Added `compile_re` option. If set to False, PyMongo represented BSON
           regular expressions as :class:`~bson.regex.Regex` objects instead of
           attempting to compile BSON regular expressions as Python native
           regular expressions, thus preventing errors for some incompatible
           patterns, see `PYTHON-500`_.

        .. _PYTHON-500: https://jira.mongodb.org/browse/PYTHON-500
        )r  )selfr  s     rD   r  zBSON.decode  s    P dM**rF   N)__name__
__module____qualname____doc__classmethodr   rI   r  rM   rF   rD   r  r    s-     ).2@ @2 $9 (+rF   r  c                      t         S )z"Is the C extension installed?
    )_USE_CrM   rF   rD   has_cr    s	     MrF   r@   )FF)T)r  r  r  r   platformr=  r{   r   uuidcodecsr   rj   r   r   bson.binaryr   r   r   r   r	   r
   r   r   	bson.coder   bson.codec_optionsr   r   r   
bson.dbrefr   bson.decimal128r   bson.errorsr   r   r   
bson.int64r   bson.max_keyr   bson.min_keyr   bson.objectidr   bson.py3compatr   r   r   r    r!   r"   r#   
bson.regexr$   bson.sonr%   r&   bson.timestampr'   bson.tz_utilr(   r  r)   r  ImportErrorfromtimestampr  utcfromtimestampr  BSONNUMBSONSTRBSONOBJBSONARRBSONBINBSONUNDBSONOIDBSONBOOBSONDATBSONNULBSONRGXBSONREFBSONCODBSONSYMBSONCWSBSONINTBSONTIMBSONLONBSONDECBSONMINBSONMAXStructunpack_fromrq   unpack_UNPACK_INTr`   r   r   r   rt   rE   rJ   r   r  rT   python_implementationrX   r]   rf   rn   rr   rx   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   packr  r  r!  r.  rQ  tupleranger   r   r   r   r  r  r  r  r  r  r  r"  r&  r)  r+  r0  r3  rE  rK  rO  rS  rU  rX  rZ  r\  booldictfloatrm  listr   UUIDMappingrk  rn  longrp  r  r  rG  r   r-  r~  r  rI   r  r  r  r  r  r  r  r  r  rM   rF   rD   <module>r     sM  2h     	  
 33 3 3 > >  &, ,    "% % %  ! $ F
 --a5003 



















 #V]]4(44 fmmD!(( 6==&22 +fmmE2>> !FMM$'33 &u-99  G!*$i0G$h "8!!#x/$D=
N?

N" $ N$N-BB ',3E
8AwAwA wA w	A
 wA w;A wA wA wA w;A wA wA wA wA w*A  w!A" w#A$ www?w?+A0 
F-(J

0 
((M fmmD!&&FMM$$$	$v}}U+00 V]]4 %%
&--&++=t==.2&
2 2 &J/
 H
LF(FHN5)
;
/
M6OJC
F&

,	= ' 	/	
 
=  	, | 
< 	J 	II| N 
< 	,  
=!" N#$ N%& 	=] "KK7	@ 			
 "IdO -9-- (-).2Hj>;$ 
((ME ( &79  !&5J >6  5 .@ $9 B0J 
""J&"=J %: 5B .C 5:(J+5 J+Z}#  Fs   *S? ?T
	T
