forked from mongodb/node-mongodb-native
/
bson.cc
1426 lines (1304 loc) · 56.8 KB
/
bson.cc
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
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <v8.h>
#include <node.h>
#include <node_events.h>
#include <node_buffer.h>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#include "bson.h"
#include "long.h"
#include "objectid.h"
#include "binary.h"
#include "code.h"
#include "dbref.h"
using namespace v8;
using namespace node;
// BSON DATA TYPES
const uint32_t BSON_DATA_NUMBER = 1;
const uint32_t BSON_DATA_STRING = 2;
const uint32_t BSON_DATA_OBJECT = 3;
const uint32_t BSON_DATA_ARRAY = 4;
const uint32_t BSON_DATA_BINARY = 5;
const uint32_t BSON_DATA_OID = 7;
const uint32_t BSON_DATA_BOOLEAN = 8;
const uint32_t BSON_DATA_DATE = 9;
const uint32_t BSON_DATA_NULL = 10;
const uint32_t BSON_DATA_REGEXP = 11;
const uint32_t BSON_DATA_CODE_W_SCOPE = 15;
const uint32_t BSON_DATA_INT = 16;
const uint32_t BSON_DATA_TIMESTAMP = 17;
const uint32_t BSON_DATA_LONG = 18;
const int32_t BSON_INT32_MAX = 2147483648;
const int32_t BSON_INT32_MIN = -2147483648;
// BSON BINARY DATA SUBTYPES
const uint32_t BSON_BINARY_SUBTYPE_FUNCTION = 1;
const uint32_t BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
const uint32_t BSON_BINARY_SUBTYPE_UUID = 3;
const uint32_t BSON_BINARY_SUBTYPE_MD5 = 4;
const uint32_t BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
static Handle<Value> VException(const char *msg) {
HandleScope scope;
return ThrowException(Exception::Error(String::New(msg)));
};
void BSON::Initialize(v8::Handle<v8::Object> target) {
// Grab the scope of the call from Node
HandleScope scope;
// Define a new function template
Local<FunctionTemplate> t = FunctionTemplate::New(New);
constructor_template = Persistent<FunctionTemplate>::New(t);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("BSON"));
// Class methods
NODE_SET_METHOD(constructor_template->GetFunction(), "serialize", BSONSerialize);
NODE_SET_METHOD(constructor_template->GetFunction(), "deserialize", BSONDeserialize);
NODE_SET_METHOD(constructor_template->GetFunction(), "encodeLong", EncodeLong);
NODE_SET_METHOD(constructor_template->GetFunction(), "toLong", ToLong);
NODE_SET_METHOD(constructor_template->GetFunction(), "toInt", ToInt);
target->Set(String::NewSymbol("BSON"), constructor_template->GetFunction());
}
// Create a new instance of BSON and assing it the existing context
Handle<Value> BSON::New(const Arguments &args) {
HandleScope scope;
BSON *bson = new BSON();
bson->Wrap(args.This());
return args.This();
}
Handle<Value> BSON::BSONSerialize(const Arguments &args) {
// printf("= BSONSerialize ===================================== USING Native BSON Parser\n");
if(args.Length() == 1 && !args[0]->IsObject()) return VException("One or two arguments required - [object] or [object, boolean]");
if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return VException("One or two arguments required - [object] or [object, boolean]");
if(args.Length() > 2) return VException("One or two arguments required - [object] or [object, boolean]");
// Calculate the total size of the document in binary form to ensure we only allocate memory once
uint32_t object_size = BSON::calculate_object_size(args[0]);
// Allocate the memory needed for the serializtion
char *serialized_object = (char *)malloc(object_size * sizeof(char));
// Catch any errors
try {
// Check if we have a boolean value
bool check_key = false;
if(args.Length() == 2 && args[1]->IsBoolean()) {
check_key = args[1]->BooleanValue();
}
// Serialize the object
BSON::serialize(serialized_object, 0, Null(), args[0], check_key);
} catch(char *err_msg) {
// Free up serialized object space
free(serialized_object);
// Throw exception with the string
Handle<Value> error = VException(err_msg);
// free error message
free(err_msg);
// Return error
return error;
}
// Encode the binary value
Local<Value> bin_value = Encode(serialized_object, object_size, BINARY);
// Return the serialized content
return bin_value;
}
Handle<Value> BSON::ToLong(const Arguments &args) {
HandleScope scope;
if(args.Length() != 2 && !args[0]->IsString() && !args[1]->IsString()) return VException("Two arguments of type String required");
// Create a new Long value and return it
Local<Value> argv[] = {args[0], args[1]};
Handle<Value> long_obj = Long::constructor_template->GetFunction()->NewInstance(2, argv);
return scope.Close(long_obj);
}
Handle<Value> BSON::ToInt(const Arguments &args) {
HandleScope scope;
if(args.Length() != 1 && !args[0]->IsNumber() && !args[1]->IsString()) return VException("One argument of type Number required");
// Return int value
return scope.Close(args[0]->ToInt32());
}
Handle<Value> BSON::EncodeLong(const Arguments &args) {
HandleScope scope;
// Encode the value
if(args.Length() != 1 && !Long::HasInstance(args[0])) return VException("One argument required of type Long");
// Unpack the object and encode
Local<Object> obj = args[0]->ToObject();
Long *long_obj = Long::Unwrap<Long>(obj);
// Allocate space
char *long_str = (char *)malloc(8 * sizeof(char));
// Write the content to the char array
BSON::write_int32((long_str), long_obj->low_bits);
BSON::write_int32((long_str + 4), long_obj->high_bits);
// Encode the data
Local<String> long_final_str = Encode(long_str, 8, BINARY)->ToString();
// Free up memory
free(long_str);
// Return the encoded string
return scope.Close(long_final_str);
}
void BSON::write_int32(char *data, uint32_t value) {
// Write the int to the char*
memcpy(data, &value, 4);
}
void BSON::write_double(char *data, double value) {
// Write the double to the char*
memcpy(data, &value, 8);
}
void BSON::write_int64(char *data, int64_t value) {
// Write the int to the char*
memcpy(data, &value, 8);
}
char *BSON::check_key(Local<String> key) {
// Allocate space for they key string
char *key_str = (char *)malloc(key->Length() * sizeof(char) + 1);
// Error string
char *error_str = (char *)malloc(256 * sizeof(char));
// Decode the key
ssize_t len = DecodeBytes(key, BINARY);
ssize_t written = DecodeWrite(key_str, len, key, BINARY);
*(key_str + key->Length()) = '\0';
// Check if we have a valid key
if(key->Length() > 0 && *(key_str) == '$') {
// Create the string
sprintf(error_str, "key %s must not start with '$'", key_str);
// Free up memory
free(key_str);
// Throw exception with string
throw error_str;
} else if(key->Length() > 0 && strchr(key_str, '.') != NULL) {
// Create the string
sprintf(error_str, "key %s must not contain '.'", key_str);
// Free up memory
free(key_str);
// Throw exception with string
throw error_str;
}
return NULL;
}
uint32_t BSON::serialize(char *serialized_object, uint32_t index, Handle<Value> name, Handle<Value> value, bool check_key) {
// printf("============================================= serialized::::\n");
// If we have a name check that key is valid
if(!name->IsNull() && check_key) {
if(BSON::check_key(name->ToString()) != NULL) return -1;
}
// If we have an object let's serialize it
if(Long::HasInstance(value)) {
// printf("============================================= -- serialized::::long\n");
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_LONG;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
// Unpack the object and encode
Local<Object> obj = value->ToObject();
Long *long_obj = Long::Unwrap<Long>(obj);
// Write the content to the char array
BSON::write_int32((serialized_object + index), long_obj->low_bits);
BSON::write_int32((serialized_object + index + 4), long_obj->high_bits);
// Adjust the index
index = index + 8;
} else if(ObjectID::HasInstance(value) || (value->IsObject() && value->ToObject()->HasRealNamedProperty(String::New("toHexString")))) {
// printf("============================================= -- serialized::::object_id\n");
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_OID;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
// Unpack the object and encode
Local<Object> obj = value->ToObject();
ObjectID *object_id_obj = ObjectID::Unwrap<ObjectID>(obj);
// Fetch the converted oid
char *binary_oid = object_id_obj->convert_hex_oid_to_bin();
// Write the oid to the char array
memcpy((serialized_object + index), binary_oid, 12);
// Adjust the index
index = index + 12;
} else if(Binary::HasInstance(value)) {
// printf("============================================= -- serialized::::binary\n");
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_BINARY;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
// Unpack the object and encode
Local<Object> obj = value->ToObject();
Binary *binary_obj = Binary::Unwrap<Binary>(obj);
// Let's write the total size of the binary
BSON::write_int32((serialized_object + index), (binary_obj->index + 4));
// Adjust index
index = index + 4;
// Write subtype
*(serialized_object + index) = (char)binary_obj->sub_type;
// Adjust index
index = index + 1;
// Let's write the content to the char* array
BSON::write_int32((serialized_object + index), binary_obj->index);
// Adjust index
index = index + 4;
// Write binary content
memcpy((serialized_object + index), binary_obj->data, binary_obj->index);
// Adjust index
index = index + binary_obj->index;
} else if(DBRef::HasInstance(value)) {
// printf("============================================= -- serialized::::dbref\n");
// Unpack the dbref
Local<Object> dbref = value->ToObject();
// Create an object containing the right namespace variables
Local<Object> obj = Object::New();
// unpack dbref to get to the bin
DBRef *db_ref_obj = DBRef::Unwrap<DBRef>(dbref);
char *oid_bin = db_ref_obj->oid->convert_hex_oid_to_bin();
// Return the value
Local<Value> argv[] = {String::New(db_ref_obj->oid->oid)};
Handle<Value> object_id_obj = ObjectID::constructor_template->GetFunction()->NewInstance(1, argv);
// Encode the oid to bin
obj->Set(String::New("$ref"), dbref->Get(String::New("namespace")));
obj->Set(String::New("$id"), object_id_obj);
obj->Set(String::New("$db"), dbref->Get(String::New("db")));
// Encode the variable
index = BSON::serialize(serialized_object, index, name, obj, check_key);
} else if(Code::HasInstance(value)) {
// printf("============================================= -- serialized::::code\n");
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_CODE_W_SCOPE;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
// Unpack the object and encode
Local<Object> obj = value->ToObject();
Code *code_obj = Code::Unwrap<Code>(obj);
// Keep pointer to start
uint32_t first_pointer = index;
// Adjust the index
index = index + 4;
// Write the size of the code string
BSON::write_int32((serialized_object + index), strlen(code_obj->code) + 1);
// Adjust the index
index = index + 4;
// Write the code string
memcpy((serialized_object + index), code_obj->code, strlen(code_obj->code));
*(serialized_object + index + strlen(code_obj->code)) = '\0';
// Adjust index
index = index + strlen(code_obj->code) + 1;
// Encode the scope
uint32_t scope_object_size = BSON::calculate_object_size(code_obj->scope_object);
// Serialize the scope object
BSON::serialize((serialized_object + index), 0, Null(), code_obj->scope_object, check_key);
// Adjust the index
index = index + scope_object_size;
// Encode the total size of the object
BSON::write_int32((serialized_object + first_pointer), (index - first_pointer));
} else if(value->IsString()) {
// printf("============================================= -- serialized::::string\n");
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_STRING;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
// Write the actual string into the char array
Local<String> str = value->ToString();
// Let's fetch the int value
uint32_t string_length = str->Length() + 1;
// Write the integer to the char *
BSON::write_int32((serialized_object + index), string_length);
// Adjust the index
index = index + 4;
// Write the string to the file
len = DecodeBytes(str, BINARY);
written = DecodeWrite((serialized_object + index), len, str, BINARY);
// Add the null termination
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
} else if(value->IsInt32()) {
// printf("============================================= -- serialized::::int32\n");
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_INT;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
// Write the integer to the char *
int32_t int_value = value->Int32Value();
BSON::write_int32((serialized_object + index), int_value);
// Adjust the index
index = index + 4;
} else if(value->IsNull()) {
// printf("============================================= -- serialized::::null\n");
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_NULL;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
} else if(value->IsNumber()) {
// printf("============================================= -- serialized::::number\n");
uint32_t first_pointer = index;
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_INT;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
Local<Number> number = value->ToNumber();
// Get the values
double d_number = number->NumberValue();
int64_t l_number = number->IntegerValue();
// Check if we have a double value and not a int64
double d_result = d_number - l_number;
// If we have a value after subtracting the integer value we have a float
if(d_result > 0 || d_result < 0) {
// printf("============================================= -- serialized::::double\n");
// Write the double to the char array
BSON::write_double((serialized_object + index), d_number);
// Adjust type to be double
*(serialized_object + first_pointer) = BSON_DATA_NUMBER;
// Adjust index for double
index = index + 8;
} else if(l_number <= BSON_INT32_MAX || l_number >= BSON_INT32_MIN) {
if(l_number == BSON_INT32_MAX) {
BSON::write_int32((serialized_object + index), BSON_INT32_MAX);
} else {
BSON::write_int32((serialized_object + index), BSON_INT32_MIN);
}
// Adjust the size of the index
index = index + 4;
} else {
// object_size = object_size + 8;
}
} else if(value->IsBoolean()) {
// printf("============================================= -- serialized::::boolean\n");
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_BOOLEAN;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
// Save the boolean value
*(serialized_object + index) = value->BooleanValue() ? '\1' : '\0';
// Adjust the index
index = index + 1;
} else if(value->IsDate()) {
// printf("============================================= -- serialized::::date\n");
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_DATE;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
// Fetch the Integer value
int64_t integer_value = value->IntegerValue();
BSON::write_int64((serialized_object + index), integer_value);
// Adjust the index
index = index + 8;
} else if(value->IsObject() && value->ToObject()->ObjectProtoToString()->Equals(String::New("[object RegExp]"))) {
// printf("============================================= -- serialized::::regexp\n");
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_REGEXP;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
// Additional size
uint32_t regexp_size = 0;
// Fetch the string for the regexp
Local<String> str = value->ToString();
len = DecodeBytes(str, BINARY);
// Let's define the buffer that contains the regexp string
char *data = new char[len + 1];
*(data + len) = '\0';
// Write the data to the buffer from the string object
written = DecodeWrite(data, len, str, BINARY);
// Locate the last pointer of the string
char *options_ptr = strrchr(data, '/');
// String size
uint32_t regexp_string_size = (options_ptr - data) - 1;
// printf("------------------------------------ [%s]%d:%d\n", data, (options_ptr - data), regexp_string_size);
// Copy the string to the char stream
memcpy((serialized_object + index), (data + 1), regexp_string_size);
*(serialized_object + index + regexp_string_size + 1) = '\0';
// Ajust the index
index = index + regexp_string_size + 1;
// If it's not a null we have options
if(options_ptr != NULL && (options_ptr - data) > 0) {
uint32_t offset = (options_ptr - data);
// Validate that we have valid options
for(int i = 1; i < (len - offset); i++) {
if(*(options_ptr + i) == 'i' || *(options_ptr + i) == 'm' || *(options_ptr + i) == 'x') {
*(serialized_object + index) = *(options_ptr + i);
index = index + 1;
}
}
}
// Add termiating null
*(serialized_object + index) = '\0';
// Adjust pointer
index = index + 1;
} else if(value->IsArray()) {
// printf("============================================= -- serialized::::array\n");
// Cast to array
Local<Array> array = Local<Array>::Cast(value->ToObject());
// Turn length into string to calculate the size of all the strings needed
char *length_str = (char *)malloc(256 * sizeof(char));
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_ARRAY;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
// Object size
uint32_t object_size = BSON::calculate_object_size(value);
// printf("C++ =================================== array_size: %d\n", object_size);
// Write the size of the object
BSON::write_int32((serialized_object + index), object_size);
// Adjust the index
index = index + 4;
// Write out all the elements
for(uint32_t i = 0; i < array->Length(); i++) {
// Add "index" string size for each element
sprintf(length_str, "%d", i);
// Encode the values
index = BSON::serialize(serialized_object, index, String::New(length_str), array->Get(Integer::New(i)), check_key);
// Write trailing '\0' for object
*(serialized_object + index) = '\0';
}
// Write trailing '\0' for object
*(serialized_object + index + 1) = '\0';
// Free up memory
free(length_str);
} else if(value->IsObject()) {
// printf("============================================= -- serialized::::object\n");
if(!name->IsNull()) {
// Save the string at the offset provided
*(serialized_object + index) = BSON_DATA_OBJECT;
// Adjust writing position for the first byte
index = index + 1;
// Convert name to char*
ssize_t len = DecodeBytes(name, BINARY);
ssize_t written = DecodeWrite((serialized_object + index), len, name, BINARY);
// Add null termiation for the string
*(serialized_object + index + len) = '\0';
// Adjust the index
index = index + len + 1;
}
// Unwrap the object
Local<Object> object = value->ToObject();
Local<Array> property_names = object->GetPropertyNames();
// Calculate size of the total object
uint32_t object_size = BSON::calculate_object_size(value);
// printf("------------------------------------------------------ property_names.length: %d\n", property_names->Length());
// printf("------------------------------------------------------ calculated_object: %d\n", object_size);
// Write the size
BSON::write_int32((serialized_object + index), object_size);
// Adjust size
index = index + 4;
// Process all the properties on the object
for(uint32_t i = 0; i < property_names->Length(); i++) {
// Fetch the property name
Local<String> property_name = property_names->Get(i)->ToString();
// Convert name to char*
ssize_t len = DecodeBytes(property_name, BINARY);
char *data = new char[len];
// *(data + len) = '\0';
ssize_t written = DecodeWrite(data, len, property_name, BINARY);
// printf("=========================== property_name:: %s\n", data);
// Fetch the object for the property
Local<Value> property = object->Get(property_name);
// Write the next serialized object
index = BSON::serialize(serialized_object, index, property_name, property, check_key);
}
// Pad the last item
*(serialized_object + index) = '\0';
index = index + 1;
// Null out reminding fields if we have a toplevel object and nested levels
if(name->IsNull()) {
for(uint32_t i = 0; i < (object_size - index); i++) {
*(serialized_object + index + i) = '\0';
}
}
}
return index;
}
uint32_t BSON::calculate_object_size(Handle<Value> value) {
uint32_t object_size = 0;
// printf("================================ ----------- calculate_object_size\n");
// If we have an object let's unwrap it and calculate the sub sections
if(Long::HasInstance(value)) {
// printf("================================ calculate_object_size:long\n");
object_size = object_size + 8;
} else if(ObjectID::HasInstance(value)) {
// printf("================================ calculate_object_size:objectid\n");
object_size = object_size + 12;
} else if(Binary::HasInstance(value)) {
// printf("================================ calculate_object_size:binary\n");
// Unpack the object and encode
Local<Object> obj = value->ToObject();
Binary *binary_obj = Binary::Unwrap<Binary>(obj);
// Adjust the object_size, binary content lengt + total size int32 + binary size int32 + subtype
object_size += binary_obj->index + 4 + 4 + 1;
} else if(Code::HasInstance(value)) {
// printf("================================ calculate_object_size:code\n");
// Unpack the object and encode
Local<Object> obj = value->ToObject();
Code *code_obj = Code::Unwrap<Code>(obj);
// Let's calculate the size the code object adds adds
object_size += strlen(code_obj->code) + 4 + BSON::calculate_object_size(code_obj->scope_object) + 4 + 1;
} else if(DBRef::HasInstance(value)) {
// Unpack the dbref
Local<Object> dbref = value->ToObject();
// Create an object containing the right namespace variables
Local<Object> obj = Object::New();
// unpack dbref to get to the bin
DBRef *db_ref_obj = DBRef::Unwrap<DBRef>(dbref);
// Return the value
Local<Value> argv[] = {String::New(db_ref_obj->oid->oid)};
Handle<Value> object_id_obj = ObjectID::constructor_template->GetFunction()->NewInstance(1, argv);
// Encode the oid to bin
obj->Set(String::New("$ref"), dbref->Get(String::New("namespace")));
obj->Set(String::New("$id"), object_id_obj);
obj->Set(String::New("$db"), dbref->Get(String::New("db")));
// Calculate size
object_size += BSON::calculate_object_size(obj);
} else if(value->IsString()) {
// printf("================================ calculate_object_size:string\n");
Local<String> str = value->ToString();
// Let's calculate the size the string adds, length + type(1 byte) + size(4 bytes)
object_size += str->Length() + 1 + 4;
} else if(value->IsInt32()) {
// printf("================================ calculate_object_size:int32\n");
object_size += 4;
} else if(value->IsNull()) {
// printf("================================ calculate_object_size:null\n");
} else if(value->IsNumber()) {
// Check if we have a float value or a long value
Local<Number> number = value->ToNumber();
double d_number = number->NumberValue();
int64_t l_number = number->IntegerValue();
// Check if we have a double value and not a int64
double d_result = d_number - l_number;
// If we have a value after subtracting the integer value we have a float
if(d_result > 0 || d_result < 0) {
// printf("================================ calculate_object_size:double\n");
object_size = object_size + 8;
} else if(d_number <= 2147483648 || d_number >= -2147483648) {
object_size = object_size + 4;
} else {
object_size = object_size + 8;
}
} else if(value->IsBoolean()) {
// printf("================================ calculate_object_size:boolean\n");
object_size = object_size + 1;
} else if(value->IsDate()) {
// printf("================================ calculate_object_size:date\n");
object_size = object_size + 8;
} else if(value->IsObject() && value->ToObject()->ObjectProtoToString()->Equals(String::New("[object RegExp]"))) {
// printf("================================ calculate_object_size:regexp\n");
// Additional size
uint32_t regexp_size = 0;
// Fetch the string for the regexp
Local<String> str = value->ToString();
ssize_t len = DecodeBytes(str, BINARY);
// Let's define the buffer that contains the regexp string
char *data = new char[len + 1];
*(data + len) = '\0';
// Write the data to the buffer from the string object
ssize_t written = DecodeWrite(data, len, str, BINARY);
// Split up the regexp into pieces
char *options_ptr = strrchr(data, '/');
if(options_ptr != NULL && (options_ptr - data) > 0) {
// printf("====================== regexp_string: %d:%s:%c:%lli\n", len, data, *(options_ptr), (options_ptr - data));
// /abcd/mi
uint32_t offset = (options_ptr - data);
// Validate that we have valid options
for(int i = 1; i < (len - offset); i++) {
if(*(options_ptr + i) == 'i' || *(options_ptr + i) == 'm' || *(options_ptr + i) == 'x') regexp_size = regexp_size + 1;
}
}
// Calculate the space needed for the regexp: size of string - 2 for the /'ses +2 for null termiations
object_size = object_size + ((options_ptr - data) - 1) + 2 + regexp_size;
} else if(value->IsArray()) {
// printf("================================ calculate_object_size:array\n");
// Cast to array
Local<Array> array = Local<Array>::Cast(value->ToObject());
// Turn length into string to calculate the size of all the strings needed
char *length_str = (char *)malloc(256 * sizeof(char));
// Calculate the size of each element
for(uint32_t i = 0; i < array->Length(); i++) {
// Add "index" string size for each element
sprintf(length_str, "%d", i);
// Add the size of the string length
uint32_t label_length = strlen(length_str) + 1;
// Add the type definition size for each item
object_size = object_size + label_length + 1;
// Add size of the object
uint32_t object_length = BSON::calculate_object_size(array->Get(Integer::New(i)));
object_size = object_size + object_length;
}
// Add the object size
object_size += 1 + 4;
// Free up memory
free(length_str);
} else if(value->IsObject()) {
// printf("================================ calculate_object_size:object\n");
// Unwrap the object
Local<Object> object = value->ToObject();
Local<Array> property_names = object->GetPropertyNames();
// Process all the properties on the object
for(uint32_t index = 0; index < property_names->Length(); index++) {
// Fetch the property name
Local<String> property_name = property_names->Get(index)->ToString();
// Fetch the object for the property
Local<Value> property = object->Get(property_name);
// Get size of property (property + property name length + 1 for terminating 0)
object_size += BSON::calculate_object_size(property) + property_name->Length() + 1 + 1;
}
object_size = object_size + 4 + 1;
}
return object_size;
}
Handle<Value> BSON::BSONDeserialize(const Arguments &args) {
HandleScope scope;
// printf("= BSONDeserialize ===================================== USING Native BSON Parser\n");
// Ensure that we have an parameter
if(Buffer::HasInstance(args[0]) && args.Length() > 1) return VException("One argument required - buffer1.");
if(args[0]->IsString() && args.Length() > 1) return VException("One argument required - string1.");
// Throw an exception if the argument is not of type Buffer
if(!Buffer::HasInstance(args[0]) && !args[0]->IsString()) return VException("Argument must be a Buffer or String.");
// Define pointer to data
char *data;
uint32_t length;
// If we passed in a buffer, let's unpack it, otherwise let's unpack the string
if(Buffer::HasInstance(args[0])) {
Buffer *buffer = ObjectWrap::Unwrap<Buffer>(args[0]->ToObject());
data = buffer->data();
uint32_t length = buffer->length();
} else {
// Let's fetch the encoding
// enum encoding enc = ParseEncoding(args[1]);
// The length of the data for this encoding
ssize_t len = DecodeBytes(args[0], BINARY);
// Let's define the buffer size
data = new char[len];
// Write the data to the buffer from the string object
ssize_t written = DecodeWrite(data, len, args[0], BINARY);
// Assert that we wrote the same number of bytes as we have length
assert(written == len);
}
// Deserialize the content
return BSON::deserialize(data, NULL);
}
// Deserialize the stream
Handle<Value> BSON::deserialize(char *data, bool is_array_item) {
// printf("----------------------------------------------------------------- deserialize\n");
HandleScope scope;
// Holds references to the objects that are going to be returned
Local<Object> return_data = Object::New();
Local<Array> return_array = Array::New();
// The current index in the char data
uint32_t index = 0;
// Decode the size of the BSON data structure
uint32_t size = BSON::deserialize_int32(data, index);
// printf("C:: ============================ BSON:SIZE:%d\n", size);
// Adjust the index to point to next piece
index = index + 4;
// for(int n = 0; n < size; n++) {
// printf("C:: ============ %02x\n",(unsigned char)data[n]);
// }
//
// for(int n = 0; s_value[n] != '\0'; n++) {
// printf("C:: ============ %02x\n",(unsigned char)s_value[n]);
// }
// While we have data left let's decode
while(index < size) {
// printf("C:: ==================================== current index: %d\n", index);
// Read the first to bytes to indicate the type of object we are decoding
uint16_t type = BSON::deserialize_int8(data, index);
// printf(" C:: ============================ BSON:TYPE:%d\n", type);
// Handles the internal size of the object
uint32_t insert_index = 0;
// Adjust index to skip type byte
index = index + 1;
if(type == BSON_DATA_STRING) {
// Read the null terminated index String
char *string_name = BSON::extract_string(data, index);
if(string_name == NULL) return VException("Invalid C String found.");
// Let's create a new string
index = index + strlen(string_name) + 1;
// Handle array value if applicable
uint32_t insert_index = 0;
if(is_array_item) {
insert_index = atoi(string_name);
}
// Read the length of the string (next 4 bytes)
uint32_t string_size = BSON::deserialize_int32(data, index);
// Adjust index to point to start of string
index = index + 4;
// Decode the string and add zero terminating value at the end of the string
char *value = (char *)malloc((string_size * sizeof(char)) + 1);
strncpy(value, (data + index), string_size);
*(value + string_size) = '\0';
// Adjust the index for the size of the string
index = index + string_size;
// Add the value to the data
if(is_array_item) {
return_array->Set(Number::New(insert_index), String::New(value));
} else {
return_data->Set(String::New(string_name), String::New(value));
}
// Free up the memory
free(value);
} else if(type == BSON_DATA_INT) {
// printf("===================================== decoding int\n");
// Read the null terminated index String
char *string_name = BSON::extract_string(data, index);
if(string_name == NULL) return VException("Invalid C String found.");
// printf("================== label: %s\n", string_name);
// Let's create a new string
index = index + strlen(string_name) + 1;
// Handle array value if applicable
uint32_t insert_index = 0;
if(is_array_item) {
insert_index = atoi(string_name);
}
// Decode the integer value
uint32_t value = 0;
memcpy(&value, (data + index), 4);
// Adjust the index for the size of the value
index = index + 4;
// Add the element to the object
if(is_array_item) {
// printf("=================== wow\n");
return_array->Set(Integer::New(insert_index), Integer::New(value));
} else {
return_data->Set(String::New(string_name), Integer::New(value));
}
} else if(type == BSON_DATA_LONG) {
// Read the null terminated index String
char *string_name = BSON::extract_string(data, index);
if(string_name == NULL) return VException("Invalid C String found.");
// Let's create a new string
index = index + strlen(string_name) + 1;
// Handle array value if applicable
uint32_t insert_index = 0;
if(is_array_item) {
insert_index = atoi(string_name);
}
// Decode the integer value
int64_t value = 0;
memcpy(&value, (data + index), 8);
// Adjust the index for the size of the value
index = index + 8;
// Add the element to the object
if(is_array_item) {
return_array->Set(Number::New(insert_index), BSON::decodeLong(value));
} else {
return_data->Set(String::New(string_name), BSON::decodeLong(value));
}
} else if(type == BSON_DATA_NUMBER) {
// printf("===================================== decoding float/double\n");
// Read the null terminated index String
char *string_name = BSON::extract_string(data, index);
if(string_name == NULL) return VException("Invalid C String found.");
// Let's create a new string
index = index + strlen(string_name) + 1;
// Handle array value if applicable
uint32_t insert_index = 0;
if(is_array_item) {
insert_index = atoi(string_name);
}
// Decode the integer value
double value = 0;
memcpy(&value, (data + index), 8);
// Adjust the index for the size of the value
index = index + 8;
// Add the element to the object
if(is_array_item) {
return_array->Set(Number::New(insert_index), Number::New(value));
} else {
return_data->Set(String::New(string_name), Number::New(value));
}
} else if(type == BSON_DATA_NULL) {
// printf("===================================== decoding float/double\n");
// Read the null terminated index String
char *string_name = BSON::extract_string(data, index);
if(string_name == NULL) return VException("Invalid C String found.");
// Let's create a new string
index = index + strlen(string_name) + 1;
// Handle array value if applicable
uint32_t insert_index = 0;
if(is_array_item) {
insert_index = atoi(string_name);
}
// Add the element to the object
if(is_array_item) {
return_array->Set(Number::New(insert_index), Null());
} else {
return_data->Set(String::New(string_name), Null());
}
} else if(type == BSON_DATA_BOOLEAN) {
// Read the null terminated index String
char *string_name = BSON::extract_string(data, index);
if(string_name == NULL) return VException("Invalid C String found.");
// Let's create a new string
index = index + strlen(string_name) + 1;
// Handle array value if applicable
uint32_t insert_index = 0;
if(is_array_item) {
insert_index = atoi(string_name);
}
// Decode the boolean value
char bool_value = *(data + index);
// Adjust the index for the size of the value
index = index + 1;
// Add the element to the object
if(is_array_item) {
return_array->Set(Number::New(insert_index), bool_value == 1 ? Boolean::New(true) : Boolean::New(false));
} else {
return_data->Set(String::New(string_name), bool_value == 1 ? Boolean::New(true) : Boolean::New(false));
}
} else if(type == BSON_DATA_DATE) {
// Read the null terminated index String
char *string_name = BSON::extract_string(data, index);