@@ -236,10 +236,8 @@ def get_data_and_view(data: Any) -> Tuple[Any, memoryview]:
236
236
237
237
def _raise_unknown_type (element_type : int , element_name : str ) -> NoReturn :
238
238
"""Unknown type helper."""
239
- raise InvalidBSON (
240
- "Detected unknown BSON type %r for fieldname '%s'. Are "
241
- "you using the latest driver version?" % (chr (element_type ).encode (), element_name )
242
- )
239
+ msg = f"Detected unknown BSON type { chr (element_type ).encode ()!r} for fieldname '{ element_name } '. Are you using the latest driver version?"
240
+ raise InvalidBSON (msg )
243
241
244
242
245
243
def _get_int (
@@ -269,10 +267,12 @@ def _get_string(
269
267
length = _UNPACK_INT_FROM (data , position )[0 ]
270
268
position += 4
271
269
if length < 1 or obj_end - position < length :
272
- raise InvalidBSON ("invalid string length" )
270
+ msg = "invalid string length"
271
+ raise InvalidBSON (msg )
273
272
end = position + length - 1
274
273
if data [end ] != 0 :
275
- raise InvalidBSON ("invalid end of string" )
274
+ msg = "invalid end of string"
275
+ raise InvalidBSON (msg )
276
276
return _utf_8_decode (view [position :end ], opts .unicode_decode_error_handler , True )[0 ], end + 1
277
277
278
278
@@ -284,12 +284,15 @@ def _get_object_size(data: Any, position: int, obj_end: int) -> Tuple[int, int]:
284
284
raise InvalidBSON (str (exc ))
285
285
end = position + obj_size - 1
286
286
if data [end ] != 0 :
287
- raise InvalidBSON ("bad eoo" )
287
+ msg = "bad eoo"
288
+ raise InvalidBSON (msg )
288
289
if end >= obj_end :
289
- raise InvalidBSON ("invalid object length" )
290
+ msg = "invalid object length"
291
+ raise InvalidBSON (msg )
290
292
# If this is the top-level document, validate the total size too.
291
293
if position == 0 and obj_size != obj_end :
292
- raise InvalidBSON ("invalid object length" )
294
+ msg = "invalid object length"
295
+ raise InvalidBSON (msg )
293
296
return obj_size , end
294
297
295
298
@@ -321,7 +324,8 @@ def _get_array(
321
324
size = _UNPACK_INT_FROM (data , position )[0 ]
322
325
end = position + size - 1
323
326
if data [end ] != 0 :
324
- raise InvalidBSON ("bad eoo" )
327
+ msg = "bad eoo"
328
+ raise InvalidBSON (msg )
325
329
326
330
position += 4
327
331
end -= 1
@@ -352,7 +356,8 @@ def _get_array(
352
356
append (value )
353
357
354
358
if position != end + 1 :
355
- raise InvalidBSON ("bad array length" )
359
+ msg = "bad array length"
360
+ raise InvalidBSON (msg )
356
361
return result , position + 1
357
362
358
363
@@ -366,11 +371,13 @@ def _get_binary(
366
371
length2 = _UNPACK_INT_FROM (data , position )[0 ]
367
372
position += 4
368
373
if length2 != length - 4 :
369
- raise InvalidBSON ("invalid binary (st 2) - lengths don't match!" )
374
+ msg = "invalid binary (st 2) - lengths don't match!"
375
+ raise InvalidBSON (msg )
370
376
length = length2
371
377
end = position + length
372
378
if length < 0 or end > obj_end :
373
- raise InvalidBSON ("bad binary object length" )
379
+ msg = "bad binary object length"
380
+ raise InvalidBSON (msg )
374
381
375
382
# Convert UUID subtypes to native UUIDs.
376
383
if subtype in ALL_UUID_SUBTYPES :
@@ -437,7 +444,8 @@ def _get_code_w_scope(
437
444
code , position = _get_string (data , view , position + 4 , code_end , opts , element_name )
438
445
scope , position = _get_object (data , view , position , code_end , opts , element_name )
439
446
if position != code_end :
440
- raise InvalidBSON ("scope outside of javascript code boundaries" )
447
+ msg = "scope outside of javascript code boundaries"
448
+ raise InvalidBSON (msg )
441
449
return Code (code , scope ), position
442
450
443
451
@@ -587,7 +595,8 @@ def _elements_to_dict(
587
595
)
588
596
result [key ] = value
589
597
if position != obj_end :
590
- raise InvalidBSON ("bad object or element length" )
598
+ msg = "bad object or element length"
599
+ raise InvalidBSON (msg )
591
600
return result
592
601
593
602
@@ -637,15 +646,17 @@ def _make_c_string_check(string: Union[str, bytes]) -> bytes:
637
646
"""Make a 'C' string, checking for embedded NUL characters."""
638
647
if isinstance (string , bytes ):
639
648
if b"\x00 " in string :
640
- raise InvalidDocument ("BSON keys / regex patterns must not contain a NUL character" )
649
+ msg = "BSON keys / regex patterns must not contain a NUL character"
650
+ raise InvalidDocument (msg )
641
651
try :
642
652
_utf_8_decode (string , None , True )
643
653
return string + b"\x00 "
644
654
except UnicodeError :
645
655
raise InvalidStringData ("strings in documents must be valid UTF-8: %r" % string )
646
656
else :
647
657
if "\x00 " in string :
648
- raise InvalidDocument ("BSON keys / regex patterns must not contain a NUL character" )
658
+ msg = "BSON keys / regex patterns must not contain a NUL character"
659
+ raise InvalidDocument (msg )
649
660
return _utf_8_encode (string )[0 ] + b"\x00 "
650
661
651
662
@@ -665,7 +676,8 @@ def _make_name(string: str) -> bytes:
665
676
"""Make a 'C' string suitable for a BSON key."""
666
677
# Keys can only be text in python 3.
667
678
if "\x00 " in string :
668
- raise InvalidDocument ("BSON keys / regex patterns must not contain a NUL character" )
679
+ msg = "BSON keys / regex patterns must not contain a NUL character"
680
+ raise InvalidDocument (msg )
669
681
return _utf_8_encode (string )[0 ] + b"\x00 "
670
682
671
683
@@ -805,7 +817,8 @@ def _encode_int(name: bytes, value: int, dummy0: Any, dummy1: Any) -> bytes:
805
817
try :
806
818
return b"\x12 " + name + _PACK_LONG (value )
807
819
except struct .error :
808
- raise OverflowError ("BSON can only handle up to 8-byte ints" )
820
+ msg = "BSON can only handle up to 8-byte ints"
821
+ raise OverflowError (msg )
809
822
810
823
811
824
def _encode_timestamp (name : bytes , value : Any , dummy0 : Any , dummy1 : Any ) -> bytes :
@@ -818,7 +831,8 @@ def _encode_long(name: bytes, value: Any, dummy0: Any, dummy1: Any) -> bytes:
818
831
try :
819
832
return b"\x12 " + name + _PACK_LONG (value )
820
833
except struct .error :
821
- raise OverflowError ("BSON can only handle up to 8-byte ints" )
834
+ msg = "BSON can only handle up to 8-byte ints"
835
+ raise OverflowError (msg )
822
836
823
837
824
838
def _encode_decimal128 (name : bytes , value : Decimal128 , dummy0 : Any , dummy1 : Any ) -> bytes :
@@ -941,18 +955,22 @@ def _name_value_to_bson(
941
955
name , fallback_encoder (value ), check_keys , opts , in_fallback_call = True
942
956
)
943
957
944
- raise InvalidDocument (f"cannot encode object: { value !r} , of type: { type (value )!r} " )
958
+ msg = f"cannot encode object: { value !r} , of type: { type (value )!r} "
959
+ raise InvalidDocument (msg )
945
960
946
961
947
962
def _element_to_bson (key : Any , value : Any , check_keys : bool , opts : CodecOptions ) -> bytes :
948
963
"""Encode a single key, value pair."""
949
964
if not isinstance (key , str ):
950
- raise InvalidDocument (f"documents must have only string keys, key was { key !r} " )
965
+ msg = f"documents must have only string keys, key was { key !r} "
966
+ raise InvalidDocument (msg )
951
967
if check_keys :
952
968
if key .startswith ("$" ):
953
- raise InvalidDocument (f"key { key !r} must not start with '$'" )
969
+ msg = f"key { key !r} must not start with '$'"
970
+ raise InvalidDocument (msg )
954
971
if "." in key :
955
- raise InvalidDocument (f"key { key !r} must not contain '.'" )
972
+ msg = f"key { key !r} must not contain '.'"
973
+ raise InvalidDocument (msg )
956
974
957
975
name = _make_name (key )
958
976
return _name_value_to_bson (name , value , check_keys , opts )
@@ -970,7 +988,8 @@ def _dict_to_bson(doc: Any, check_keys: bool, opts: CodecOptions, top_level: boo
970
988
if not top_level or key != "_id" :
971
989
elements .append (_element_to_bson (key , value , check_keys , opts ))
972
990
except AttributeError :
973
- raise TypeError (f"encoder expected a mapping type but got: { doc !r} " )
991
+ msg = f"encoder expected a mapping type but got: { doc !r} "
992
+ raise TypeError (msg )
974
993
975
994
encoded = b"" .join (elements )
976
995
return _PACK_INT (len (encoded ) + 5 ) + encoded + b"\x00 "
@@ -1063,10 +1082,12 @@ def _decode_all(
1063
1082
while position < end :
1064
1083
obj_size = _UNPACK_INT_FROM (data , position )[0 ]
1065
1084
if data_len - position < obj_size :
1066
- raise InvalidBSON ("invalid object size" )
1085
+ msg = "invalid object size"
1086
+ raise InvalidBSON (msg )
1067
1087
obj_end = position + obj_size - 1
1068
1088
if data [obj_end ] != 0 :
1069
- raise InvalidBSON ("bad eoo" )
1089
+ msg = "bad eoo"
1090
+ raise InvalidBSON (msg )
1070
1091
if use_raw :
1071
1092
docs .append (opts .document_class (data [position : obj_end + 1 ], opts )) # type: ignore
1072
1093
else :
@@ -1152,7 +1173,8 @@ def _array_of_documents_to_buffer(view: memoryview) -> bytes:
1152
1173
append (view [position : position + obj_size ])
1153
1174
position += obj_size
1154
1175
if position != end :
1155
- raise InvalidBSON ("bad object or element length" )
1176
+ msg = "bad object or element length"
1177
+ raise InvalidBSON (msg )
1156
1178
return b"" .join (buffers )
1157
1179
1158
1180
@@ -1283,7 +1305,8 @@ def decode_file_iter(
1283
1305
if not size_data :
1284
1306
break # Finished with file normally.
1285
1307
elif len (size_data ) != 4 :
1286
- raise InvalidBSON ("cut off in middle of objsize" )
1308
+ msg = "cut off in middle of objsize"
1309
+ raise InvalidBSON (msg )
1287
1310
obj_size = _UNPACK_INT_FROM (size_data , 0 )[0 ] - 4
1288
1311
elements = size_data + file_obj .read (max (0 , obj_size ))
1289
1312
yield _bson_to_dict (elements , opts )
@@ -1300,7 +1323,8 @@ def is_valid(bson: bytes) -> bool:
1300
1323
- `bson`: the data to be validated
1301
1324
"""
1302
1325
if not isinstance (bson , bytes ):
1303
- raise TypeError ("BSON data must be an instance of a subclass of bytes" )
1326
+ msg = "BSON data must be an instance of a subclass of bytes"
1327
+ raise TypeError (msg )
1304
1328
1305
1329
try :
1306
1330
_bson_to_dict (bson , DEFAULT_CODEC_OPTIONS )
0 commit comments