-
Notifications
You must be signed in to change notification settings - Fork 89
/
Grijjy.ProtocolBuffers.pas
2250 lines (1993 loc) · 72 KB
/
Grijjy.ProtocolBuffers.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.ProtocolBuffers;
(*<Google Protocol Buffers for Delphi.
This unit contains declarations for serializing attributed Delphi records
in Protocol Buffer format.
It does @bold(not) use the Google Protocol Buffers framework. Instead, it uses
a custom framework, but serializes in a Protocol Buffers compatible bitstream.
@bold(About Protocol Buffers)
Protocol Buffers is both a framework and a bitstream specification:
https://developers.google.com/protocol-buffers/
It is used to serialize messages in an efficient binary format. A message is
a collection of fields, where each field is uniquely identified with an
integer Tag. Fields can be of various simple data types, including integers,
enums, strings, booleans and strings, as well as compound data types such as
nested messages, repeated messages (arrays) and binary data.
@bold(Delphi Implementation)
This Delphi implementation uses attributed records to define messages. These
are regular Delphi records, but fields that are decorated with the [Serialize]
attribute can be serialized. For example:
<source>
type
TPhoneType = (Mobile, Home, Work);
type
TPhoneNumber = record
public
[Serialize(1)] Number: String;
[Serialize(2)] PhoneType: TPhoneType;
public
procedure Initialize;
end;
type
TPerson = record
public
[Serialize(1)] Name: String;
[Serialize(2)] Id: Integer;
[Serialize(3)] Email: String;
[Serialize(4)] MainPhone: TPhoneNumber;
[Serialize(5)] OtherPhones: TArray<TPhoneNumber>;
public
procedure Initialize;
end;
</source>
Each serializable field must be decorated with a [Serialize] attribute with a
single parameter containing the Tag for that field. Tags @bold(must) be unique
within the record, but you can use the same tag in different records or in
nested records. When a record contains duplicate tags, an exception will be
raised when the record is (de)serialized.
Tags start at 1 and must be positive. You should reserve tags 1-15 for the
most common fields, since these tags are stored most efficiently (using 1
byte). Tags 16-2047 are stored in 2 bytes, and other tags take more bytes.
Records are serialized in an extensible way. You can add, delete and reorder
fields without breaking compatibility with older bitstreams. However, you
should never change the tag or data type of a field.
@bold(Supported Data Types)
You can use a wide variety of Delphi data types for your serializable fields:
* UInt8 (Byte), UInt16 (Word), UInt32 (Longword/Cardinal), UInt64
* Int8 (Shortint), Int16 (Smallint), Int32 (Longint/Integer), Int64
* Single, Double
* Boolean
* Enumerated types, @bold(as long as) the type does @bold(not) contain any
explicitly assigned values (Delphi does not provide RTTI for these)
* Records (that is, your field can be of another record type)
* Strings (of type UnicodeString)
* TBytes (for raw binary data)
* 1-dimensional dynamic arrays (TArray<>) of the types described above,
Tech note: all arrays of primitive numeric types (integers, floats and enums)
are stored in "packed" format, which is supported since Protocol Buffers
version 2.1.0. This is a more efficient format that doesn't repeat the tag for
each element. All other array types are stored unpacked (where the tag is
repeated for each element).
The integer data types are stored in an efficient VarInt format. This means
that smaller values are stored in less bytes than larger values. 32-bit
integer types are stored in 1-5 bytes, and 64-bit integer types are stored in
1-10 bytes. Sometimes, you can have integer data that contains random values
across the entire 32-bit or 64-bit range. In those cases, it is more efficient
to store these integers as fixed 32-bit or 64-bit values. You can do this
by declaring the field as one of 4 fixed integer types:
* FixedInt32, FixedUInt32, FixedInt64, FixedUInt64
All other data types can @bold(not) be used for serializable fields. An
exception will be raised when an unsupported data type is encountered.
However, you can still use these types for regular (non-serializable) fields.
In particular, the following types are @bold(not) supported:
* Extended, Comp, Currency
* Class, Object, Interface
* Enumerated types with explicitly assigned values
* AnsiString, RawByteString, UCS4String etc.
* Static arrays
* Multi-dimensional dynamic arrays
@bold(Using the (de)serializer)
Serializing is very easy. You just fill your record with the values you want
to serialize and call:
<source>
TgoProtocolBuffer.Serialize<TPerson>(MyPerson, 'Person.dat');
</source>
This is a generic method with a type parameter that must match the type of
record you are serializing.
Since Delphi is able to infer the generic type from the first parameter, you
can also write this a little bit shorter:
<source>
TgoProtocolBuffer.Serialize(MyPerson, 'Person.dat');
</source>
You can serialize to a file, stream or TBytes array.
Deserializing is equally simple:
<source>
TgoProtocolBuffer.Deserialize(MyPerson, 'Person.dat');
</source>
Because all fields in a record are optional, some fields may not be in the
stream. To prevent the record from having unitialized fields after
deserialization, the record is cleared before it is deserialized (that is, all
fields are set to 0 or nil).
You can also provide your own means of initializing the record with default
values. To do that, you have to add a parameterless Initialize procedure to
your record. Then, the deserialization process will call that routine after
clearing the record (so it will still clear any fields you don't initialize
yourself). *)
{$INCLUDE 'Grijjy.inc'}
interface
uses
System.Classes,
System.SysUtils,
System.TypInfo,
System.SyncObjs,
System.Rtti,
System.Generics.Collections,
Grijjy.SysUtils;
type
{ A 32-bit unsigned integer that is always serialized using 4 bytes. }
FixedUInt32 = type UInt32;
{ A 32-bit signed integer that is always serialized using 4 bytes. }
FixedInt32 = type Int32;
{ A 64-bit unsigned integer that is always serialized using 8 bytes. }
FixedUInt64 = type UInt64;
{ A 64-bit signed integer that is always serialized using 8 bytes. }
FixedInt64 = type Int64;
type
{ Valid range of field tags }
TgoSerializationTag = 1..536870911;
type
{ Exception type that is raise when an error occurs during (de)serialization }
EgoSerializationError = class(Exception)
end;
type
{ A Delphi attribute you use to decorate record fields that need to be
serialized. }
SerializeAttribute = class(TCustomAttribute)
{$REGION 'Internal Declarations'}
private
FTag: TgoSerializationTag;
{$ENDREGION 'Internal Declarations'}
public
{ Attribute constructor }
constructor Create(const ATag: TgoSerializationTag);
{ The tag that is associated with the field to which this attribute is
attached. }
property Tag: TgoSerializationTag read FTag;
end;
type
{ Static class used for (de)serializing records in Protocol Buffer format }
TgoProtocolBuffer = class
{$REGION 'Internal Declarations'}
private
type
TWriter = class(TgoByteBuffer)
public
procedure WriteVarUInt(const AValue: Cardinal);
procedure WriteVarInt(const AValue: Integer); inline;
procedure WriteVarUInt64(const AValue: UInt64);
procedure WriteVarInt64(const AValue: Int64); inline;
end;
type
TReader = class
private
FBuffer: PByte;
FSize: Integer;
FIndex: Integer;
public
constructor Create(const ABuffer: Pointer; const ASize: Integer);
function HasData: Boolean; inline;
procedure Skip(const ASize: Integer); inline;
procedure ReadBytes(out AData; const ASize: Integer);
function ReadByte: Byte; inline;
function ReadVarUInt: Cardinal;
function ReadVarInt: Integer;
function ReadVarUInt64: UInt64;
function ReadVarInt64: Int64;
function PeekVarUInt(out ASize: Integer): Cardinal;
property Index: Integer read FIndex;
end;
type
TInitializeProc = procedure(Self: Pointer);
TSerializeProc = procedure(const AWriter: TWriter; const ARecord: PByte;
const ATag, AOffset: Integer; const AParam: TObject);
TDeserializeProc = procedure(const AReader: TReader; const ARecord: PByte;
const ATag, AOffset: Integer; const AParam: TObject);
type
TFieldTypeInfo = class
strict private
FTag: Integer;
FOffset: Integer;
FSerializeProc: TSerializeProc;
FDeserializeProc: TDeserializeProc;
FParam: TObject;
public
constructor Create(const ATag, AOffset: Integer;
const ASerializeProc: TSerializeProc;
const ADeserializeProc: TDeserializeProc; const AParam: TObject);
property Tag: Integer read FTag;
property Offset: Integer read FOffset;
property SerializeProc: TSerializeProc read FSerializeProc;
property DeserializeProc: TDeserializeProc read FDeserializeProc;
property Param: TObject read FParam;
end;
type
TBaseTypeInfo = class
strict private
FSize: Integer;
FTypeInfo: PTypeInfo;
public
constructor Create(const ATypeInfo: PTypeInfo; const ASize: Integer);
property Size: Integer read FSize;
property TypeInfo: PTypeInfo read FTypeInfo;
end;
type
TRecordTypeInfo = class(TBaseTypeInfo)
strict private
FFields: TArray<TFieldTypeInfo>;
FInitProc: TInitializeProc;
public
constructor Create(const ATypeInfo: PTypeInfo; const ASize: Integer;
const AInitProc: TInitializeProc; const AFields: TArray<TFieldTypeInfo>);
destructor Destroy; override;
procedure Serialize(const AWriter: TWriter; const ARecord: Pointer);
procedure Deserialize(const AReader: TReader; const ARecord: Pointer);
property InitProc: TInitializeProc read FInitProc;
end;
type
TArrayTypeInfo = class(TBaseTypeInfo)
strict private
FElementType: PTypeInfo;
FElementSize: Integer;
FElementInfo: TBaseTypeInfo;
FElementSerializeProc: TSerializeProc;
FElementDeserializeProc: TDeserializeProc;
FElementParam: TObject;
public
constructor Create(const ATypeInfo: PTypeInfo; const ASize: Integer;
const AElementType: PTypeInfo; const AElementSize: Integer;
const AElementInfo: TBaseTypeInfo;
const AElementSerializeProc: TSerializeProc;
const AElementDeserializeProc: TDeserializeProc;
const AElementParam: TObject);
property ElementType: PTypeInfo read FElementType;
property ElementSize: Integer read FElementSize;
property ElementInfo: TBaseTypeInfo read FElementInfo;
property ElementSerializeProc: TSerializeProc read FElementSerializeProc;
property ElementDeserializeProc: TDeserializeProc read FElementDeserializeProc;
property ElementParam: TObject read FElementParam;
end;
private
class var FTypeInfoMap: TObjectDictionary<Pointer, TBaseTypeInfo>;
class var FTypeInfoMapLock: TCriticalSection;
private
class function RegisterRecordTypeInfo(const ATypeInfo: Pointer): TRecordTypeInfo; static;
class function RegisterArrayTypeInfo(const ATypeInfo: PTypeInfo): TArrayTypeInfo; static;
class function GetSerializationProcs(const AType: TRttiType;
out ASerializeProc: TSerializeProc; out ADeserializeProc: TDeserializeProc;
out AParam: TObject): Boolean; static;
private
class procedure SerializeUInt8(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeUInt16(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeUInt32(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeUInt64(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeInt8(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeInt16(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeInt32(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeInt64(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeFixed32(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeFixed64(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeUString(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeRecord(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeBytes(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeDynArrayPacked(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure SerializeDynArrayUnpacked(const AWriter: TWriter;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
private
class procedure DeserializeUInt8(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeUInt16(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeUInt32(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeUInt64(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeInt8(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeInt16(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeInt32(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeInt64(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeFixed32(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeFixed64(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeUString(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeBytes(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeRecord(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeDynArrayPacked(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
class procedure DeserializeDynArrayUnpacked(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject); static;
public
{ @exclude }
class constructor Create;
{ @exclude }
class destructor Destroy;
{$ENDREGION 'Internal Declarations'}
public
{ Serializes a record to an array of bytes.
Parameters:
T: the type of the record to serialize.
ARecord: the record (of type T) to serialize.
Returns:
A byte array containing the serialized record. }
class function Serialize<T: record>(const ARecord: T): TBytes; overload; static; inline;
{ Serializes a record to an array of bytes.
Parameters:
ARecordType: the type of the record to serialize. This is the result
from a TypeInfo(TMyRecord) call.
ARecord: the record (of ARecordType) to serialize.
Returns:
A byte array containing the serialized record. }
class function Serialize(const ARecordType: Pointer;
const ARecord): TBytes; overload; static;
{ Serializes a record to a file.
Parameters:
T: the type of the record to serialize.
ARecord: the record (of type T) to serialize.
AFilename: the name of the file to serialize the record to. }
class procedure Serialize<T: record>(const ARecord: T;
const AFilename: String); overload; static; inline;
{ Serializes a record to a file.
Parameters:
ARecordType: the type of the record to serialize. This is the result
from a TypeInfo(TMyRecord) call.
ARecord: the record (of ARecordType) to serialize.
AFilename: the name of the file to serialize the record to. }
class procedure Serialize(const ARecordType: Pointer; const ARecord;
const AFilename: String); overload; static;
{ Serializes a record to a stream.
Parameters:
T: the type of the record to serialize.
ARecord: the record (of type T) to serialize.
AStream: the stream to serialize the record to. }
class procedure Serialize<T: record>(const ARecord: T;
const AStream: TStream); overload; static; inline;
{ Serializes a record to a stream.
Parameters:
ARecordType: the type of the record to serialize. This is the result
from a TypeInfo(TMyRecord) call.
ARecord: the record (of ARecordType) to serialize.
AStream: the stream to serialize the record to. }
class procedure Serialize(const ARecordType: Pointer; const ARecord;
const AStream: TStream); overload; static;
{ Deserializes a record from an array of bytes.
When the record contains a parameterless @code(Initialize) procedure, then
that procedure will be called before the record is deserialized.
Parameters:
T: the type of the record to deserialize.
ARecord: the record (of type T) to deserialize.
AData: the byte array containing the serialized record. }
class procedure Deserialize<T: record>(out ARecord: T;
const AData: TBytes); overload; static; inline;
{ Deserializes a record from an array of bytes.
When the record contains a parameterless @code(Initialize) procedure, then
that procedure will be called before the record is deserialized.
Parameters:
ARecordType: the type of the record to deserialize. This is the result
from a TypeInfo(TMyRecord) call.
ARecord: the record (of ARecordType) to deserialize.
AData: the byte array containing the serialized record. }
class procedure Deserialize(const ARecordType: Pointer; out ARecord;
const AData: TBytes); overload; static;
{ Deserializes a record from a memory buffer.
When the record contains a parameterless @code(Initialize) procedure, then
that procedure will be called before the record is deserialized.
Parameters:
T: the type of the record to deserialize.
ARecord: the record (of type T) to deserialize.
ABuffer: the memory buffer containing the serialized record.
ABufferSize: the size of the buffer }
class procedure Deserialize<T: record>(out ARecord: T; const ABuffer: Pointer;
const ABufferSize: Integer); overload; static; inline;
{ Deserializes a record from a stream.
When the record contains a parameterless @code(Initialize) procedure, then
that procedure will be called before the record is deserialized.
Parameters:
T: the type of the record to deserialize.
ARecordType: the type of the record to deserialize. This is the result
from a TypeInfo(TMyRecord) call.
ARecord: the record (of ARecordType) to deserialize.
ABuffer: the memory buffer containing the serialized record.
ABufferSize: the size of the buffer }
class procedure Deserialize(const ARecordType: Pointer; out ARecord;
const ABuffer: Pointer; const ABufferSize: Integer); overload; static;
{ Deserializes a record from a file.
When the record contains a parameterless @code(Initialize) procedure, then
that procedure will be called before the record is deserialized.
Parameters:
T: the type of the record to deserialize.
ARecord: the record (of type T) to deserialize.
AFilename: the name of the file containing the serialized record. }
class procedure Deserialize<T: record>(out ARecord: T; const AFilename: String); overload; static; inline;
{ Deserializes a record from a file.
When the record contains a parameterless @code(Initialize) procedure, then
that procedure will be called before the record is deserialized.
Parameters:
ARecordType: the type of the record to deserialize. This is the result
from a TypeInfo(TMyRecord) call.
ARecord: the record (of ARecordType) to deserialize.
AFilename: the name of the file containing the serialized record. }
class procedure Deserialize(const ARecordType: Pointer; out ARecord;
const AFilename: String); overload; static;
{ Deserializes a record from a stream.
When the record contains a parameterless @code(Initialize) procedure, then
that procedure will be called before the record is deserialized.
Parameters:
T: the type of the record to deserialize.
ARecord: the record (of type T) to deserialize.
AStream: the stream containing the serialized record. }
class procedure Deserialize<T: record>(out ARecord: T; const AStream: TStream); overload; static; inline;
{ Deserializes a record from a stream.
When the record contains a parameterless @code(Initialize) procedure, then
that procedure will be called before the record is deserialized.
Parameters:
T: the type of the record to deserialize.
ARecordType: the type of the record to deserialize. This is the result
from a TypeInfo(TMyRecord) call.
ARecord: the record (of ARecordType) to deserialize.
AStream: the stream containing the serialized record. }
class procedure Deserialize(const ARecordType: Pointer; out ARecord;
const AStream: TStream); overload; static;
{ Registers a record for serialization in Protocol Buffer format. This is
only needed for use with Free Pascal. When using Delphi, the record type is
automatically registered when it is first (de)serialized.
You can also use this method to register 3rd party or RTL record types.
Every record type you want to use for serialization must be registered
once and only once. You usually do this at application startup. If a
record has fields of other record types, then those other record types
must be registered as well.
To register a record, you must declare a dummy variable of the record
type and then call this method as in the following example:
<source>
var
P: TPerson; // Dummy variable
begin
TgoProtocolBuffer.Register(TypeInfo(TPerson), P, @TPerson.Initialize,
[@P.Name, 1, @P.Id, 2, @P.Email, 3, @P.Phone, 4]);
end;
</source>
The parameters are the @code(TypeInfo(..)) of the record type, the dummy
variable, the optional address of an Initialize method and an array of
tags and field addresses.
The dummy variable is just used as a helper to pass the field addresses.
You don't need to initialize this variable with any data.
Before a record of this type is deserialized, its fields are always
cleared (set to 0 or nil). You can perform additional initialization after
this by specifying an Initialize method. If set, that method will be
called after clearing all fields, but before deserializing. Pass nil to
clear the record only.
The final parameter is an array of tags and field addresses. Each tag
uniquely identifies the corresponding field. Tags must be in the range
1-536870911. Tags must be unique within the record and each tag must have
a corresponding field address. If the number of tags doesn't match the
number of addresses, or if there are any other invalid parameters, then an
exception is raised.
You can pass the tags and field addresses in any way you want, as long as
you pass the tags in the same order as the corresponding field addresses.
You can use the (Field, Tag)* order as in the example above, or the
opposite (Tag, Field)* order as in this example:
<source>[1, @P.Name, 2, @P.Id, 3, @P.Email, 4, @P.Phone]</source>
You can also specify all fields first, followed by all tags, or the other
way around:
<source>[@P.Name, @P.Id, @P.Email, @P.Phone, 1, 2, 3, 4]</source>
Or any other combination that makes sense in the declaration:
<source>
[@P.Name, @P.Id,
1 , 2,
@P.Email, @P.Phone,
3 , 4]
</source>
Just remember that the order of the tags must match the order of the
fields.
Parameters:
ARecordType: the type of the record to register. This is the result
from a TypeInfo(TMyRecord) call.
ARecord: a dummy instance of the record type to register (of type
ARecordType).
AInitializeProc: the record method to call to initialize the record
with its default values.
AFields: an array of tags and record field addresses. See the
documentation above for more information. }
class procedure Register(const ARecordType: Pointer; const ARecord;
const AInitializeProc: TInitializeProc; const AFields: array of const); static;
end;
implementation
uses
Grijjy.Collections;
const
WIRE_TYPE_VARINT = 0;
WIRE_TYPE_64BIT = 1;
WIRE_TYPE_VARIABLE_SIZE = 2;
WIRE_TYPE_START_GROUP = 3;
WIRE_TYPE_END_GROUP = 4;
WIRE_TYPE_32BIT = 5;
type
PInt8 = ^Int8;
PInt16 = ^Int16;
PInt32 = ^Int32;
PUInt8 = ^UInt8;
PUInt16 = ^UInt16;
PUInt32 = ^UInt32;
{ SerializeAttribute }
constructor SerializeAttribute.Create(const ATag: TgoSerializationTag);
begin
inherited Create;
FTag := ATag;
end;
{ TgoProtocolBuffer }
class constructor TgoProtocolBuffer.Create;
begin
FTypeInfoMap := TObjectDictionary<Pointer, TBaseTypeInfo>.Create([doOwnsValues]);
FTypeInfoMapLock := TCriticalSection.Create;
end;
class procedure TgoProtocolBuffer.Deserialize<T>(out ARecord: T;
const AData: TBytes);
begin
Deserialize(TypeInfo(T), ARecord, AData);
end;
class procedure TgoProtocolBuffer.Deserialize<T>(out ARecord: T;
const ABuffer: Pointer; const ABufferSize: Integer);
begin
Deserialize(TypeInfo(T), ARecord, ABuffer, ABufferSize);
end;
class procedure TgoProtocolBuffer.Deserialize<T>(out ARecord: T;
const AFilename: String);
begin
Deserialize(TypeInfo(T), ARecord, AFilename);
end;
class procedure TgoProtocolBuffer.Deserialize<T>(out ARecord: T;
const AStream: TStream);
begin
Deserialize(TypeInfo(T), ARecord, AStream);
end;
class procedure TgoProtocolBuffer.Deserialize(const ARecordType: Pointer;
out ARecord; const AData: TBytes);
begin
Deserialize(ARecordType, ARecord, Pointer(AData), Length(AData));
end;
class procedure TgoProtocolBuffer.Deserialize(const ARecordType: Pointer;
out ARecord; const ABuffer: Pointer; const ABufferSize: Integer);
var
RecordTypeInfo: TRecordTypeInfo;
RecordPtr: Pointer;
Reader: TReader;
begin
RecordPtr := @ARecord;
RecordTypeInfo := RegisterRecordTypeInfo(ARecordType);
Reader := TReader.Create(ABuffer, ABufferSize);
try
RecordTypeInfo.Deserialize(Reader, RecordPtr);
finally
Reader.Free;
end;
end;
class procedure TgoProtocolBuffer.Deserialize(const ARecordType: Pointer;
out ARecord; const AFilename: String);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(AFilename, fmOpenRead or fmShareDenyWrite);
try
Deserialize(ARecordType, ARecord, Stream);
finally
Stream.Free;
end;
end;
class procedure TgoProtocolBuffer.Deserialize(const ARecordType: Pointer;
out ARecord; const AStream: TStream);
var
Bytes: TBytes;
begin
SetLength(Bytes, AStream.Size - AStream.Position);
if Assigned(Bytes) then
AStream.ReadBuffer(Bytes[0], Length(Bytes));
Deserialize(ARecordType, ARecord, Bytes);
end;
class procedure TgoProtocolBuffer.Register(const ARecordType: Pointer; const ARecord;
const AInitializeProc: TInitializeProc; const AFields: array of const);
var
Context: TRttiContext;
RecordAddress, RecordEndAddress: NativeUInt;
RecordType, FieldType: TRttiType;
RecordTypeInfo: TRecordTypeInfo;
Tags: TArray<Integer>;
Offsets: TArray<NativeUInt>;
TagSet: TgoSet<Integer>;
OffsetToTag: TDictionary<NativeUInt, Integer>;
OffsetsToIgnore: TgoSet<NativeUInt>;
I, FieldCount, TagCount, OffsetCount, Count, Tag: Integer;
V: TVarRec;
Fields: TArray<TRttiField>;
Field: TRttiField;
FieldInfo: TFieldTypeInfo;
FieldInfos: TArray<TFieldTypeInfo>;
SerializeProc: TSerializeProc;
DeserializeProc: TDeserializeProc;
Param: TObject;
begin
Assert(Assigned(FTypeInfoMap));
if (ARecordType = nil) then
raise EgoSerializationError.Create('Invalid call to TgoProtocolBuffer.Register. ARecordType cannot be nil.');
if (FTypeInfoMap.ContainsKey(ARecordType)) then
raise EgoSerializationError.Create('Invalid call to TgoProtocolBuffer.Register. Duplicate registration of type ' + GetTypeName(ARecordType));
Context := TRttiContext.Create;
RecordType := Context.GetType(ARecordType);
if (RecordType = nil) then
raise EgoSerializationError.Create('Unable to get data type for type ' + GetTypeName(ARecordType));
if (Length(AFields) = 0) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). No fields specified.', [RecordType.Name]);
if (Odd(Length(AFields))) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Number of elements in AFields array must be even.', [RecordType.Name]);
RecordAddress := NativeUInt(@ARecord);
RecordEndAddress := RecordAddress + NativeUInt(RecordType.TypeSize);
FieldCount := Length(AFields) div 2;
SetLength(Tags, FieldCount);
SetLength(Offsets, FieldCount);
TagCount := 0;
OffsetCount := 0;
TagSet := TgoSet<Integer>.Create;
try
{ Sort all AFields values into tags and offsets }
for I := 0 to Length(AFields) - 1 do
begin
V := AFields[I];
if (V.VType = vtInteger) then
begin
if (TagCount >= FieldCount) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Too many tags specified.', [RecordType.Name]);
if (TagSet.Contains(V.VInteger)) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Duplicate tag %d.', [RecordType.Name, V.VInteger]);
if ((V.VInteger < 1) or (V.VInteger > 536870911)) and (V.VInteger <> -1) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Tag %d must be between 1 and 536870911.', [RecordType.Name, V.VInteger]);
TagSet.Add(V.VInteger);
Tags[TagCount] := V.VInteger;
Inc(TagCount);
end
else if (V.VType = vtPointer) then
begin
if (OffsetCount >= FieldCount) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Too many field addresses specified.', [RecordType.Name]);
if (NativeUInt(V.VPointer) < RecordAddress) or (NativeUInt(V.VPointer) >= RecordEndAddress) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Field address does not belong to record.', [RecordType.Name]);
Offsets[OffsetCount] := NativeUInt(V.VPointer) - RecordAddress;
Inc(OffsetCount);
end
else
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Each AFields element must be an Integer (tag) or Pointer (field address).', [RecordType.Name]);
end;
finally
TagSet.Free;
end;
if (TagCount <> FieldCount) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Insufficient number of tags specified.', [RecordType.Name]);
if (OffsetCount <> FieldCount) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Insufficient number of field addresses specified.', [RecordType.Name]);
Count := 0;
OffsetsToIgnore := nil;
OffsetToTag := TDictionary<NativeUInt, Integer>.Create;
try
OffsetsToIgnore := TgoSet<NativeUInt>.Create;
for I := 0 to FieldCount - 1 do
begin
if (Tags[I] > 0) then
begin
if (OffsetToTag.TryGetValue(Offsets[I], Tag)) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Duplicate field offset %d (tags %d and %d).', [RecordType.Name, Offsets[I], Tag, Tags[I]]);
OffsetToTag.Add(Offsets[I], Tags[I]);
end
else
OffsetsToIgnore.AddOrSet(Offsets[I]);
end;
Fields := RecordType.GetDeclaredFields;
SetLength(FieldInfos, FieldCount);
for Field in Fields do
begin
if (OffsetToTag.TryGetValue(Field.Offset, Tag)) then
begin
FieldType := Field.FieldType;
if (not GetSerializationProcs(FieldType, SerializeProc, DeserializeProc, Param)) then
begin
if (OffsetsToIgnore.Contains(Field.Offset)) then
Continue;
if (FieldType.TypeKind in [tkString, tkLString, tkWString]) then
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Unsupported data type "%s". Note that string types other than UnicodeString are not supported.', [RecordType.Name, FieldType.Name])
else
raise EgoSerializationError.CreateFmt('Invalid call to TgoProtocolBuffer.Register(%s). Unsupported data type "%s".', [RecordType.Name, FieldType.Name]);
end;
Assert(Count < FieldCount);
FieldInfo := TFieldTypeInfo.Create(Tag, Field.Offset, SerializeProc, DeserializeProc, Param);
FieldInfos[Count] := FieldInfo;
Inc(Count);
{ Remove this field offset. This is to support variant parts in record.
For example, TRectF is defined as:
TRectF = record
case Integer of
0: (Left, Top, Right, Bottom: Single);
1: (TopLeft, BottomRight: TPointF);
end;
Both Left and TopLeft have the same offset. However, once Left has
been processed, we don't want to process TopLeft anymore.
NOTE: this means that only the "first variants" in a variant record
can be registered (the 4 Single fields in this example }
OffsetToTag.Remove(Field.Offset);
end;
end;
finally
OffsetsToIgnore.Free;
OffsetToTag.Free;
end;
if (Count = 0) then
raise EgoSerializationError.CreateFmt('Unable register record type %s. It does not contain any [Serialize] fields',
[RecordType.Name]);
SetLength(FieldInfos, Count);
RecordTypeInfo := TRecordTypeInfo.Create(ARecordType, RecordType.TypeSize, AInitializeProc, FieldInfos);
{ Another thread may already have registered the same type in the meantime.
In that case, ignore this one and use the existing type. }
Assert(Assigned(FTypeInfoMap));
Assert(Assigned(FTypeInfoMapLock));
FTypeInfoMapLock.Enter;
try
if (FTypeInfoMap.ContainsKey(ARecordType)) then
{ Ignore and free the type we just created. }
FreeAndNil(RecordTypeInfo)
else
FTypeInfoMap.Add(ARecordType, RecordTypeInfo);
finally
FTypeInfoMapLock.Leave;
end;
end;
class procedure TgoProtocolBuffer.DeserializeBytes(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject);
type
PBytes = ^TBytes;
var
Len: Integer;
Bytes: TBytes;
P: PBytes;
begin
Len := AReader.ReadVarUInt;
if (Len > 0) then
begin
SetLength(Bytes, Len);
AReader.ReadBytes(Bytes[0], Len);
end;
P := @ARecord[AOffset];
P^ := Bytes;
end;
class procedure TgoProtocolBuffer.DeserializeDynArrayPacked(const AReader: TReader;
const ARecord: PByte; const ATag, AOffset: Integer; const AParam: TObject);
var
ArrayInfo: TArrayTypeInfo absolute AParam;
ElementDeserializeProc: TDeserializeProc;
ElementParam: TObject;
ElementSize, Len, EndIndex, Count: Integer;
Capacity: NativeInt;
PA: PPointer;
P: Pointer;
Element: PByte;
begin
Assert(Assigned(AParam));
Assert(AParam is TArrayTypeInfo);
ElementDeserializeProc := ArrayInfo.ElementDeserializeProc;
ElementParam := ArrayInfo.ElementParam;
ElementSize := ArrayInfo.ElementSize;
PA := @ARecord[AOffset];
P := PA^;
Element := P;
Len := AReader.ReadVarUInt;
EndIndex := AReader.Index + Len;
Count := 0;
Capacity := 0;
while (AReader.Index < EndIndex) do
begin
if (Count >= Capacity) then
begin
Inc(Capacity, 16);
DynArraySetLength(P, ArrayInfo.TypeInfo, 1, @Capacity);
Element := PByte(P) + (Count * ElementSize);
end;
Inc(Count);
ElementDeserializeProc(AReader, Element, ATag, 0, ElementParam);
Inc(Element, ElementSize);
end;
Assert(AReader.Index = EndIndex);
Capacity := Count;
DynArraySetLength(P, ArrayInfo.TypeInfo, 1, @Capacity);
PA^ := P;
end;
class procedure TgoProtocolBuffer.DeserializeDynArrayUnpacked(
const AReader: TReader; const ARecord: PByte; const ATag, AOffset: Integer;
const AParam: TObject);
var
ArrayInfo: TArrayTypeInfo absolute AParam;
ElementDeserializeProc: TDeserializeProc;
ElementParam: TObject;
PA: PPointer;
P: Pointer;
Element: PByte;
Count, NextTag, Size, ElementSize: Integer;
Capacity: NativeInt;
begin
Assert(Assigned(AParam));
Assert(AParam is TArrayTypeInfo);
ElementDeserializeProc := ArrayInfo.ElementDeserializeProc;
ElementParam := ArrayInfo.ElementParam;
ElementSize := ArrayInfo.ElementSize;
PA := @ARecord[AOffset];
P := PA^;
Element := P;
Count := 0;
Capacity := 0;
while True do
begin
if (Count >= Capacity) then
begin
Inc(Capacity, 16);
DynArraySetLength(P, ArrayInfo.TypeInfo, 1, @Capacity);
Element := PByte(P) + (Count * ElementSize);
end;