-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSuperStream.pas
2031 lines (1769 loc) · 65 KB
/
SuperStream.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
{**
SuperStream is copyright (c) 2000 Ross Judson.<P>
The contents of this file are subject to the Mozilla Public License
Version 1.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the
License at http://www.mozilla.org/MPL/ <P>
SuperStream documentation is in DelphiDoc format. For information on
DelphiDoc, please visit www.soletta.com. Any updates to SuperStream can
also be found there. <P>
Use tab size 2. <P>
The SuperStream brings several important new capabilities to Delphi. <P>
First, the TStreamAdapter class permits the construction of streams
that alter or buffer the data that passes through them, on the way to
another stream. An ownership concept is present, so that the streams
are easy to build and free. This enables, for example, easy buffering
of TFileStreams. The stock TFileStream is unbuffered and rather slow
if many small io operations are made to it. A TBufferedStream adapter
can be placed on top of it to improve performance. Stream adapters can
be chained, so a TObjStream can be placed over a TBufferedStream, which
is over a TFileStream, and so on. <P>
TBufferedStreams speed up io against the underlying stream if it is slow
for many small reads and writes. <P>
TObjStream permits the easy storage and recovery of complex object graphs,
complete with versioning. It makes use of as much information as it
can that is provided by the Delphi compiler. Usage of the object streams
is as simple as declaring an "object io procedure" for a class of
object and registering it. TObjStream differs from most object streaming
code in that it makes heavy use of Delphi's open arrays to make coding
as easy as possible. <P>
TObjStream understands class hierarchies, so any io procedures that are
declared for superclasses are also called. <P>
TObjStream is suitable for many lightweight object storage tasks. Couple
TObjStream objects together with TBufferedStreams to improve performance. <P>
Here are the steps to use an object stream: <P>
</UL>
<LI> Decide which classes should be persistent.</LI>
<LI> Write IO procedures for those classes. Each IO procedure should have
the following signature:
<CODE> TObjIO = procedure(obj : TObject; stream : TObjStream; direction : TObjIODirection; version : Integer; var callSuper : Boolean); </CODE> </LI>
<LI> Register the IO procedures by calling TObjStream.RegisterClass. </LI>
<LI> Create an object stream then read or write to it using WriteObject or
ReadObject. </LI>
</UL> <P>
Your IO procedure should be prepared to receive a version number other than
the tip revision. If it receives an older version, it should correctly
load the older version of the object. The best way to do this is to use
case statements, switching on the object version. When you write objects,
you should generally write the latest version. By doing this, your
application can read in old objects, but will automatically upgrade them
to the latest version. See the TestIO routine in the sample file for
an example of this.<P>
If you wish to register a class for IO but don't need to provide a procedure
for it 'cause the superclass procedure will do, you still need to call
RegisterClass. Pass nil in place of an IO procedure pointer.
See the StrTestFrm.pas file for example IO procedures. You will primarily
be using the TransferItems and TransferItemsEx calls. If you need to
handle TDateTime, Single, or Double, make sure you use the TransferItemsEx
call, passing the ssvt constants appropriate to your data.<P>
To transfer arrays of items, use the TransferArrays calls. <P>
Serializing sets can be a bit tricky. Use the TransferBlocks call to
handle sets -- pass the address of the set and do a SizeOf() call on the
set to find out how much data to store. <P>
Note that you can freely mix calls to WriteObject and the various
transfer calls during your IO procedures. <P>
Here is an example IO procedure: <P>
<PRE><CODE>
procedure TestIO(obj : TObject; stream : TObjStream; direction : TObjIODirection; version : Integer; var callSuper : Boolean);
begin
with obj as TTest do
case version of
1:
begin
// old version didn't have a t value
stream.TransferItems([s], [@s], direction, version);
t := 'yipe';
end;
2:
stream.TransferItems([s,t], [@s, @t], direction, version);
end;
end;
</CODE></PRE>
}
// We violate range checking in a few places here, deliberately.
{$RANGECHECKS OFF}
{$IFDEF VER100}
{$DEFINE DELPHI3}
{$ENDIF}
{$IFDEF VER110}
{$DEFINE DELPHI3}
{$ENDIF}
{$IFDEF VER120}
{$DEFINE DELPHI4}
{$ENDIF}
unit SuperStream;
interface
uses Classes, SysUtils;
const
// These are straight from system.pas, except we've added ssvtSingle and ssvtDouble
// so we can handle those kind of values.
ssvtNone = -1;
{** Indicates that the item is a single-precision (4 byte) floating point number. }
ssvtSingle = -2;
{** Indicates that the item is a double-precision (8 byte) floating point number. }
ssvtDouble = -3;
{** Indicates that the item is a TDateTime, which is really a double. }
ssvtDateTime = ssvtDouble;
{** Indicate that the item is an integer (32-bit). }
ssvtInteger = vtInteger ;
{** Indicate that the item is a boolean. }
ssvtBoolean = vtBoolean ;
{** Indicate that the item is a character. }
ssvtChar = vtChar ;
{** Indicate that the item is an extended floating point value. Unless your variable
is specifically declared as extended, you will rarely want to use this. Instead,
use the ssvtSingle or ssvtDouble as appropriate. }
ssvtExtended = vtExtended ;
{** Indicate that the item is a short string. }
ssvtString = vtString ;
{** Indicate that the item is a pointer. }
ssvtPointer = vtPointer ;
{** Indicate that the item is a pointer to character. }
ssvtPChar = vtPChar ;
{** Indicate that the item is an object. }
ssvtObject = vtObject ;
{** Indicate that the item is a class object. }
ssvtClass = vtClass ;
{** Indicate that the item is a wide character. }
ssvtWideChar = vtWideChar ;
{** Indicate that the item is a pointer to wide characters. }
ssvtPWideChar = vtPWideChar ;
{** Indicate that the item is an AnsiString (long string). }
ssvtAnsiString = vtAnsiString;
{** Indicate that the item is a currency value (like extended). }
ssvtCurrency = vtCurrency ;
{** Indicate that the item is a variant (not supported). }
ssvtVariant = vtVariant ;
{** Indicate that the item is an interface (not supported). }
ssvtInterface = vtInterface ;
{** Indicate that the item is a wide string (not supported). }
ssvtWideString = vtWideString;
{** Delphi 10 Unicode String }
ssvtUnicodeString = vtUnicodeString;
{$IFDEF DELPHI4}
ssvtInt64 = vtInt64;
{$ENDIF}
type
TInitializer = procedure;
{** TStreamAdapter defines a stream that wraps another stream. }
TStreamAdapter = class(TStream)
public
{** Construct a stream adapter.
@param targetStream The stream being adapted.
@param owned If true, the stream being adapted will be destroyed
when the adapter is destroyed. }
constructor Create(targetStream : TStream; owned : Boolean);
{** Destroy a stream adapter. Will also destroy the target stream if
the owned flag is set true. }
destructor Destroy; override;
{** Read count bytes into buffer. This is an override of the standard
stream function.
@param buffer Variable to read bytes into.
@param count Number of bytes to read. }
function Read(var Buffer; Count: Longint): Longint; override;
{** write count bytes to the stream. This is an override of the standard
stream function.
@param buffer Variable to write to the stream.
@param count Number of bytes to write. }
function Write(const Buffer; Count: Longint): Longint; override;
{** Move to a given position in the stream.
@param offset The position to move to.
@param origin Where to move: Can be soFromBeginning, soFromCurrent, or soFromEnd. }
function Seek(Offset: Longint; Origin: Word): Longint; override;
protected
{** The stream being adapted. }
FStream : TStream;
{** Indicates Whether the target stream will be freed on destruction of
the adapter. }
FOwned : Boolean;
procedure SetSize(NewSize: Longint); override;
private
procedure _SetSize(NewSize : LongInt);
end;
{** Exceptions thrown by the object streaming system will be of this class
or a descendent. }
TObjStreamException = class(Exception)
end;
TObjStream = class;
{** This determines the whether the io is read or write. }
TObjIODirection = (iodirRead, iodirWrite);
{** IO procedures must have this signature. obj is the object being read or
written. If being written, you will probably want to case the object to
the correct type. If being read, the object will already have been created,
but will NOT have had a constructor called. If your object requires that
a constructor be called, invoke it directly, as in obj.Create. This will
not create a new object, but will initialize yours. Note that many
constructors just initialize variables -- if you're about to read in all
those variables, you don't need to set them beforehand. <P>
Stream is the object stream. You may invoke any of its methods in your
IO procedure, including WriteObject and the TransferXXX family. <P>
Direction indicates whether the call is for reading (iodirRead) or writing
(iodirWrite). Most of the time you won't have to worry about this --
the TransferXXX calls read and write objects automatically depending on
the direction flag passed to them. <P>
Version is the version of the object. You will always be requested to
write only the latest version of an object, unless you specifically
try to write an earlier version yourself. SuperStream won't do it. You
may be asked to read an earlier version of an object. You should make
sure you correctly read the earlier version, and fill in any extra
information that isn't covered. That way you'll have automatic upgrading
of your objects. <P>
CallSuper is a boolean that's preset to true, indicating that the superClass'
IO procedure will be called. If you don't want the superClass' IO procedure
to be called, set this to false before returning. <P>
}
TObjIO = procedure(obj : TObject; stream : TObjStream; direction : TObjIODirection; version : Integer; var callSuper : Boolean);
TObjCreation = procedure(obj : TObject; stream : TObjStream; version : Integer) of object;
TStreamRegistration = class;
{** Each object stream starts with one of these. }
TObjStreamHeader = record
magic : Integer;
dummy1, dummy2, dummy3, dummy4 : Integer;
end;
{** Options that can be applied to object streams. Currently only the
graph option is supported. Supplying osoGraph as an option permits the
reading and writing of arbitrary graphs of objects. If this option is
not supplied, objects will be written in full each time they are
encountered. It is highly recommended that the osoGraph option be supplied
if there is any chance of an object appearing more than once. Not supplying
the option will result in a small speedup. }
TObjStreamOption = (
osoGraph // support object graphs
);
{** A set of stream options. }
TObjStreamOptions = set of TObjStreamOption;
{** Object stream adapters read and write objects from other streams. It is
often useful to couple this adapter with a buffering adapter, as object
streams frequently read and write with thousands of small byte count io
operations. }
TObjStream = class(TStreamAdapter)
protected
FUnicodeStringBuffer : UnicodeString;
{** Indicates whether the header has already been transferred. }
FHeaderTransferred : Boolean;
{** Stores the options this stream has active. }
FOptions : TObjStreamOptions;
{** Stores the list of objects that have been written or read. This
is only used in graph mode. }
FObjList : TList;
{** Hook for programs to modify object construction. }
FObjCreation : TObjCreation;
public
{** If assigned, this event will be fired whenever a new object is created.
This gives the program a chance to alter the construction of the new object. }
property OnObjCreation : TObjCreation read FObjCreation write FObjCreation;
{** Register class notifies the streaming system of a persistent capable class.
@param cls The class being registered.
@param _writer An io procedure for the class.
@param latest The current version number for the class (an integer).
The version number will usually be incremented each time
the structure of the object changes. }
class procedure RegisterClass(cls : TClass; _writer : TObjIO; latest : Integer);
{** Register class notifies the streaming system of a persistent capable class.
@param cls The class being registered.
@param _writer An io procedure for the class.
@param latest The current version number for the class (an integer).
The version number will usually be incremented each time
the structure of the object changes.
@param init Object initializer. }
class procedure RegisterClassEx(cls : TClass; _writer : TObjIO; latest : Integer; init : TInitializer);
{** Assigns default io procedures for some of Delphi's classes. If this
is not called, io procedures will have to be registered for all classes.
IO procedures are registered for TStringList and TObjList. TObjList is
a list of objects, and is contained within this unit. }
class procedure RegisterDefaultClasses;
{** Reads a single object from a file, very conveniently.
@param filename The file to read the object from. }
class function ReadObjectInFile(const fn : String; options : TObjStreamOptions) : TObject;
{** Writes a single object to a file, conveniently.
@param filename The file to write the object info.
@param obj The object to write. The object must have its class registered. }
class procedure WriteObjectToFile(const fn : String; options : TObjStreamOptions; obj : TObject);
{** Reads a single object from a stream, very conveniently.
@param stream The stream to read the object from. }
class function ReadObjectInStream(const f : TStream; options : TObjStreamOptions) : TObject;
{** Writes a single object to a file, conveniently.
@param filename The file to write the object info.
@param obj The object to write. The object must have its class registered. }
class procedure WriteObjectToStream(const f : TStream; options : TObjStreamOptions; obj : TObject);
{** Construct an object stream.
@param stream The stream to read or write objects to/from.
@param owned If true, the target stream will be freed when the object stream
is freed.
@param options Options from the TobjStreamOption type.}
constructor Create(stream : TStream; owned : Boolean; options : TObjStreamOptions);
{** Construct an object stream on a file. The stream will be buffered
internally. You must also specify whether you intend to read or write
from the stream.
@param fn The file to use for streaming.
@param options Options from the TObjStreamOption type.
@param dir The IO direction (iodirRead, iodirWrite). }
constructor CreateOnFile(const fn : String; options : TObjStreamOptions; dir : TObjIODirection);
destructor Destroy; override;
{** Use TransferItems to load and store atomic values. Be careful with
floating point -- it doesn't provide a way to do single and double, yet,
because there's no way to distinguish those types. If you want to do
singles, doubles, or TDateTime, use the TransferItemsEx call instead,
which lets you specify the types of your members.
@param items An array of items to read or write. The items should be
encased in square brackets: [a,b,c]. This is Delphi's
open array syntax.
@param itemAddresses Pointers to each of the variables passed in items,
also in open array format: [@a, @b, @c].
@param direction Either iodirRead or iodirWrite, depending on
whether objects are being read or written.
@param version This will contain the version number of the object
read in. }
procedure TransferItems(
items : array of const;
itemAddresses : array of pointer;
direction : TObjIODirection;
var version : Integer); virtual;
{** TransferVarRec does the io for a single TVarRec, where that TVarRec
is the actual storage location for the value. }
procedure TransferVarRec(var item : TVarRec; direction : TObjIODirection);
{** TransferItem is used to read or write a single TVarRec-based object.
This is very useful for writing the DeCAL classes, which store DObjects
that are equivalent to TVarRec.
@param item The item to transfer.
@param itemAddress Where the item is.
@param direction Whether to read or write.}
procedure TransferItem(const item : TVarRec; itemAddress : Pointer; direction : TObjIODirection);
{** TransferItemEx is used to read or write a single TVarRec-based object,
supplying a specific type.
@param item The item to transfer.
@param itemAddress Where the item is.
@param itemType The type of the variable (ssvt constant).
@param direction Whether to read or write.}
procedure TransferItemEx(const item : TVarRec; itemAddress : Pointer; itemType : Integer; direction : TObjIODirection);
{** Transfer items to and from the stream, with type information. If you need to distinguish between different forms of floating point,
use this routine instead. itemTypes is an array of ssvt codes (see
the top of this file) that correspond to the atomic data types. You
can use ssvtNone if you want the default mechanism to handle it.
The best way to use this is to stream your singles and doubles first,
then the rest of your items. The list of itemtypes doesn't have to
be the same length as the list of items to transfer -- ssvtNone will
be assumed for the remaining items if the list is shorter. <P>
The most common use of this routine is to transfer single or double
floating point values, whose type is not handled accurately by the
array of const system Delphi provides. <P>
@param items An array of items to read or write. The items should be
encased in square brackets: [a,b,c]. This is Delphi's
open array syntax.
@param itemAddresses Pointers to each of the variables passed in items,
also in open array format: [@a, @b, @c].
@param itemTypes The itemTypes open array exists so that atomic types
not handled by Delphi's open array system can be
used. Each variable in the items parameter should
have, in itemTypes, a corresponding type indicator.
Note that this is usually only necessary of SINGLE
or DOUBLE values are going to be written. <P>
Here are the possible values:
<UL>
<LI> ssvtNone </LI>
<LI> ssvtSingle </LI>
<LI> ssvtDouble </LI>
<LI> ssvtInteger </LI>
<LI> ssvtBoolean </LI>
<LI> ssvtChar </LI>
<LI> ssvtExtended </LI>
<LI> ssvtString </LI>
<LI> ssvtPointer </LI>
<LI> ssvtPChar </LI>
<LI> ssvtObject </LI>
<LI> ssvtClass </LI>
<LI> ssvtWideChar </LI>
<LI> ssvtPWideChar </LI>
<LI> ssvtAnsiString </LI>
<LI> ssvtCurrency </LI>
<LI> ssvtVariant </LI>
<LI> ssvtInterface </LI>
<LI> ssvtWideString </LI>
<LI> ssvtInt64 </LI>
</UL>
@param direction Either iodirRead or iodirWrite, depending on
whether objects are being read or written.
@param version This will contain the version number of the object
read in. }
procedure TransferItemsEx(
items : array of const;
itemAddresses : array of pointer;
itemTypes : array of Integer;
direction : TObjIODirection;
var version : Integer); virtual;
{** Use TransferArrays to load and store multiple arrays of atomic values.
@param firstItem An open array of the first item of each array.
@param firstItemAddresses An open array of the addresses of the first
item in each array.
@param counts An open array containing a count for each array to be
written.
@param direction iodirRead or iodirWrite, depending on whether read
or write is desired.}
procedure TransferArrays(
firstItem : array of const;
firstItemAddresses : array of Pointer;
counts : array of Integer;
direction : TObjIODirection); virtual;
{** Use TransferArrays to load and store multiple arrays of atomic values,
with additional type information.
@param firstItem An open array of the first item of each array.
@param firstItemAddresses An open array of the addresses of the first
item in each array.
@param itemTypes An open array of ssvt constants indicating the type
of each array.
@param counts An open array containing a count for each array to be
written.
@param direction iodirRead or iodirWrite, depending on whether read
or write is desired.}
procedure TransferArraysEx(
firstItem : array of const;
firstItemAddresses : array of Pointer;
itemTypes : array of Integer;
counts : array of Integer;
direction : TObjIODirection); virtual;
{** Use TransferBlocks to load and store blocks of memory in an object stream.
@param addresses An open array of pointers to the blocks.
@param sizes An open array of the sizes of each block.
@param direction iodirRead or iodirWrite, depending on whether read
or write is desired.}
procedure TransferBlocks(
addresses : array of pointer;
sizes : array of integer;
direction : TObjIODirection); virtual;
{** Write an object to the stream. The object's class must have been
registered. IO routines for subclasses will automatically be called.
@param obj The object to write.}
procedure WriteObject(obj : TObject); virtual;
{** Read an object from the stream. The object's class must have been
registered. IO routines for subclasses will automatically be called.}
function ReadObject : TObject; virtual;
{** Write an object to the stream using the given io procedure.
@param obj The object to write.
@param io The io procedure to use.
@param version The version number that will be passed to the io procedure.
@param callSuperClassIO Indicates whether the object's superclass io procedures
will be called after the specified io procedure is called. }
procedure WriteObjectWith(obj : TObject; io : TObjIO; version : Integer); virtual;
{** Read an object from the stream using the given io procedure.
@param obj An already constructed empty object to read values into.
@param io The io procedure to use for this read or write only.
@param version The version number to pass to the io procedure.
@param callSuperClassIO If true, the object's superclass io procedure will be called
after the specified io procedure is called.}
function ReadObjectWith(obj : TObject; io : TObjIO; var version : Integer) : TObject; virtual;
{** Flush the list of objects written/read. This is useful if you are
resetting the stream to read it again. }
procedure FlushObjectList; virtual;
protected
class function GetRegistrationFor(cls : TClass) : TStreamRegistration;
procedure DoHeaderTransfer; virtual;
procedure ReadFixed(var buffer; count : LongInt);
end;
{** Stream registration objects keep information about each class that is
streamable. They store an IO procedure, class information, and version
information. This is an internal class and should not be used by calling
units. *}
TStreamRegistration = class
targetClass : TClass;
io : TObjIO;
latestVersion : Integer;
init : TInitializer;
constructor Create(tc : TClass; i : TObjIO; latest : Integer; _init : TInitializer);
end;
{** The buffered input stream adapter can accelerate the use of underlying
streams. Delphi's TFileStream performs no buffering, so its performance
when reading and writing large numbers of small objects is not very good.
Wrapping a TFileStream with a TBufferedStream results in much better
performance. Note that you can only read from these streams. Writing will
throw an exception. }
TBufferedInputStream = class(TStreamAdapter)
public
constructor Create(targetStream : TStream; bufSize : Integer; Owned : Boolean);
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
protected
FStream : TStream;
FWindow : TMemoryStream;
FBufferSize : Integer;
FWindowPosition : Integer;
FOwned : Boolean;
procedure SetSize(NewSize: Longint); override;
procedure SetBufferSize(newSize : Integer); virtual;
private
procedure _SetSize(NewSize : LongInt);
public
property BufferSize : Integer read FBufferSize write SetBufferSize;
end;
{** The buffered output stream adapter can accelerate the use of underlying
streams. Note that you can only write sequentially to this stream; reading
or seeking will throw an exception. }
TBufferedOutputStream = class(TStreamAdapter)
public
constructor Create(targetStream : TStream; bufSize : Integer; Owned : Boolean);
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(Offset: Longint; Origin: Word): Longint; override;
protected
FStream : TStream;
FWindow : TMemoryStream;
FBufferSize : Integer;
FOwned : Boolean;
procedure SetSize(NewSize: Longint); override;
procedure SetBufferSize(newSize : Integer); virtual;
private
procedure _SetSize(NewSize : LongInt);
procedure Flush;
public
property BufferSize : Integer read FBufferSize write SetBufferSize;
end;
{** TObjList is a subclass of TList that contains a list of objects.
It provides an extra property, Objects, that gives access to the list. }
TObjList = class(TList)
protected
FOwns : Boolean;
function GetObject(idx : Integer) : TObject;
procedure SetObject(idx : Integer; obj : Tobject);
public
destructor Destroy; override;
{** Clear the list, freeing all the objects. }
procedure FreeAll;
{** Get at a list element, typecase to a TObject. This property is also
set up as the default property, so all you need to do is use objectList[x]
to get at an object. }
property Objects[idx : Integer] : TObject read GetObject write SetObject; default;
{** If the Owns property is true, the TObjList will free the objects it
contains when it is destroyed. }
property Owns : Boolean read FOwns write FOwns;
end;
implementation
uses Windows,
System.Internal.StrHlpr,
System.Math;
const
// How big should the buffered streams used by the TObjStream helpers be?
FileBuffering = 4096;
var
registry : TList = nil;
defaultsRegistered : Boolean = false;
constructor TStreamRegistration.Create(tc : TClass; i : TObjIO; latest : Integer; _init : TInitializer);
begin
targetClass := tc;
io := i;
latestVersion := latest;
init := _init;
end;
class procedure TObjStream.RegisterClass(cls : TClass; _writer : TObjIO; latest : Integer);
begin
RegisterClassEx(cls, _writer, latest, nil);
end;
class procedure TObjStream.RegisterClassEx(cls : TClass; _writer : TObjIO; latest : Integer; init : TInitializer);
begin
if registry = nil then
registry := TList.Create;
registry.Add(TStreamRegistration.Create(cls, _writer, latest, init));
end;
procedure IOStringList(obj : TObject; stream : TObjStream; direction : TObjIODirection; version : Integer; var callSuper : Boolean);
var len : Integer;
s : String;
begin
with obj as TStringList do
begin
case version of
1:begin
if direction = iodirWrite then
begin
s := Text;
len := Length(s);
stream.write(len, sizeof(len));
if len > 0 then
stream.write(s[1], len);
end
else
begin
stream.read(len, sizeof(len));
if len > 0 then
begin
SetLength(s, len);
stream.read(s[1], len);
end
else
s := '';
Text := s;
end;
end;
end;
end;
end;
procedure IOObjList(obj : TObject; stream : TObjStream; direction : TObjIODirection; version : Integer; var callSuper : Boolean);
var len : Integer;
ol : TObjList;
i : Integer;
begin
ol := obj as TObjList;
case version of
1: begin
stream.transferItems([ol.FOwns], [@ol.fowns], direction, version);
if direction = iodirWrite then
begin
len := ol.Count;
stream.write(len, sizeof(len));
if len > 0 then
begin
for i := 0 to len - 1 do
begin
stream.WriteObject(ol[i]);
end;
end;
end
else
begin
// invoke constructor to set up default values
ol.Create;
stream.read(len, sizeof(len));
if len > 0 then
begin
ol.Capacity := len;
for i := 0 to len - 1 do
ol.Add(stream.readObject);
end;
end;
end;
end;
end;
class procedure TObjStream.RegisterDefaultClasses;
begin
if not defaultsRegistered then
begin
defaultsRegistered := true;
RegisterClass(TStringList, IOStringList, 1);
RegisterClass(TObjList, IOObjList, 1);
end;
end;
class function TObjStream.GetRegistrationFor(cls : TClass) : TStreamRegistration;
var idx : Integer;
reg : TStreamRegistration;
begin
result := nil;
for idx := 0 to registry.count - 1 do
begin
reg := TStreamRegistration(registry[idx]);
if reg.targetClass = cls then
begin
result := reg;
break;
end;
end;
end;
procedure TObjStream.FlushObjectList;
begin
FObjList.Clear;
end;
procedure TObjStream.WriteObjectWith(obj : TObject; io : TObjIO; version : Integer);
var cls : TClass;
reg : TStreamRegistration;
first : Boolean;
nm : ShortString;
callSuper : Boolean;
begin
first := true;
cls := obj.ClassType;
repeat
if first then
begin
// need to write out class identifier tag here.
nm := cls.classname;
write(nm[0], 1);
write(nm[1], Ord(nm[0]));
callSuper := true;
// invoke the passed-in io routine
io(obj, self, ioDirWrite, version, callSuper);
end
else
begin
reg := GetRegistrationFor(cls);
if reg <> nil then
begin
write(reg.latestVersion, sizeof(integer));
callSuper := true;
if assigned(reg.io) then
reg.io(obj, self, iodirWrite, reg.latestVersion, callSuper);
end;
end;
first := false;
// walk up class tree;
cls := cls.ClassParent;
until (not callSuper) or (cls = nil);
end;
function TObjStream.ReadObjectWith(obj : TObject; io : TObjIO; var version : Integer) : TObject;
var cls : TClass;
reg : TStreamRegistration;
callSuper : Boolean;
begin
callSuper := true;
io(obj, self, iodirRead, version, callSuper);
if callSuper then
begin
cls := obj.ClassParent;
while (cls <> nil) and (callSuper) do
begin
reg := GetRegistrationFor(cls);
if reg <> nil then
begin
read(version, sizeof(version));
if assigned(reg.io) then
reg.io(obj, self, iodirRead, version, callSuper);
end;
cls := cls.ClassParent;
end;
end;
result := nil;
end;
procedure TObjStream.WriteObject(obj : TObject);
var cls : TClass;
reg : TStreamRegistration;
first : Boolean;
nm : ShortString;
position : Integer;
max : Integer;
zero : Char;
callSuper : Boolean;
begin
if obj = nil then
begin
if osoGraph in FOptions then
begin
max := MaxInt;
write(max, sizeof(max));
end
else
begin
zero := chr(0);
write(zero, 1);
end;
exit;
end;
if osoGraph in FOptions then
begin
// we may not be writing this object.
position := FObjList.IndexOf(obj);
write(position, sizeof(position));
if position >= 0 then
exit // this object has already been written
else
FObjList.Add(obj);
end;
first := true;
cls := obj.ClassType;
repeat
reg := GetRegistrationFor(cls);
if reg <> nil then
begin
if first then
begin
// need to write out class identifier tag here.
nm := cls.classname;
write(nm[0], 1);
write(nm[1], Ord(nm[0]));
end;
write(reg.latestVersion, sizeof(integer));
callSuper := true;
if assigned(reg.io) then
reg.io(obj, self, iodirWrite, reg.latestVersion, callSuper);
end
else if first then
raise TObjStreamException.Create(Format('Trying to write unregistered class (%s).', [obj.classname]));
first := false;
// walk up class tree;
cls := cls.ClassParent;
until (cls = nil) or (not callSuper);
end;
function TObjStream.ReadObject : TObject;
var nm : ShortString;
i : Integer;
reg : TStreamRegistration;
version : Integer;
cls : TClass;
objid : Integer;
found, callSuper : Boolean;
begin
DoHeaderTransfer;
if osoGraph in FOptions then
begin
readFixed(objid, sizeof(Integer));
// check for null pointer.
if objid = MaxInt then
begin
result := nil;
exit;
end;
if (objid >= 0) and (objid < FObjList.Count) then
begin
result := TObject(FObjList[objid]);
exit;
end;
end;
result := nil;
readFixed(nm[0], 1);
// check for null pointer case
if nm[0] = chr(0) then
exit;
found := false;
readFixed(nm[1], Ord(nm[0]));
i := 0;
while i < registry.Count do
begin
reg := TStreamRegistration(registry[i]);
if reg.targetClass.ClassName = nm then
begin
found := true;
result := reg.targetClass.NewInstance;
if osoGraph in FOptions then
FObjList.Add(result);
readFixed(version, sizeof(version));
callSuper := true;
if assigned(FObjCreation) then
FObjCreation(result, self, version);
if assigned(reg.io) then
reg.io(result, self, iodirRead, version, callSuper);