forked from mongodb/mongo-python-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_cbsonmodule.c
More file actions
3033 lines (2822 loc) · 95.3 KB
/
_cbsonmodule.c
File metadata and controls
3033 lines (2822 loc) · 95.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2009-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file contains C implementations of some of the functions
* needed by the bson module. If possible, these implementations
* should be used to speed up BSON encoding and decoding.
*/
#include "Python.h"
#include "datetime.h"
#include "buffer.h"
#include "time64.h"
#include "encoding_helpers.h"
#define _CBSON_MODULE
#include "_cbsonmodule.h"
/* New module state and initialization code.
* See the module-initialization-and-state
* section in the following doc:
* http://docs.python.org/release/3.1.3/howto/cporting.html
* which references the following pep:
* http://www.python.org/dev/peps/pep-3121/
* */
struct module_state {
PyObject* Binary;
PyObject* Code;
PyObject* ObjectId;
PyObject* DBRef;
PyObject* Regex;
PyObject* UUID;
PyObject* Timestamp;
PyObject* MinKey;
PyObject* MaxKey;
PyObject* UTC;
PyTypeObject* REType;
PyObject* BSONInt64;
PyObject* Decimal128;
PyObject* Mapping;
PyObject* CodecOptions;
};
/* The Py_TYPE macro was introduced in CPython 2.6 */
#ifndef Py_TYPE
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#endif
#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif
/* Maximum number of regex flags */
#define FLAGS_SIZE 7
/* Default UUID representation type code. */
#define PYTHON_LEGACY 3
/* Other UUID representations. */
#define STANDARD 4
#define JAVA_LEGACY 5
#define CSHARP_LEGACY 6
#define BSON_MAX_SIZE 2147483647
/* The smallest possible BSON document, i.e. "{}" */
#define BSON_MIN_SIZE 5
/* Get an error class from the bson.errors module.
*
* Returns a new ref */
static PyObject* _error(char* name) {
PyObject* error;
PyObject* errors = PyImport_ImportModule("bson.errors");
if (!errors) {
return NULL;
}
error = PyObject_GetAttrString(errors, name);
Py_DECREF(errors);
return error;
}
/* Safely downcast from Py_ssize_t to int, setting an
* exception and returning -1 on error. */
static int
_downcast_and_check(Py_ssize_t size, uint8_t extra) {
if (size > BSON_MAX_SIZE || ((BSON_MAX_SIZE - extra) < size)) {
PyObject* InvalidStringData = _error("InvalidStringData");
if (InvalidStringData) {
PyErr_SetString(InvalidStringData,
"String length must be <= 2147483647");
Py_DECREF(InvalidStringData);
}
return -1;
}
return (int)size + extra;
}
static PyObject* elements_to_dict(PyObject* self, const char* string,
unsigned max,
const codec_options_t* options);
static int _write_element_to_buffer(PyObject* self, buffer_t buffer,
int type_byte, PyObject* value,
unsigned char check_keys,
const codec_options_t* options);
/* Date stuff */
static PyObject* datetime_from_millis(long long millis) {
/* To encode a datetime instance like datetime(9999, 12, 31, 23, 59, 59, 999999)
* we follow these steps:
* 1. Calculate a timestamp in seconds: 253402300799
* 2. Multiply that by 1000: 253402300799000
* 3. Add in microseconds divided by 1000 253402300799999
*
* (Note: BSON doesn't support microsecond accuracy, hence the rounding.)
*
* To decode we could do:
* 1. Get seconds: timestamp / 1000: 253402300799
* 2. Get micros: (timestamp % 1000) * 1000: 999000
* Resulting in datetime(9999, 12, 31, 23, 59, 59, 999000) -- the expected result
*
* Now what if the we encode (1, 1, 1, 1, 1, 1, 111111)?
* 1. and 2. gives: -62135593139000
* 3. Gives us: -62135593138889
*
* Now decode:
* 1. Gives us: -62135593138
* 2. Gives us: -889000
* Resulting in datetime(1, 1, 1, 1, 1, 2, 15888216) -- an invalid result
*
* If instead to decode we do:
* diff = ((millis % 1000) + 1000) % 1000: 111
* seconds = (millis - diff) / 1000: -62135593139
* micros = diff * 1000 111000
* Resulting in datetime(1, 1, 1, 1, 1, 1, 111000) -- the expected result
*/
int diff = (int)(((millis % 1000) + 1000) % 1000);
int microseconds = diff * 1000;
Time64_T seconds = (millis - diff) / 1000;
struct TM timeinfo;
gmtime64_r(&seconds, &timeinfo);
return PyDateTime_FromDateAndTime(timeinfo.tm_year + 1900,
timeinfo.tm_mon + 1,
timeinfo.tm_mday,
timeinfo.tm_hour,
timeinfo.tm_min,
timeinfo.tm_sec,
microseconds);
}
static long long millis_from_datetime(PyObject* datetime) {
struct TM timeinfo;
long long millis;
timeinfo.tm_year = PyDateTime_GET_YEAR(datetime) - 1900;
timeinfo.tm_mon = PyDateTime_GET_MONTH(datetime) - 1;
timeinfo.tm_mday = PyDateTime_GET_DAY(datetime);
timeinfo.tm_hour = PyDateTime_DATE_GET_HOUR(datetime);
timeinfo.tm_min = PyDateTime_DATE_GET_MINUTE(datetime);
timeinfo.tm_sec = PyDateTime_DATE_GET_SECOND(datetime);
millis = timegm64(&timeinfo) * 1000;
millis += PyDateTime_DATE_GET_MICROSECOND(datetime) / 1000;
return millis;
}
/* Just make this compatible w/ the old API. */
int buffer_write_bytes(buffer_t buffer, const char* data, int size) {
if (buffer_write(buffer, data, size)) {
PyErr_NoMemory();
return 0;
}
return 1;
}
int buffer_write_double(buffer_t buffer, double data) {
double data_le = BSON_DOUBLE_TO_LE(data);
return buffer_write_bytes(buffer, (const char*)&data_le, 8);
}
int buffer_write_int32(buffer_t buffer, int32_t data) {
uint32_t data_le = BSON_UINT32_TO_LE(data);
return buffer_write_bytes(buffer, (const char*)&data_le, 4);
}
int buffer_write_int64(buffer_t buffer, int64_t data) {
uint64_t data_le = BSON_UINT64_TO_LE(data);
return buffer_write_bytes(buffer, (const char*)&data_le, 8);
}
void buffer_write_int32_at_position(buffer_t buffer,
int position,
int32_t data) {
uint32_t data_le = BSON_UINT32_TO_LE(data);
memcpy(buffer_get_buffer(buffer) + position, &data_le, 4);
}
static int write_unicode(buffer_t buffer, PyObject* py_string) {
int size;
const char* data;
PyObject* encoded = PyUnicode_AsUTF8String(py_string);
if (!encoded) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
data = PyBytes_AS_STRING(encoded);
#else
data = PyString_AS_STRING(encoded);
#endif
if (!data)
goto unicodefail;
#if PY_MAJOR_VERSION >= 3
if ((size = _downcast_and_check(PyBytes_GET_SIZE(encoded), 1)) == -1)
#else
if ((size = _downcast_and_check(PyString_GET_SIZE(encoded), 1)) == -1)
#endif
goto unicodefail;
if (!buffer_write_int32(buffer, (int32_t)size))
goto unicodefail;
if (!buffer_write_bytes(buffer, data, size))
goto unicodefail;
Py_DECREF(encoded);
return 1;
unicodefail:
Py_DECREF(encoded);
return 0;
}
/* returns 0 on failure */
static int write_string(buffer_t buffer, PyObject* py_string) {
int size;
const char* data;
#if PY_MAJOR_VERSION >= 3
if (PyUnicode_Check(py_string)){
return write_unicode(buffer, py_string);
}
data = PyBytes_AsString(py_string);
#else
data = PyString_AsString(py_string);
#endif
if (!data) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
if ((size = _downcast_and_check(PyBytes_Size(py_string), 1)) == -1)
#else
if ((size = _downcast_and_check(PyString_Size(py_string), 1)) == -1)
#endif
return 0;
if (!buffer_write_int32(buffer, (int32_t)size)) {
return 0;
}
if (!buffer_write_bytes(buffer, data, size)) {
return 0;
}
return 1;
}
/*
* Are we in the main interpreter or a sub-interpreter?
* Useful for deciding if we can use cached pure python
* types in mod_wsgi.
*/
static int
_in_main_interpreter(void) {
static PyInterpreterState* main_interpreter = NULL;
PyInterpreterState* interpreter;
if (main_interpreter == NULL) {
interpreter = PyInterpreterState_Head();
while (PyInterpreterState_Next(interpreter))
interpreter = PyInterpreterState_Next(interpreter);
main_interpreter = interpreter;
}
return (main_interpreter == PyThreadState_Get()->interp);
}
/*
* Get a reference to a pure python type. If we are in the
* main interpreter return the cached object, otherwise import
* the object we need and return it instead.
*/
static PyObject*
_get_object(PyObject* object, char* module_name, char* object_name) {
if (_in_main_interpreter()) {
Py_XINCREF(object);
return object;
} else {
PyObject* imported = NULL;
PyObject* module = PyImport_ImportModule(module_name);
if (!module)
return NULL;
imported = PyObject_GetAttrString(module, object_name);
Py_DECREF(module);
return imported;
}
}
/* Load a Python object to cache.
*
* Returns non-zero on failure. */
static int _load_object(PyObject** object, char* module_name, char* object_name) {
PyObject* module;
module = PyImport_ImportModule(module_name);
if (!module) {
return 1;
}
*object = PyObject_GetAttrString(module, object_name);
Py_DECREF(module);
return (*object) ? 0 : 2;
}
/* Load all Python objects to cache.
*
* Returns non-zero on failure. */
static int _load_python_objects(PyObject* module) {
PyObject* empty_string;
PyObject* re_compile;
PyObject* compiled;
struct module_state *state = GETSTATE(module);
if (_load_object(&state->Binary, "bson.binary", "Binary") ||
_load_object(&state->Code, "bson.code", "Code") ||
_load_object(&state->ObjectId, "bson.objectid", "ObjectId") ||
_load_object(&state->DBRef, "bson.dbref", "DBRef") ||
_load_object(&state->Timestamp, "bson.timestamp", "Timestamp") ||
_load_object(&state->MinKey, "bson.min_key", "MinKey") ||
_load_object(&state->MaxKey, "bson.max_key", "MaxKey") ||
_load_object(&state->UTC, "bson.tz_util", "utc") ||
_load_object(&state->Regex, "bson.regex", "Regex") ||
_load_object(&state->BSONInt64, "bson.int64", "Int64") ||
_load_object(&state->Decimal128, "bson.decimal128", "Decimal128") ||
_load_object(&state->UUID, "uuid", "UUID") ||
#if PY_MAJOR_VERSION >= 3
_load_object(&state->Mapping, "collections.abc", "Mapping") ||
#else
_load_object(&state->Mapping, "collections", "Mapping") ||
#endif
_load_object(&state->CodecOptions, "bson.codec_options", "CodecOptions")) {
return 1;
}
/* Reload our REType hack too. */
#if PY_MAJOR_VERSION >= 3
empty_string = PyBytes_FromString("");
#else
empty_string = PyString_FromString("");
#endif
if (empty_string == NULL) {
state->REType = NULL;
return 1;
}
if (_load_object(&re_compile, "re", "compile")) {
state->REType = NULL;
Py_DECREF(empty_string);
return 1;
}
compiled = PyObject_CallFunction(re_compile, "O", empty_string);
Py_DECREF(re_compile);
if (compiled == NULL) {
state->REType = NULL;
Py_DECREF(empty_string);
return 1;
}
Py_INCREF(Py_TYPE(compiled));
state->REType = Py_TYPE(compiled);
Py_DECREF(empty_string);
Py_DECREF(compiled);
return 0;
}
/*
* Get the _type_marker from an Object.
*
* Return the type marker, 0 if there is no marker, or -1 on failure.
*/
static long _type_marker(PyObject* object) {
PyObject* type_marker = NULL;
long type = 0;
if (PyObject_HasAttrString(object, "_type_marker")) {
type_marker = PyObject_GetAttrString(object, "_type_marker");
if (type_marker == NULL) {
return -1;
}
}
/*
* Python objects with broken __getattr__ implementations could return
* arbitrary types for a call to PyObject_GetAttrString. For example
* pymongo.database.Database returns a new Collection instance for
* __getattr__ calls with names that don't match an existing attribute
* or method. In some cases "value" could be a subtype of something
* we know how to serialize. Make a best effort to encode these types.
*/
#if PY_MAJOR_VERSION >= 3
if (type_marker && PyLong_CheckExact(type_marker)) {
type = PyLong_AsLong(type_marker);
#else
if (type_marker && PyInt_CheckExact(type_marker)) {
type = PyInt_AsLong(type_marker);
#endif
Py_DECREF(type_marker);
/*
* Py(Long|Int)_AsLong returns -1 for error but -1 is a valid value
* so we call PyErr_Occurred to differentiate.
*/
if (type == -1 && PyErr_Occurred()) {
return -1;
}
} else {
Py_XDECREF(type_marker);
}
return type;
}
/* Fill out a codec_options_t* from a CodecOptions object. Use with the "O&"
* format spec in PyArg_ParseTuple.
*
* Return 1 on success. options->document_class is a new reference.
* Return 0 on failure.
*/
int convert_codec_options(PyObject* options_obj, void* p) {
codec_options_t* options = (codec_options_t*)p;
long type_marker;
options->unicode_decode_error_handler = NULL;
if (!PyArg_ParseTuple(options_obj, "ObbzO",
&options->document_class,
&options->tz_aware,
&options->uuid_rep,
&options->unicode_decode_error_handler,
&options->tzinfo)) {
return 0;
}
type_marker = _type_marker(options->document_class);
if (type_marker < 0) return 0;
Py_INCREF(options->document_class);
Py_INCREF(options->tzinfo);
options->options_obj = options_obj;
Py_INCREF(options->options_obj);
options->is_raw_bson = (101 == type_marker);
return 1;
}
/* Fill out a codec_options_t* with default options.
*
* Return 1 on success.
* Return 0 on failure.
*/
int default_codec_options(struct module_state* state, codec_options_t* options) {
PyObject* options_obj = NULL;
PyObject* codec_options_func = _get_object(
state->CodecOptions, "bson.codec_options", "CodecOptions");
if (codec_options_func == NULL) {
return 0;
}
options_obj = PyObject_CallFunctionObjArgs(codec_options_func, NULL);
Py_DECREF(codec_options_func);
if (options_obj == NULL) {
return 0;
}
return convert_codec_options(options_obj, options);
}
void destroy_codec_options(codec_options_t* options) {
Py_CLEAR(options->document_class);
Py_CLEAR(options->tzinfo);
Py_CLEAR(options->options_obj);
}
static int write_element_to_buffer(PyObject* self, buffer_t buffer,
int type_byte, PyObject* value,
unsigned char check_keys,
const codec_options_t* options) {
int result;
if(Py_EnterRecursiveCall(" while encoding an object to BSON "))
return 0;
result = _write_element_to_buffer(self, buffer, type_byte,
value, check_keys, options);
Py_LeaveRecursiveCall();
return result;
}
static void
_fix_java(const char* in, char* out) {
int i, j;
for (i = 0, j = 7; i < j; i++, j--) {
out[i] = in[j];
out[j] = in[i];
}
for (i = 8, j = 15; i < j; i++, j--) {
out[i] = in[j];
out[j] = in[i];
}
}
static void
_set_cannot_encode(PyObject* value) {
PyObject* InvalidDocument = _error("InvalidDocument");
if (InvalidDocument) {
PyObject* repr = PyObject_Repr(value);
if (repr) {
#if PY_MAJOR_VERSION >= 3
PyObject* errmsg = PyUnicode_FromString("Cannot encode object: ");
#else
PyObject* errmsg = PyString_FromString("Cannot encode object: ");
#endif
if (errmsg) {
#if PY_MAJOR_VERSION >= 3
PyObject* error = PyUnicode_Concat(errmsg, repr);
if (error) {
PyErr_SetObject(InvalidDocument, error);
Py_DECREF(error);
}
Py_DECREF(errmsg);
Py_DECREF(repr);
#else
PyString_ConcatAndDel(&errmsg, repr);
if (errmsg) {
PyErr_SetObject(InvalidDocument, errmsg);
Py_DECREF(errmsg);
}
#endif
} else {
Py_DECREF(repr);
}
}
Py_DECREF(InvalidDocument);
}
}
/*
* Encode a builtin Python regular expression or our custom Regex class.
*
* Sets exception and returns 0 on failure.
*/
static int _write_regex_to_buffer(
buffer_t buffer, int type_byte, PyObject* value) {
PyObject* py_flags;
PyObject* py_pattern;
PyObject* encoded_pattern;
long int_flags;
char flags[FLAGS_SIZE];
char check_utf8 = 0;
const char* pattern_data;
int pattern_length, flags_length;
result_t status;
/*
* Both the builtin re type and our Regex class have attributes
* "flags" and "pattern".
*/
py_flags = PyObject_GetAttrString(value, "flags");
if (!py_flags) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
int_flags = PyLong_AsLong(py_flags);
#else
int_flags = PyInt_AsLong(py_flags);
#endif
Py_DECREF(py_flags);
if (int_flags == -1 && PyErr_Occurred()) {
return 0;
}
py_pattern = PyObject_GetAttrString(value, "pattern");
if (!py_pattern) {
return 0;
}
if (PyUnicode_Check(py_pattern)) {
encoded_pattern = PyUnicode_AsUTF8String(py_pattern);
Py_DECREF(py_pattern);
if (!encoded_pattern) {
return 0;
}
} else {
encoded_pattern = py_pattern;
check_utf8 = 1;
}
#if PY_MAJOR_VERSION >= 3
if (!(pattern_data = PyBytes_AsString(encoded_pattern))) {
Py_DECREF(encoded_pattern);
return 0;
}
if ((pattern_length = _downcast_and_check(PyBytes_Size(encoded_pattern), 0)) == -1) {
Py_DECREF(encoded_pattern);
return 0;
}
#else
if (!(pattern_data = PyString_AsString(encoded_pattern))) {
Py_DECREF(encoded_pattern);
return 0;
}
if ((pattern_length = _downcast_and_check(PyString_Size(encoded_pattern), 0)) == -1) {
Py_DECREF(encoded_pattern);
return 0;
}
#endif
status = check_string((const unsigned char*)pattern_data,
pattern_length, check_utf8, 1);
if (status == NOT_UTF_8) {
PyObject* InvalidStringData = _error("InvalidStringData");
if (InvalidStringData) {
PyErr_SetString(InvalidStringData,
"regex patterns must be valid UTF-8");
Py_DECREF(InvalidStringData);
}
Py_DECREF(encoded_pattern);
return 0;
} else if (status == HAS_NULL) {
PyObject* InvalidDocument = _error("InvalidDocument");
if (InvalidDocument) {
PyErr_SetString(InvalidDocument,
"regex patterns must not contain the NULL byte");
Py_DECREF(InvalidDocument);
}
Py_DECREF(encoded_pattern);
return 0;
}
if (!buffer_write_bytes(buffer, pattern_data, pattern_length + 1)) {
Py_DECREF(encoded_pattern);
return 0;
}
Py_DECREF(encoded_pattern);
flags[0] = 0;
if (int_flags & 2) {
STRCAT(flags, FLAGS_SIZE, "i");
}
if (int_flags & 4) {
STRCAT(flags, FLAGS_SIZE, "l");
}
if (int_flags & 8) {
STRCAT(flags, FLAGS_SIZE, "m");
}
if (int_flags & 16) {
STRCAT(flags, FLAGS_SIZE, "s");
}
if (int_flags & 32) {
STRCAT(flags, FLAGS_SIZE, "u");
}
if (int_flags & 64) {
STRCAT(flags, FLAGS_SIZE, "x");
}
flags_length = (int)strlen(flags) + 1;
if (!buffer_write_bytes(buffer, flags, flags_length)) {
return 0;
}
*(buffer_get_buffer(buffer) + type_byte) = 0x0B;
return 1;
}
/* Write a single value to the buffer (also write its type_byte, for which
* space has already been reserved.
*
* returns 0 on failure */
static int _write_element_to_buffer(PyObject* self, buffer_t buffer,
int type_byte, PyObject* value,
unsigned char check_keys,
const codec_options_t* options) {
struct module_state *state = GETSTATE(self);
PyObject* mapping_type;
PyObject* uuid_type;
/*
* Don't use PyObject_IsInstance for our custom types. It causes
* problems with python sub interpreters. Our custom types should
* have a _type_marker attribute, which we can switch on instead.
*/
long type = _type_marker(value);
if (type < 0) {
return 0;
}
switch (type) {
case 5:
{
/* Binary */
PyObject* subtype_object;
char subtype;
const char* data;
int size;
*(buffer_get_buffer(buffer) + type_byte) = 0x05;
subtype_object = PyObject_GetAttrString(value, "subtype");
if (!subtype_object) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
subtype = (char)PyLong_AsLong(subtype_object);
#else
subtype = (char)PyInt_AsLong(subtype_object);
#endif
if (subtype == -1) {
Py_DECREF(subtype_object);
return 0;
}
#if PY_MAJOR_VERSION >= 3
size = _downcast_and_check(PyBytes_Size(value), 0);
#else
size = _downcast_and_check(PyString_Size(value), 0);
#endif
if (size == -1) {
Py_DECREF(subtype_object);
return 0;
}
Py_DECREF(subtype_object);
if (subtype == 2) {
#if PY_MAJOR_VERSION >= 3
int other_size = _downcast_and_check(PyBytes_Size(value), 4);
#else
int other_size = _downcast_and_check(PyString_Size(value), 4);
#endif
if (other_size == -1)
return 0;
if (!buffer_write_int32(buffer, other_size)) {
return 0;
}
if (!buffer_write_bytes(buffer, &subtype, 1)) {
return 0;
}
}
if (!buffer_write_int32(buffer, size)) {
return 0;
}
if (subtype != 2) {
if (!buffer_write_bytes(buffer, &subtype, 1)) {
return 0;
}
}
#if PY_MAJOR_VERSION >= 3
data = PyBytes_AsString(value);
#else
data = PyString_AsString(value);
#endif
if (!data) {
return 0;
}
if (!buffer_write_bytes(buffer, data, size)) {
return 0;
}
return 1;
}
case 7:
{
/* ObjectId */
const char* data;
PyObject* pystring = PyObject_GetAttrString(value, "_ObjectId__id");
if (!pystring) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
data = PyBytes_AsString(pystring);
#else
data = PyString_AsString(pystring);
#endif
if (!data) {
Py_DECREF(pystring);
return 0;
}
if (!buffer_write_bytes(buffer, data, 12)) {
Py_DECREF(pystring);
return 0;
}
Py_DECREF(pystring);
*(buffer_get_buffer(buffer) + type_byte) = 0x07;
return 1;
}
case 11:
{
/* Regex */
return _write_regex_to_buffer(buffer, type_byte, value);
}
case 13:
{
/* Code */
int start_position,
length_location,
length;
PyObject* scope = PyObject_GetAttrString(value, "scope");
if (!scope) {
return 0;
}
if (scope == Py_None) {
Py_DECREF(scope);
*(buffer_get_buffer(buffer) + type_byte) = 0x0D;
return write_string(buffer, value);
}
*(buffer_get_buffer(buffer) + type_byte) = 0x0F;
start_position = buffer_get_position(buffer);
/* save space for length */
length_location = buffer_save_space(buffer, 4);
if (length_location == -1) {
PyErr_NoMemory();
Py_DECREF(scope);
return 0;
}
if (!write_string(buffer, value)) {
Py_DECREF(scope);
return 0;
}
if (!write_dict(self, buffer, scope, 0, options, 0)) {
Py_DECREF(scope);
return 0;
}
Py_DECREF(scope);
length = buffer_get_position(buffer) - start_position;
buffer_write_int32_at_position(
buffer, length_location, (int32_t)length);
return 1;
}
case 17:
{
/* Timestamp */
PyObject* obj;
unsigned long i;
obj = PyObject_GetAttrString(value, "inc");
if (!obj) {
return 0;
}
i = PyLong_AsUnsignedLong(obj);
Py_DECREF(obj);
if (i == (unsigned long)-1 && PyErr_Occurred()) {
return 0;
}
if (!buffer_write_int32(buffer, (int32_t)i)) {
return 0;
}
obj = PyObject_GetAttrString(value, "time");
if (!obj) {
return 0;
}
i = PyLong_AsUnsignedLong(obj);
Py_DECREF(obj);
if (i == (unsigned long)-1 && PyErr_Occurred()) {
return 0;
}
if (!buffer_write_int32(buffer, (int32_t)i)) {
return 0;
}
*(buffer_get_buffer(buffer) + type_byte) = 0x11;
return 1;
}
case 18:
{
/* Int64 */
const long long ll = PyLong_AsLongLong(value);
if (PyErr_Occurred()) { /* Overflow */
PyErr_SetString(PyExc_OverflowError,
"MongoDB can only handle up to 8-byte ints");
return 0;
}
if (!buffer_write_int64(buffer, (int64_t)ll)) {
return 0;
}
*(buffer_get_buffer(buffer) + type_byte) = 0x12;
return 1;
}
case 19:
{
/* Decimal128 */
const char* data;
PyObject* pystring = PyObject_GetAttrString(value, "bid");
if (!pystring) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
data = PyBytes_AsString(pystring);
#else
data = PyString_AsString(pystring);
#endif
if (!data) {
Py_DECREF(pystring);
return 0;
}
if (!buffer_write_bytes(buffer, data, 16)) {
Py_DECREF(pystring);
return 0;
}
Py_DECREF(pystring);
*(buffer_get_buffer(buffer) + type_byte) = 0x13;
return 1;
}
case 100:
{
/* DBRef */
PyObject* as_doc = PyObject_CallMethod(value, "as_doc", NULL);
if (!as_doc) {
return 0;
}
if (!write_dict(self, buffer, as_doc, 0, options, 0)) {
Py_DECREF(as_doc);
return 0;
}
Py_DECREF(as_doc);
*(buffer_get_buffer(buffer) + type_byte) = 0x03;
return 1;
}
case 101:
{
/* RawBSONDocument */
char* raw_bson_document_bytes;
Py_ssize_t raw_bson_document_bytes_len;
int raw_bson_document_bytes_len_int;
PyObject* raw_bson_document_bytes_obj = PyObject_GetAttrString(value, "raw");
if (!raw_bson_document_bytes_obj) {
return 0;
}
#if PY_MAJOR_VERSION >= 3
if (-1 == PyBytes_AsStringAndSize(raw_bson_document_bytes_obj,
&raw_bson_document_bytes,
&raw_bson_document_bytes_len)) {
#else
if (-1 == PyString_AsStringAndSize(raw_bson_document_bytes_obj,
&raw_bson_document_bytes,
&raw_bson_document_bytes_len)) {
#endif
Py_DECREF(raw_bson_document_bytes_obj);
return 0;
}
raw_bson_document_bytes_len_int = _downcast_and_check(
raw_bson_document_bytes_len, 0);
if (-1 == raw_bson_document_bytes_len_int) {
Py_DECREF(raw_bson_document_bytes_obj);
return 0;
}
if(!buffer_write_bytes(buffer, raw_bson_document_bytes,
raw_bson_document_bytes_len_int)) {
Py_DECREF(raw_bson_document_bytes_obj);
return 0;
}
*(buffer_get_buffer(buffer) + type_byte) = 0x03;
Py_DECREF(raw_bson_document_bytes_obj);
return 1;
}
case 255:
{
/* MinKey */
*(buffer_get_buffer(buffer) + type_byte) = 0xFF;
return 1;
}
case 127:
{
/* MaxKey */
*(buffer_get_buffer(buffer) + type_byte) = 0x7F;
return 1;
}
}