U
    ~fh#                     @  s   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	m
Z
 ddlmZmZmZmZmZ ddlmZ ddlmZ ddlmZ d	Zed
jZedjZed
jZdddddZddddZG dd dZ dS )z)Tools for working with MongoDB ObjectIds.    )annotationsN)SystemRandom)AnyNoReturnOptionalTypeUnion)_datetime_to_millis	InvalidId)utci z>Iz>I5sstrr   oidreturnc                 C  s   t d|  d S )NzS%r is not a valid ObjectId, it must be a 12-byte input or a 24-character hex stringr
   )r    r   1/tmp/pip-unpacked-wheel-36gvocj8/bson/objectid.py_raise_invalid_id%   s
    r   bytesr   c                   C  s
   t dS )z+Get the 5-byte random field of an ObjectId.   )osurandomr   r   r   r   _random_bytes,   s    r   c                   @  sv  e Zd ZdZe Ze de	Z
e Ze ZdZdZd;dddd	d
Zeddd dddZeddddddZeddddZddddZdddddZeddddZedddd Zddd!d"Zddd#d$d%Zd&dd'd(Zd&dd)d*Zddd+d,d-Z ddd+d.d/Z!ddd+d0d1Z"ddd+d2d3Z#ddd+d4d5Z$ddd+d6d7Z%d8dd9d:Z&dS )<ObjectIdzA MongoDB ObjectId.r   )Z__id   Nz%Optional[Union[str, ObjectId, bytes]]Noner   c                 C  s>   |dkr|    n(t|tr0t|dkr0|| _n
| | dS )aZ  Initialize a new ObjectId.

        An ObjectId is a 12-byte unique identifier consisting of:

          - a 4-byte value representing the seconds since the Unix epoch,
          - a 5-byte random value,
          - a 3-byte counter, starting with a random value.

        By default, ``ObjectId()`` creates a new unique identifier. The
        optional parameter `oid` can be an :class:`ObjectId`, or any 12
        :class:`bytes`.

        For example, the 12 bytes b'foo-bar-quux' do not follow the ObjectId
        specification but they are acceptable input::

          >>> ObjectId(b'foo-bar-quux')
          ObjectId('666f6f2d6261722d71757578')

        `oid` can also be a :class:`str` of 24 hex digits::

          >>> ObjectId('0123456789ab0123456789ab')
          ObjectId('0123456789ab0123456789ab')

        Raises :class:`~bson.errors.InvalidId` if `oid` is not 12 bytes nor
        24 hex digits, or :class:`TypeError` if `oid` is not an accepted type.

        :param oid: a valid ObjectId.

        .. seealso:: The MongoDB documentation on  `ObjectIds <http://dochub.mongodb.org/core/objectids>`_.

        .. versionchanged:: 3.8
           :class:`~bson.objectid.ObjectId` now implements the `ObjectID
           specification version 0.2
           <https://github.com/mongodb/specifications/blob/master/source/
           objectid.rst>`_.
        N   )_ObjectId__generate
isinstancer   len_ObjectId__id_ObjectId__validateselfr   r   r   r   __init__?   s
    %
zObjectId.__init__zType[ObjectId]zdatetime.datetime)clsgeneration_timer   c                 C  s   t t|d d }| |S )aJ  Create a dummy ObjectId instance with a specific generation time.

        This method is useful for doing range queries on a field
        containing :class:`ObjectId` instances.

        .. warning::
           It is not safe to insert a document containing an ObjectId
           generated using this method. This method deliberately
           eliminates the uniqueness guarantee that ObjectIds
           generally provide. ObjectIds generated with this method
           should be used exclusively in queries.

        `generation_time` will be converted to UTC. Naive datetime
        instances will be treated as though they already contain UTC.

        An example using this helper to get documents where ``"_id"``
        was generated before January 1, 2010 would be:

        >>> gen_time = datetime.datetime(2010, 1, 1)
        >>> dummy_id = ObjectId.from_datetime(gen_time)
        >>> result = collection.find({"_id": {"$lt": dummy_id}})

        :param generation_time: :class:`~datetime.datetime` to be used
            as the generation time for the resulting ObjectId.
        i  s           )	_PACK_INTr	   )r&   r'   r   r   r   r   from_datetimek   s
    zObjectId.from_datetimer   bool)r&   r   r   c              	   C  s6   |sdS zt | W dS  ttfk
r0   Y dS X dS )zChecks if a `oid` string is valid or not.

        :param oid: the object id to validate

        .. versionadded:: 2.3
        FTN)r   r   	TypeError)r&   r   r   r   r   is_valid   s    zObjectId.is_validr   r   c                 C  s&   t  }|| jkr || _t | _| jS )z1Generate a 5-byte random number once per process.)r   getpid_pidr   _ObjectId__random)r&   pidr   r   r   _random   s
    
zObjectId._randomc              	   C  sV   t j t j}|d td  t _W 5 Q R X ttt t  t|dd  | _	dS )z'Generate a new value for this ObjectId.      N)
r   	_inc_lock_inc_MAX_COUNTER_VALUE_PACK_INT_RANDOMinttimer1   r(   r!   )r$   incr   r   r   Z
__generate   s    zObjectId.__generatec              	   C  s~   t |tr|j| _nft |trht|dkr^zt|| _W qf tt	fk
rZ   t
| Y qfX qzt
| ntdt| dS )a   Validate and use the given id for this ObjectId.

        Raises TypeError if id is not an instance of :class:`str`,
        :class:`bytes`, or ObjectId. Raises InvalidId if it is not a
        valid ObjectId.

        :param oid: a valid ObjectId
           z6id must be an instance of (bytes, str, ObjectId), not N)r   r   binaryr!   r   r    r   fromhexr+   
ValueErrorr   typer#   r   r   r   Z
__validate   s    	



zObjectId.__validatec                 C  s   | j S )z/12-byte binary representation of this ObjectId.r!   r$   r   r   r   r<      s    zObjectId.binaryc                 C  s$   t | jdd d }tj|tS )a	  A :class:`datetime.datetime` instance representing the time of
        generation for this :class:`ObjectId`.

        The :class:`datetime.datetime` is timezone aware, and
        represents the generation time in UTC. It is precise to the
        second.
        r   r3   )_UNPACK_INTr!   datetimefromtimestampr   )r$   	timestampr   r   r   r'      s    	zObjectId.generation_timec                 C  s   | j S )zdReturn value of object for pickling.
        needed explicitly because __slots__() defined.
        r@   rA   r   r   r   __getstate__   s    zObjectId.__getstate__)valuer   c                 C  s:   t |tr|d }n|}t |tr0|d| _n|| _dS )z Explicit state set from picklingr!   zlatin-1N)r   dictr   encoder!   )r$   rG   r   r   r   r   __setstate__   s    


zObjectId.__setstate__r   c                 C  s   t | j S N)binasciihexlifyr!   decoderA   r   r   r   __str__   s    zObjectId.__str__c                 C  s   d| dS )Nz
ObjectId('z')r   rA   r   r   r   __repr__   s    zObjectId.__repr__)otherr   c                 C  s   t |tr| j|jkS tS rK   r   r   r!   r<   NotImplementedr$   rQ   r   r   r   __eq__   s    
zObjectId.__eq__c                 C  s   t |tr| j|jkS tS rK   rR   rT   r   r   r   __ne__   s    
zObjectId.__ne__c                 C  s   t |tr| j|jk S tS rK   rR   rT   r   r   r   __lt__   s    
zObjectId.__lt__c                 C  s   t |tr| j|jkS tS rK   rR   rT   r   r   r   __le__  s    
zObjectId.__le__c                 C  s   t |tr| j|jkS tS rK   rR   rT   r   r   r   __gt__  s    
zObjectId.__gt__c                 C  s   t |tr| j|jkS tS rK   rR   rT   r   r   r   __ge__  s    
zObjectId.__ge__r8   c                 C  s
   t | jS )z,Get a hash value for this :class:`ObjectId`.)hashr!   rA   r   r   r   __hash__  s    zObjectId.__hash__)N)'__name__
__module____qualname____doc__r   r-   r.   r   randintr6   r5   	threadingLockr4   r   r/   	__slots__Z_type_markerr%   classmethodr)   r,   r1   r   r"   propertyr<   r'   rF   rJ   rO   rP   rU   rV   rW   rX   rY   rZ   r\   r   r   r   r   r   1   s>   , 	r   )!r`   
__future__r   rL   rC   r   structrb   r9   randomr   typingr   r   r   r   r   Zbson.datetime_msr	   Zbson.errorsr   Zbson.tz_utilr   r6   Structpackr(   r7   unpackrB   r   r   r   r   r   r   r   <module>   s&   