forked from grijjy/GrijjyFoundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Grijjy.Bson.Serialization.pas
4908 lines (4260 loc) · 159 KB
/
Grijjy.Bson.Serialization.pas
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
unit Grijjy.Bson.Serialization;
(*< Serializing Delphi records and objects to JSON and BSON format (or to
TgoBsonDocument values).
@bold(Quick Start)
<source>
type
TOrderDetail = record
public
Product: String;
Quantity: Integer;
end;
TOrder = record
public
Customer: String;
OrderDetails: TArray<<TOrderDetail>;
end;
procedure TestSerialization;
var
Order, Rehydrated: TOrder;
Json: String;
begin
Order.Customer := 'John';
SetLength(Order.OrderDetails, 2);
Order.OrderDetails[0].Product := 'Pen';
Order.OrderDetails[0].Quantity := 1;
Order.OrderDetails[1].Product := 'Ruler';
Order.OrderDetails[1].Quantity := 2;
{ Serialize Order record to JSON: }
TgoBsonSerializer.Serialize(Order, Json);
WriteLn(Json); // Outputs:
// { "Customer" : "John",
// "OrderDetails" : [
// { "Product" : "Pen", "Quantity" : 1 },
// { "Product" : "Ruler", "Quantity" : 2 }
// ]
// }
{ Deserialize JSON to Order record: }
TgoBsonSerializer.Deserialize(Json, Rehydrated);
{ Rehydrated will have the same values as Order }
end;
</source>
@bold(Features)
The serialization engine supports the following features:
* You can serialize records and classes to JSON, BSON and TgoBsonDocument.
* You can also serialize dynamic arrays to JSON (but not to BSON and
TgoBsonDocument).
* By default, all public fields and public and published read/write properties
are serialized. Private and protected fields and properties are never
serialized.
* Fields can be of type boolean, integer (all sizes and flavors), floating-point
(Single and Double), WideChar, UnicodeString, TDateTime, TGUID,
TgoObjectId and TBytes (for binary data).
* Fields can also be of an enumerated type, as long as that type does not
have any explicitly declared values (since Delphi provides no RTTI for those).
* Likewise, a set of an enumerated type is also supported.
* Furthermore, a field can also be of a serializable record or class type, or a
dynamic array of a serializable type.
* You can customize some behavior and output using attributes.
@bold(Representations)
By default, the serialization engine serializes fields and properties
(collecively called "members" from here onward) as their native types. That is,
integers are serialized as integers and strings are serialized as strings.
However, you can use the <tt>BsonRepresentation</tt> attribute to change the way
a member is serialized to JSON:
<source>
type
TColor = (Red, Green, Blue);
type
TOrderDetail = record
public
Color: TColor;
[BsonRepresentation(TgoBsonRepresentation.String)]
ColorAsString: TColor;
end;
</source>
This serializes the Color member as a integer (which is the default
serialization type for enums), but serializes the ColorAsString member as a
string (using the name of the enum, eg "Red", "Green" or "Blue"). Not all types
can be serialized as other types. Below is a list of the types that can be
serialized as another type, and the conversion that will take place.
Boolean, can be serialized as:
* Boolean (default)
* Int32, Int64, Double (False=0, True=1)
* String (False="false", True="true")
Integer types:
* Int32, Int64 (default)
* Double
* String (IntToStr-conversion)
Enumerated types:
* Int32 (default, ordinal value)
* Int64 (ordinal value)
* String (name of the enum value)
Set types:
* Int32, Int64 (default, stored as a bitmask)
* String (comma-separated list of elements, without any (square) brackets)
Floating point types:
* Double (default)
* Int32, Int64 (truncated version)
* String (FloatToStr-conversion, in US format)
TDateTime:
* DateTime (default)
* Int64 (number of UTC ticks since midnight 1/1/0001, using 10,000 ticks per
millisecond)
* String (DateToISO8601-conversion)
* Document (a document with two elements: TimeStamp serialized as a DateTime
value, and Ticks serialized as the number of ticks since midnight 1/1/0001).
For example:
<tt>{ "DateTime" : ISODate("2016-05-01T15:28:57.784Z"),
"Ticks" : NumberLong("635977133377840000") }</tt>
String:
* String (default)
* Symbol
* ObjectId (if the string is a valid TgoObjectId)
WideChar:
* Int32 (default, ordinal value)
* Int64 (ordinal value)
* String (single-character string)
TGUID:
* Binary (default)
* String (without curly braces)
TgoObjectId:
* TgoObjectId (default)
* String (string value of ObjectId)
TBytes:
* Binary (default)
* String (hex string, using 2 hex digits per byte)
Note that for array members, the BsonRepresentation attribute applies to the
element types, not to the array itself:
<source>
type
TColor = (Red, Green, Blue);
type
TMyColors = record
public
[BsonRepresentation(TgoBsonRepresentation.String)]
Colors: TArray<<TColor>;
end;
</source>
This will serialize each color as a string (not the entire array as a string).
@bold(Handling Extra Elements)
When a JSON/BSON stream is deserialized, the name of each element is used to look
up a matching member in the record or class. Normally, if no matching member is
found, the element is ignored. This also means that when the record or class is
rendered back to JSON/BSON, those extra exlements will not exist and may be lost
forever.
You can also treat extra members in the JSON/BSON stream as an error condition.
In that case, an exception will be raised when extra elements are found. To
enable this error, use the <tt>BsonErrorOnExtraElements</tt> attribute at the
record or class level:
<source>
[BsonErrorOnExtraElements]
TOrderDetail = record
public
...
end;
</source>
@bold(Member Customization)
Normally, read-only properties are not serialized (unless the property is of a
class type, and the object property has already been created). If you want to
serialize read-only properties, you can mark them with a <tt>BsonElement</tt>
attribute:
<source>
TOrder = class
public
[BsonElement]
property TotalAmount: Double read GetTotalAmount;
end;
</source>
Of course, read-only properties are never deserialized.
Also, you may wish to serialize a member using a different name than the member
name. A common use for this is if you want to serialize using a C-style name
(lower case with underscores) but you would like the member to have a Pascal-style
name (with camel caps). Another situation where you may want to use this is if
the serialization name includes a character that is invalid in a Delphi
identifier. You can use the <tt>BsonElement</tt> attribute to provide the
serialization name:
<source>
TOrder = record
public
[BsonElement('customer_name')]
CustomerName: String;
[BsonElement('$id')]
Id: TgoObjectId;
end;
</source>
You may also choose to ignore a public member when serializing using the
<tt>BsonIgnore</tt> attribute:
<source>
TOrder = record
public
CustomerName: String;
[BsonIgnore]
CustomerAge: Integer;
end;
</source>
This will only serialize the CustomerName member. This would be the same as
making the CustomerAge field private or protected, with the difference that the
CustomAge field is still accessible in code outside of the TOrder class.
You can also ignore a field only when it has a default value, using the
<tt>BsonIgnoreIfDefault</tt> attribute:
<source>
TOrder = record
public
[BsonIgnoreIfDefault]
CustomerName: String;
end;
</source>
This will only serialize the customer name if it is not an empty string. For
other types the default value will be 0, False, [] etc. For Boolean, integral
and String types, you can specify the default value using the
<tt>BsonDefaultValue</tt> attribute:
<source>
TOrder = record
public
[BsonIgnoreIfDefault]
[BsonDefaultValue('John Smith')]
CustomerName: String;
end;
</source>
This will only serialize the customer name if it isn't 'John Smith'.
@bold(Note): an exception will be raised if you apply the
<tt>BsonDefaultValue</tt> attribute to a member that is not of a Boolean,
integral or String type.
@bold(Note): the <tt>BsonIgnoreIfDefault</tt> attribute can be used on all types
except record types.
@bold(Using Records)
The easiest way to serialize to/from JSON/BSON is by declaring record types as
shown above.
When a record is deserialized, all its values will be cleared first. This
assures that no values will be left uninitialized if certain members are not
deserialized.
If you want to customize the initialization behavior, then you can add a method
called <tt>Initialize</tt> without parameters. If such a method exists, then it
is called instead of clearing all fields:
<source>
TOrder = record
public
// This method gets called before deserializing a TOrder
procedure Initialize;
end;
</source>
@bold(Using Classes)
Serialization is easiest and most efficient when used with record types. You can
also serialize objects (class instances), but need to be aware of a different
behavior.
When you deserialize the object, and the object you pass has a value of nil,
then a new instance will be created. You are responsible for releasing the
instance at some later point:
<source>
type
TOrder = class
public
Customer: String;
end;
procedure TestDeserialization;
var
Order: TOrder;
begin
Order := nil;
TgoBsonSerializer.Deserialize('{ "Customer" : "John" }', Order);
end;
</source>
This will create a new TOrder instance and return it in the Order parameter.
The TOrder instance is created by calling a parameterless constructor. If the
TOrder class has constructor without parameters, then that constructor will be
called. Otherwise, a parameterless constructor of the ancestor class will be
used. If the ancestor class also doesn't have a parameterless constructor, then
we keep going up one ancestor in the chain, until TObject is reached, which
always has a parameterless constructor.
If you pass a non-nil value to Deserialize, then the existing object will be
updated and no new instance will be created.
When deserializing a field or property of a class type, the behavior depends on
whether the member is already assigned.
@bold(Deserializing Assigned object-properties)
Usually, it is best to make sure that the member is always assigned, by creating
it in the constructor and destroying it in the destructor:
<source>
type
TOrderDetail = class
...
end;
TOrder = class
private
FCustomer: String;
FDetail: TOrderDetail;
public
constructor Create;
destructor Destroy; override;
property Customer: String read FCustomer write FCustomer;
property Detail: TOrderDetail read FDetail; // Read-only
end;
constructor TOrder.Create;
begin
inherited;
FDetail := TOrderDetail.Create;
end;
destructor TOrder.Destroy;
begin
FDetail.Free;
inherited;
end;
</source>
This is a very common design pattern when using composition. Properties that are
of a class type (like Detail in this example) are usually read-only.
When deserializing the TOrder.Detail property in this example, its members are
deserialized as usual. Even though the Detail property is read-only, it will
still be deserialized (other read-only properties are usually ignored).
@bold(Deserializing Non-Assigned object-properties)
If the member is not assigned, it is only created and assigned if it is a
read/write property (or field):
<source>
type
TOrderDetail = class
...
end;
TOrder = class
private
FCustomer: String;
FDetail: TOrderDetail;
public
property Customer: String read FCustomer write FCustomer;
property Detail: TOrderDetail read FDetail write FDetail; // Read/write
end;
</source>
In this case, when deserializing the Detail property, it will be created (using
a parameterless constructor) and assigned to Detail. You need to make sure
though that the Detail property will be destroyed at some point. You could make
the Order class the owner and have it destroy the property in the destructor.
This design pattern is less common and not recommended. The recommended approach
is to always make sure the Detail property is assigned (and read-only), as
mentioned previously.
@bold(Polymorphism)
A complication that arises when serializing classes (instead of records) it that
they may be part of a class hierarchy:
<source>
type
TAnimal = class
public
Weight: Double;
end;
TDog = class(TAnimal)
public
FurColor: String;
end;
</source>
All animals have a weight, but only dogs have fur. When serializing a TDog, the
output is as expected:
<source>
var
Dog: TDog;
Json: String;
begin
Dog.Weight := 30;
Dog.FurColor := 'Blond';
TgoBsonSerializer.Serialize(Dog, Json); // Result:
// { "Weight" : 30.0, "FurColor" : "Blond" }
end;
</source>
However, output is different when a TDog is serialized as a TAnimal:
<source>
var
Dog: TDog;
Animal, Rehydrated: TAnimal;
Json: String;
begin
Dog.Weight := 30;
Dog.FurColor := 'Blond';
Animal := Dog;
TgoBsonSerializer.Serialize(Animal, Json); // Result:
// { "_t" : "TDog", "Weight" : 30.0, "FurColor" : "Blond" }
TgoBsonSerializer.Deserialize(Json, Rehydrated);
// This will actually create a TDog instance (instead of TAnimal)
end;
</source>
In this case, an extra "_t" element is added (called a Discriminator) that
specifies the actual type that is serialized. This way, when you deserialize a
TAnimal, and the JSON/BSON contains a discriminator, it knows what actual type
of class to instantiate.
However, this only works if the serialization engine "knows" about the TDog
type. You have to let the engine know what kind of sub classes can be expected
when deserializing. You do this by calling <tt>RegisterSubClass(es)</tt>:
<source>
TgoBsonSerializer.RegisterSubClass(TDog);
</source>
Note that this is only needed if you plan to deserialize dogs using type
TAnimal. If you always serialize and deserialize dogs as TDog, then you don't
need to do this.
You can choose to always serialize a descriminator, even if not strictly
necessary, by adding a <tt>BsonDiscriminator</tt> attribute to the class:
<source>
type
[BsonDiscriminator(True)]
TAnimal = class
public
Weight: Double;
end;
</source>
The True argument indicates that the descriminator is required. You can also
specify a custom discriminator name using the same attribute:
<source>
type
[BsonDiscriminator('animal', True)]
TAnimal = class
public
Weight: Double;
end;
</source>
This will serialize the descriminator as <tt>{ "_t" : "animal" }</tt> instead of
using the Delphi type name <tt>{ "_t" : "TAnimal" }</tt>. In this case, the
second parameter (True) is optional. If not specified, the descriminator is not
required.
@bold(Custom Serialization)
Is some situations, you may want to customize the way a certain type is
(de)serialized entirely. For example, the TgoAlias type in Grijjy.Protocol.Types
is a record consisting of a prefix and a value. But when serializing records of
this type, you always want to serialize them as a single string containing both
the prefix and value.
To do this, you have to create and register a custom serializer for this type.
You can find an example of a custom serializer for TgoAlias in the
Grijjy.Protocol.Types unit.
First, you create a class derived from TgoBsonSerializer.TCustomSerializer. You
only need to override its Serialize and Deserialize methods. In those methods
you perform the type-specific (de)serialization. Both methods have an untyped
AValue parameter that you must cast to the actual type (TgoAlias in this
example):
<source>
type
TgoAliasSerializer = class(TgoBsonSerializer.TCustomSerializer)
public
procedure Serialize(const AValue; const AWriter: IgoBsonBaseWriter); override;
procedure Deserialize(const AReader: IgoBsonBaseReader; out AValue); override;
end;
procedure TgoAliasSerializer.Deserialize(const AReader: IgoBsonBaseReader;
out AValue);
var
Value: TgoAlias absolute AValue;
begin
// TgoAlias has in implicit conversion operator to convert from a String
Value := AReader.ReadString;
end;
procedure TgoAliasSerializer.Serialize(const AValue;
const AWriter: IgoBsonBaseWriter);
var
Value: TgoAlias absolute AValue;
begin
// TgoAlias has in implicit conversion operator to convert to a String
AWriter.WriteString(Value);
end;
</source>
Next, you need to register the custom serializer for the type. For our example:
<source>
TgoBsonSerializer.RegisterCustomSerializer<TgoAlias>(TgoAliasSerializer);
</source>
@bold(Note) that custom serializers currently only work for record types.
@bold(Notes)
* The Serialize and Deserialize methods will raise an exception if the type is
not serializable, or if the JSON/BSON to deserialize is invalid. To prevent
exceptions, you can use the TrySerialize and TryDeserialize methods instead.
These return False if (de)serialization failed.
* Members of type TDateTime are expected to be un UTC format. No attempt is made
to convert from local time to UTC and vice versa. *)
{$INCLUDE 'Grijjy.inc'}
interface
uses
System.SysUtils,
System.SyncObjs,
System.TypInfo,
System.Rtti,
System.Generics.Collections,
Grijjy.Collections,
Grijjy.Bson,
Grijjy.Bson.IO;
type
{ Type of exception that is raised on serialization errors }
EgoBsonSerializerError = class(Exception);
type
{ Possible representation types for use with BsonRepresentationAttribute }
TgoBsonRepresentation = (Default, Boolean, Int32, Int64, Double, &String,
DateTime, Document, Binary, ObjectId, Symbol);
type
{ Used internally by BsonDefaultValueAttribute to specify a default value }
TgoBsonDefaultValue = record
{$REGION 'Internal Declarations'}
private
constructor Create(const AValue: Boolean); overload;
constructor Create(const AValue: Int32); overload;
constructor Create(const AValue: Int64); overload;
constructor Create(const AValue: String); overload;
private
FAsString: String;
case FRepresentation: TgoBsonRepresentation of
TgoBsonRepresentation.Boolean: (FAsBoolean: Boolean);
TgoBsonRepresentation.Int32: (FAsInt32: Int32);
TgoBsonRepresentation.Int64: (FAsInt64: Int64);
{$ENDREGION 'Internal Declarations'}
end;
type
{ Attribute used to force serializing read-only properties and to modify the
name of an element for serialization }
BsonElementAttribute = class(TCustomAttribute)
{$REGION 'Internal Declarations'}
private
FName: String;
{$ENDREGION 'Internal Declarations'}
public
constructor Create(const AName: String = '');
{ The name the element is serialized as }
property Name: String read FName;
end;
type
{ Apply this attribute to elements you want to ignore for serialization }
BsonIgnoreAttribute = class(TCustomAttribute)
end;
type
{ Apply this attribute to elements you want to ignore if they have the default
value. Can be used in combination with BsonDefaultValueAttribute. }
BsonIgnoreIfDefaultAttribute = class(TCustomAttribute)
end;
type
{ Specifies the default value for an element. Mostly used in combination with
BsonIgnoreIfDefaultAttribute. }
BsonDefaultValueAttribute = class(TCustomAttribute)
{$REGION 'Internal Declarations'}
private
FDefaultValue: TgoBsonDefaultValue;
{$ENDREGION 'Internal Declarations'}
public
constructor Create(const ADefaultValue: Boolean); overload;
constructor Create(const ADefaultValue: Int32); overload;
constructor Create(const ADefaultValue: Int64); overload;
constructor Create(const ADefaultValue: String); overload;
{ The default value of the element }
property DefaultValue: TgoBsonDefaultValue read FDefaultValue;
end;
type
{ Changes the representation type of an element when serializing. For example,
this can be used to serialize Integer elements as Strings. }
BsonRepresentationAttribute = class(TCustomAttribute)
{$REGION 'Internal Declarations'}
private
FRepresentation: TgoBsonRepresentation;
{$ENDREGION 'Internal Declarations'}
public
constructor Create(const ARepresentation: TgoBsonRepresentation);
{ The type to use to serialize the element }
property Representation: TgoBsonRepresentation read FRepresentation;
end;
type
{ Applies a discriminator to a class. See the unit documentation for details }
BsonDiscriminatorAttribute = class(TCustomAttribute)
{$REGION 'Internal Declarations'}
private
FDiscriminator: String;
FRequired: Boolean;
{$ENDREGION 'Internal Declarations'}
public
constructor Create(const ADiscriminator: String;
const ARequired: Boolean = False); overload;
constructor Create(const ARequired: Boolean); overload;
{ The discriminator to use for the class }
property Discriminator: String read FDiscriminator;
{ Whether the discriminator is always serialized or not }
property Required: Boolean read FRequired;
end;
type
{ Apply this attribute to a record or class if you want to raise an exception
when deserializing elements that are not part of the record or class. }
BsonErrorOnExtraElementsAttribute = class(TCustomAttribute)
end;
type
{ Static class for serializing and deserializing to JSON and BSON format }
TgoBsonSerializer = record
{$REGION 'Internal Declarations'}
private type
TSerializer = class abstract
private
FTypeInfo: PTypeInfo;
FIsCustomSerializer: Boolean;
private
function GetTypeKind: TTypeKind; inline;
public
constructor Create(const ATypeInfo: PTypeInfo);
procedure Setup; virtual;
property TypeInfo: PTypeInfo read FTypeInfo;
property TypeKind: TTypeKind read GetTypeKind;
property IsCustomSerializer: Boolean read FIsCustomSerializer;
end;
private type
TInfo = class abstract
private
FName: String;
FType: PTypeInfo;
[unsafe] FSerializer: TSerializer;
FRepresentation: TgoBsonRepresentation;
FDefaultValue: TgoBsonDefaultValue;
FHasDefaultValue: Boolean;
FIgnoreIfDefault: Boolean;
FIsProperty: Boolean;
public
property Name: String read FName;
property &Type: PTypeInfo read FType;
property Representation: TgoBsonRepresentation read FRepresentation;
property IsProperty: Boolean read FIsProperty;
property DefaultValue: TgoBsonDefaultValue read FDefaultValue;
property IgnoreIfDefault: Boolean read FIgnoreIfDefault;
property Serializer: TSerializer read FSerializer;
end;
private type
TVarInfo = class;
TSerializeVarProc = procedure(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter);
TDeserializeVarProc = procedure(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader);
TVarInfo = class(TInfo)
private
FSerializeProc: TSerializeVarProc;
FDeserializeProc: TDeserializeVarProc;
private
procedure GetSerializationProcs(const AType: PTypeInfo);
private
class procedure SerializeBoolean(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeBoolean(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeInt8(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeInt8(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeUInt8(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeUInt8(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeInt16(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeInt16(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeUInt16(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeUInt16(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeInt32(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeInt32(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeUInt32(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeUInt32(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeInt64(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeInt64(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeUInt64(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeUInt64(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeSingle(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeSingle(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeDouble(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeDouble(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeChar(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeChar(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeString(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeString(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeDateTime(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeDateTime(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeGuid(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeGuid(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeObjectId(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeObjectId(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeTBytes(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeTBytes(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeEnum8(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeEnum8(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeEnum16(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeEnum16(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeEnum32(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeEnum32(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeSet8(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeSet8(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeSet16(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeSet16(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeSet32(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeSet32(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeArray(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeArray(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeRecord(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeRecord(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
class procedure SerializeObject(const AVar: TVarInfo;
const AAddress: Pointer; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeObject(const AVar: TVarInfo;
const AAddress: Pointer; const AReader: IgoBsonBaseReader); static;
public
constructor Create(const AType: PTypeInfo);
property SerializeProc: TSerializeVarProc read FSerializeProc;
property DeserializeProc: TDeserializeVarProc read FDeserializeProc;
end;
private type
TFieldInfo = class(TVarInfo)
private
FOffset: Integer;
public
constructor Create(const AStructType: TRttiType; const AField: TRttiField;
const AAttrs: TArray<TCustomAttribute>);
property Offset: Integer read FOffset;
end;
private type
TPropertyInfo = class;
TSerializePropertyProc = procedure(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter);
TDeserializePropertyProc = procedure(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader);
TPropertyInfo = class(TInfo)
private
FSerializeProc: TSerializePropertyProc;
FDeserializeProc: TDeserializePropertyProc;
FInfo: PPropInfo;
private
procedure GetSerializationProcs(const AType: PTypeInfo);
private
class procedure SerializeBoolean(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeBoolean(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeInt32(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeInt32(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeUInt32(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeUInt32(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeInt64(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeInt64(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeUInt64(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeUInt64(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeDouble(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeDouble(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeChar(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeChar(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeString(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeString(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeDateTime(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeDateTime(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeGuid(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeGuid(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeObjectId(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeObjectId(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeTBytes(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeTBytes(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeEnum(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeEnum(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeSet(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeSet(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeArray(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeArray(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeRecord(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeRecord(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
class procedure SerializeObject(const AProp: TPropertyInfo;
const AInstance: TObject; const AWriter: IgoBsonBaseWriter); static;
class procedure DeserializeObject(const AProp: TPropertyInfo;
const AInstance: TObject; const AReader: IgoBsonBaseReader); static;
public
constructor Create(const AStructType: TRttiType; const AProp: TRttiProperty);
property SerializeProc: TSerializePropertyProc read FSerializeProc;
property DeserializeProc: TDeserializePropertyProc read FDeserializeProc;
property Info: PPropInfo read FInfo;
end;
private type
TStructSerializer = class abstract(TSerializer)
private
FFields: TArray<TFieldInfo>;
FInfoByName: TObjectDictionary<String, TInfo>;
FErrorOnExtraElements: Boolean;
private
procedure MapFields(const AStructType: TRttiType);
private
procedure SerializeFields(const ABaseAddress: PByte;
const AWriter: IgoBsonBaseWriter);
protected
procedure Initialize(const AStructType: TRttiType); virtual;
public
destructor Destroy; override;
procedure Setup; override;
end;
private type
TInitializeRecordProc = procedure(const ASelf: Pointer);
TRecordSerializer = class(TStructSerializer)
private
FInitializeProc: TInitializeRecordProc;
private
procedure MapInitialize(const AStructType: TRttiType);
protected
procedure Initialize(const AStructType: TRttiType); override;
public
procedure Serialize(const ABaseAddress: PByte; const AWriter: IgoBsonBaseWriter);
procedure Deserialize(const ABaseAddress: PByte; const AReader: IgoBsonBaseReader);
property InitializeProc: TInitializeRecordProc read FInitializeProc;
end;
private type