Skip to content

Commit b1ea391

Browse files
PYTHON-5679 Optimize ObjectId (#2656)
Co-authored-by: Steven Silvester <steven.silvester@ieee.org>
1 parent e507078 commit b1ea391

File tree

1 file changed

+18
-33
lines changed

1 file changed

+18
-33
lines changed

bson/objectid.py

Lines changed: 18 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,27 @@ def __init__(self, oid: Optional[Union[str, ObjectId, bytes]] = None) -> None:
9797
objectid.rst>`_.
9898
"""
9999
if oid is None:
100-
self.__generate()
100+
# Generate a new value for this ObjectId.
101+
with ObjectId._inc_lock:
102+
inc = ObjectId._inc
103+
ObjectId._inc = (inc + 1) % (_MAX_COUNTER_VALUE + 1)
104+
105+
# 4 bytes current time, 5 bytes random, 3 bytes inc.
106+
self.__id = _PACK_INT_RANDOM(int(time.time()), ObjectId._random()) + _PACK_INT(inc)[1:4]
101107
elif isinstance(oid, bytes) and len(oid) == 12:
102108
self.__id = oid
109+
elif isinstance(oid, str):
110+
if len(oid) == 24:
111+
try:
112+
self.__id = bytes.fromhex(oid)
113+
except (TypeError, ValueError):
114+
_raise_invalid_id(oid)
115+
else:
116+
_raise_invalid_id(oid)
117+
elif isinstance(oid, ObjectId):
118+
self.__id = oid.binary
103119
else:
104-
self.__validate(oid)
120+
raise TypeError(f"id must be an instance of (bytes, str, ObjectId), not {type(oid)}")
105121

106122
@classmethod
107123
def from_datetime(cls: Type[ObjectId], generation_time: datetime.datetime) -> ObjectId:
@@ -162,37 +178,6 @@ def _random(cls) -> bytes:
162178
cls.__random = _random_bytes()
163179
return cls.__random
164180

165-
def __generate(self) -> None:
166-
"""Generate a new value for this ObjectId."""
167-
with ObjectId._inc_lock:
168-
inc = ObjectId._inc
169-
ObjectId._inc = (inc + 1) % (_MAX_COUNTER_VALUE + 1)
170-
171-
# 4 bytes current time, 5 bytes random, 3 bytes inc.
172-
self.__id = _PACK_INT_RANDOM(int(time.time()), ObjectId._random()) + _PACK_INT(inc)[1:4]
173-
174-
def __validate(self, oid: Any) -> None:
175-
"""Validate and use the given id for this ObjectId.
176-
177-
Raises TypeError if id is not an instance of :class:`str`,
178-
:class:`bytes`, or ObjectId. Raises InvalidId if it is not a
179-
valid ObjectId.
180-
181-
:param oid: a valid ObjectId
182-
"""
183-
if isinstance(oid, ObjectId):
184-
self.__id = oid.binary
185-
elif isinstance(oid, str):
186-
if len(oid) == 24:
187-
try:
188-
self.__id = bytes.fromhex(oid)
189-
except (TypeError, ValueError):
190-
_raise_invalid_id(oid)
191-
else:
192-
_raise_invalid_id(oid)
193-
else:
194-
raise TypeError(f"id must be an instance of (bytes, str, ObjectId), not {type(oid)}")
195-
196181
@property
197182
def binary(self) -> bytes:
198183
"""12-byte binary representation of this ObjectId."""

0 commit comments

Comments
 (0)