-
Notifications
You must be signed in to change notification settings - Fork 34
/
AioImpl.pas
2411 lines (2162 loc) · 61.1 KB
/
AioImpl.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
// **************************************************************************************************
// Delphi Aio Library.
// Unit AioImpl
// https://github.com/Purik/AIO
// The contents of this file are subject to the Apache License 2.0 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
//
// The Original Code is AioImpl.pas.
//
// Contributor(s):
// Pavel Minenkov
// Purik
// https://github.com/Purik
//
// The Initial Developer of the Original Code is Pavel Minenkov [Purik].
// All Rights Reserved.
//
// **************************************************************************************************
unit AioImpl;
interface
uses Classes, Greenlets, Gevent, Hub, SysUtils, sock, RegularExpressions, Aio,
SyncObjs, GInterfaces, IdGlobal,
{$IFDEF MSWINDOWS}
Winapi.Windows
{$ELSE}
{$ENDIF};
type
TIOHandler = class(TInterfacedObject, IIoHandler)
private
FLock: TCriticalSection;
FAlloc: Pointer;
FCapacity: LongWord;
FSize: LongWord;
FEmitter: IGevent;
FHandle: THandle;
FWaitHandle: THandle;
FErrorCode: NativeUInt;
public
constructor Create;
destructor Destroy; override;
property Handle: THandle read FHandle write FHandle;
property WaitHandle: THandle read FWaitHandle write FWaitHandle;
property ErrorCode: NativeUInt read FErrorCode write FErrorCode;
procedure Lock;
procedure Unlock;
function Emitter: IGevent;
function ReallocBuf(Size: LongWord): Pointer;
function GetBuf: Pointer;
function GetBufSize: LongWord;
end;
TAioProvider = class(TInterfacedObject, IAioProvider)
type
EIOError = class(Exception);
AEOF = class(EAbort);
strict private
type
TIO = record
NumOfBytes: LongWord;
LastError: Integer;
OpCode: TIOOperation;
end;
const
DEF_READ_SZ = 1024;
DEF_EOL = CRLF;
var
FOnAfterRead: TGevent;
FOnAfterWrite: TGevent;
FReadIO: TIO;
FWriteIO: TIO;
FPosition: Int64;
FEOL: string;
FEncoding: TEncoding;
FEOLs: array of string;
class procedure Cb(Fd: THandle; const Op: TIOOperation; Data: Pointer;
ErrorCode: Integer; NumOfBytes: LongWord); static;
protected
FAsStream: TStream;
FAsFile: TStream;
FAcive: Boolean;
FRegEx: TRegEx;
FInternalBuf: TBytes;
FIgnoreInternalBuf: Boolean;
FEncCopied: Boolean;
FUseDgramApi: Boolean;
function GetDgramReadAddress: TAnyAddress; dynamic; abstract;
function GetDgramWriteAddress: TAnyAddress; dynamic; abstract;
function GetFd: THandle; dynamic; abstract;
function GetDriverRcvBufSize: LongWord; dynamic;
function GetDriverSndBufSize: LongWord; dynamic;
function ReadPending(Buf: Pointer; Size: LongWord): LongWord; dynamic;
function WritePending(Buf: Pointer; Size: LongWord): LongWord; dynamic;
function ReadFull(Buf: Pointer; Size: LongWord): LongWord;
function WriteFull(Buf: Pointer; Size: LongWord): LongWord;
procedure OperationComplete(const Op: TIOOperation); dynamic;
function OnStreamRead(var Buffer; Count: Longint): LongInt;
function OnStreamWrite(const Buffer; Count: Longint): LongInt;
procedure SetPosition(const Value: Int64); virtual;
function GetPosition: Int64; virtual;
property Position: Int64 read GetPosition write SetPosition;
property OnAfterRead: TGevent read FOnAfterRead;
property OnAfterWrite: TGevent read FOnAfterWrite;
procedure OperationAborted; dynamic;
procedure ReadLnYielded;
procedure ReadLnYieldedEOLs;
procedure ReadRegExYielded(const A: array of const);
function _ReadString(Enc: TEncoding; out Buf: string; const EOLs: array of string): Boolean;
procedure DoError(ErrorCode: LongWord; const Operation: TIOOperation); dynamic;
public
constructor Create;
destructor Destroy; override;
// io operations
// if Size > 0 -> Will return control when all bytes will be transmitted
// if Size < 0 -> Will return control when the operation is completed partially
// if Size = 0 -> Will return data buffer length of driver
function Read(Buf: Pointer; Size: Integer): LongWord; dynamic;
function Write(Buf: Pointer; Size: Integer): LongWord; dynamic;
// stream interfaces
function AsStream: TStream;
function AsFile(Size: LongWord): TStream;
// extended interfaces
// strings
function GetEncoding: TEncoding;
procedure SetEncoding(Value: TEncoding);
function GetEOL: string; // end of line ex: LF or CRLF
procedure SetEOL(const Value: string);
function ReadLn: string; overload; // raise AEOF in end of stream
function ReadLn(out S: string): Boolean; overload;
function ReadLns: TGenerator<string>; overload;
function ReadLns(const EOLs: array of string): TGenerator<string>; overload;
function ReadRegEx(const RegEx: TRegEx; out S: string): Boolean; overload;
function ReadRegEx(const Pattern: string; out S: string): Boolean; overload;
function ReadRegEx(const RegEx: TRegEx): TGenerator<string>; overload;
function ReadRegEx(const Pattern: string): TGenerator<string>; overload;
function ReadString(Enc: TEncoding; out Buf: string; const EOL: string = CRLF): Boolean;
procedure WriteLn(const S: string); overload;
procedure WriteLn(const S: array of string); overload;
function WriteString(Enc: TEncoding; const Buf: string; const EOL: string = CRLF): Boolean;
// others
function ReadBytes(out Buf: TBytes): Boolean; overload;
function ReadBytes(out Buf: TIdBytes): Boolean; overload;
function ReadByte(out Buf: Byte): Boolean;
function ReadInteger(out Buf: Integer): Boolean;
function ReadSmallInt(out Buf: SmallInt): Boolean;
function ReadSingle(out Buf: Single): Boolean;
function ReadDouble(out Buf: Double): Boolean;
function WriteBytes(const Bytes: TBytes): Boolean;
function WriteByte(const Value: Byte): Boolean;
function WriteInteger(const Value: Integer): Boolean;
function WriteSmallInt(const Value: SmallInt): Boolean;
function WriteSingle(const Value: Single): Boolean;
function WriteDouble(const Value: Double): Boolean;
end;
TAioFile = class(TAioProvider, IAioFile)
strict private
FFileName: string;
FFd: THandle;
FFileSize: Int64;
FMode: Word;
FSeekable: Boolean;
protected
procedure SetPosition(const Value: Int64); override;
function GetFd: THandle; override;
function ReadPending(Buf: Pointer; Size: LongWord): LongWord; override;
function WritePending(Buf: Pointer; Size: LongWord): LongWord; override;
public
constructor Create(const FileName: string; Mode: Word);
destructor Destroy; override;
property Position;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
end;
TAioSocket = class(TAioProvider)
type
ESockError = class(Exception);
EAddressResolution = class(Exception);
private
FSocket: TSocket;
FEvent: TEvent;
FOnEvent: TGevent;
FAcceptEvent: TEvent;
FOnDisconnect: TGevent;
FOnAccept: TGevent;
FBinded: Boolean;
{$IFDEF MSWINDOWS}
FOverlap: TOverlapped;
{$ENDIF}
procedure RaiseError(ErrorCode: Integer);
protected
FLocalSin: TVarSin;
FRemoteSin: TVarSin;
function GetErrorDescr(ErrorCode: Integer): string;
procedure GetLocalSin;
procedure GetRemoteSin;
procedure CreateInternal;
procedure SetSin(var Sin: TVarSin; IP, Port: string);
function GetDriverRcvBufSize: LongWord; override;
function GetAddressFamily: Integer; dynamic;
function GetType: Integer; dynamic;
function GetProtocolFamily: Integer; dynamic;
property OnAccept: TGevent read FOnAccept;
procedure DoAccept(AcceptSock: TAioSocket);
procedure CheckError(RetCode: Integer);
function GetRemoteAddress: string;
function GetRemotePort: string;
function GetLocalAddress: string;
function GetLocalPort: string;
property OnEvent: TGevent read FOnEvent;
procedure OperationAborted; override;
function GetSinAddress(Sin: TVarSin): string;
function GetSinPort(Sin: TVarSin): Integer;
function GetFd: THandle; override;
procedure Bind(const Address: string; const Port: string);
procedure Listen;
function Connect(const Address: string; const Port: string;
Timeout: LongWord): Boolean;
procedure Disconnect;
procedure DoError(ErrorCode: LongWord; const Operation: TIOOperation); override;
public
constructor Create;
destructor Destroy; override;
function Write(Buf: Pointer; Size: Integer): LongWord; override;
end;
TAioTCPSocket = class(TAioSocket, IAioTcpSocket)
strict private
function GetOnConnect: TGevent;
protected
function GetAddressFamily: Integer; override;
function GetType: Integer; override;
function GetProtocolFamily: Integer; override;
public
procedure Bind(const Address: string; Port: Integer);
procedure Listen;
function Accept: IAioTcpSocket;
function Connect(const Address: string; Port: Integer; Timeout: LongWord): Boolean;
procedure Disconnect;
function OnConnect: TGevent;
function OnDisconnect: TGevent;
function LocalAddress: TAddress;
function RemoteAddress: TAddress;
end;
TAioUDPSocket = class(TAioSocket, IAioUdpSocket)
protected
function GetAddressFamily: Integer; override;
function GetType: Integer; override;
function GetProtocolFamily: Integer; override;
function GetDgramReadAddress: TAnyAddress; override;
function GetDgramWriteAddress: TAnyAddress; override;
public
constructor Create;
procedure Bind(const Address: string; Port: Integer);
function GetRemoteAddress: TAddress;
procedure SetRemoteAddress(const Value: TAddress);
end;
TAioComPort = class(TAioProvider, IAioComPort)
strict private
FFileName: string;
FFd: THandle;
FStateEvent: SyncObjs.TEvent;
FOnState: TGevent;
FEventMask: LongWord;
{$IFDEF MSWINDOWS}
FOverlap: TOverlapped;
{$ENDIF}
function GetEventMask: TEventMask;
protected
function GetFd: THandle; override;
public
constructor Create(const FileName: string);
destructor Destroy; override;
function EventMask: TEventMask;
function OnState: TGevent;
end;
TAioNamedPipe = class(TAioProvider, IAioNamedPipe)
strict private
FPipeName: string;
FFd: THandle;
FEvent: TEvent;
FOnConnect: TGevent;
FOvlp: TOverlapped;
FOpened: Boolean;
protected
function GetFd: THandle; override;
function GetDriverRcvBufSize: LongWord; override;
public
constructor Create(const Name: string);
destructor Destroy; override;
// server-side
procedure MakeServer(BufSize: Longword=4096);
function WaitConnection(Timeout: LongWord = INFINITE): Boolean;
// client-side
procedure Open;
// not remove data from read buffer
function Peek: TBytes;
end;
TAioConsoleApplication = class(TInterfacedObject, IAioConsoleApplication)
strict private
const
DEF_EOL = {$IFDEF MSWINDOWS}CRLF{$ELSE}CR{$ENDIF};
type
TInOut = record
Pipe1: TAioNamedPipe;
Pipe2: TAioNamedPipe;
constructor Create(const Name: string);
procedure Destroy;
procedure RefreshEncodings(Enc: TEncoding; const EOL: string);
function ParentSide: TAioNamedPipe;
function ChildSide: TAioNamedPipe;
class procedure DelayedOpen(const Pipe: TAioNamedPipe;
const Timeout: LongWord); static;
end;
var
FHandle: THandle;
FProcessId: LongWord;
FInput: TInOut;
FOutput: TInOut;
FError: TInOut;
FWorkDir: string;
FOnTerminate: TGevent;
FPath: string;
FGuid: string;
FEncoding: TEncoding;
FEncCopied: Boolean;
FEOL: string;
function TryCreate(const AbsPath: string; const Args: array of const): Boolean;
procedure AllocPipes;
procedure FinalPipes;
public
constructor Create(const Cmd: string; const Args: array of const;
const WorkDir: string = '');
destructor Destroy; override;
// encodings
function GetEncoding: TEncoding;
procedure SetEncoding(Value: TEncoding);
function GetEOL: string;
procedure SetEOL(const Value: string);
// in-out
function StdIn: IAioProvider;
function StdOut: IAioProvider;
function StdError: IAioProvider;
// process-specific
function ProcessId: LongWord;
function OnTerminate: TGevent;
function GetExitCode(const Block: Boolean = True): Integer;
procedure Terminate(ExitCode: Integer = 0);
end;
TAioConsole = class(TInterfacedObject, IAioConsole)
strict private
type
TStdHandle = class(TAioProvider)
type
THandleType = (htInput, htOutput, htError);
strict private
FHandle: THandle;
class procedure CbRead(Parameter: Pointer; const TimerOrWaitFired: Boolean); stdcall; static;
class procedure CbWrite(Parameter: Pointer; const TimerOrWaitFired: Boolean); stdcall; static;
protected
function GetFd: THandle; override;
function ReadPending(Buf: Pointer; Size: LongWord): LongWord; override;
function WritePending(Buf: Pointer; Size: LongWord): LongWord; override;
public
constructor Create(const Typ: THandleType);
destructor Destroy; override;
end;
var
FStdIn: TStdHandle;
FStdOut: TStdHandle;
FStdError: TStdHandle;
public
constructor Create;
destructor Destroy; override;
function StdIn: IAioProvider;
function StdOut: IAioProvider;
function StdError: IAioProvider;
end;
TAioSoundCard = class(TAioProvider, IAioSoundCard)
strict private
const
BUF_COUNT = 4;
type
TBuffersState = record
CurBufIndex: Integer;
ReadyCount: Integer;
QueuedCount: Integer;
ReadyBytesLen: Integer;
end;
var
FReadEvent: TEvent;
FWriteEvent: TEvent;
FInDev: THandle;
FOutDev: THandle;
FFormat: Pointer;
FRecBufs: array[0..BUF_COUNT-1] of Pointer;
FRecBufState: TBuffersState;
FPlayBufs: array[0..BUF_COUNT-1] of Pointer;
FPlayBufsState: TBuffersState;
FOnRead: TGevent;
FOnWrite: TGevent;
FRecStarted: Boolean;
procedure UpdateRecBuffersState;
procedure UpdatePlayBuffersState;
protected
function GetFd: THandle; override;
function ReadPending(Buf: Pointer; Size: LongWord): LongWord; override;
function WritePending(Buf: Pointer; Size: LongWord): LongWord; override;
public
constructor Create(SampPerFreq: LongWord; Channels: LongWord = 1; BitsPerSamp: LongWord = 16);
destructor Destroy; override;
end;
implementation
uses Math, System.WideStrUtils, MMSystem;
const
END_OF_FILE_ERROR_CODE = {$IFDEF MSWINDOWS} ERROR_HANDLE_EOF {$ELSE} 111 {$ENDIF};
type
TStreamProxy = class(TStream)
type
TOnRead = function(var Buffer; Count: Longint): LongInt of object;
TOnWrite = function(const Buffer; Count: Longint): LongInt of object;
TOnSeek = function(const Offset: Int64; Origin: TSeekOrigin): Int64 of object;
strict private
FProv: TAioProvider;
FOnRead: TOnRead;
FOnWrite: TOnWrite;
FOnSeek: TOnSeek;
protected
function GetSize: Int64; override;
public
constructor Create(Prov: TAioProvider);
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
property OnSeek: TOnSeek read FOnSeek write FOnSeek;
end;
{$IFDEF MSWINDOWS}
var
WsaDataOnce: TWSADATA;
{$I iocpwin.inc}
{$ENDIF}
{ TAioProvider }
function TAioProvider.AsFile(Size: LongWord): TStream;
begin
FAsFile.Size := Size;
Result := FAsFile;
end;
function TAioProvider.AsStream: TStream;
begin
Result := FAsStream;
end;
class procedure TAioProvider.Cb(Fd: THandle; const Op: TIOOperation;
Data: Pointer; ErrorCode: Integer; NumOfBytes: LongWord);
var
Me: TAioProvider;
begin
Me := TAioProvider(Data);
case Op of
ioRead: begin
Me.FReadIO.NumOfBytes := NumOfBytes;
Me.FReadIO.LastError := ErrorCode;
Me.FReadIO.OpCode := Op;
end;
ioWrite: begin
Me.FWriteIO.NumOfBytes := NumOfBytes;
Me.FWriteIO.LastError := ErrorCode;
Me.FWriteIO.OpCode := Op;
end;
end;
Me.OperationComplete(Op);
end;
constructor TAioProvider.Create;
begin
inherited;
FPosition := -1;
FOnAfterRead := TGevent.Create;
FOnAfterWrite := TGevent.Create;
FAsStream := TStreamProxy.Create(Self);
FAsFile := TStreamProxy.Create(Self);
FEOL := DEF_EOL;
SetEncoding(TEncoding.Default);
end;
destructor TAioProvider.Destroy;
begin
FOnAfterRead.Free;
FOnAfterWrite.Free;
FAsStream.Free;
FAsFile.Free;
if FEncCopied then
FEncoding.Free;
inherited;
end;
procedure TAioProvider.DoError(ErrorCode: LongWord;
const Operation: TIOOperation);
begin
//
end;
function TAioProvider.GetDriverRcvBufSize: LongWord;
begin
if not FIgnoreInternalBuf then
Result := Length(FInternalBuf)
else
Result := 0
end;
function TAioProvider.GetDriverSndBufSize: LongWord;
begin
Result := 0;
end;
function TAioProvider.GetEncoding: TEncoding;
begin
Result := FEncoding
end;
function TAioProvider.GetEOL: string;
begin
Result := FEOL
end;
function TAioProvider.GetPosition: Int64;
begin
Result := FPosition
end;
function TAioProvider.OnStreamRead(var Buffer; Count: Integer): LongInt;
begin
Result := Read(@Buffer, Count);
end;
function TAioProvider.OnStreamWrite(const Buffer; Count: Integer): LongInt;
begin
Result := Write(@Buffer, Count);
end;
procedure TAioProvider.OperationComplete(const Op: TIOOperation);
begin
case Op of
ioRead:
FOnAfterRead.SetEvent(False);
ioWrite:
FOnAfterWrite.SetEvent(True);
end;
end;
procedure TAioProvider.OperationAborted;
begin
//
end;
function TAioProvider.Read(Buf: Pointer; Size: Integer): LongWord;
begin
if Size > 0 then
Result := ReadFull(Buf, Size)
else if Size < 0 then
Result := ReadPending(Buf, -Size)
else
Result := GetDriverRcvBufSize;
end;
function TAioProvider.ReadByte(out Buf: Byte): Boolean;
begin
Result := Read(@Buf, SizeOf(Byte)) = SizeOf(Byte);
end;
function TAioProvider.ReadBytes(out Buf: TIdBytes): Boolean;
var
TmpBuf: TBytes;
begin
Result := ReadBytes(TmpBuf);
if Result then begin
SetLength(Buf, Length(TmpBuf));
Move(Pointer(TmpBuf)^, Pointer(Buf)^, Length(Buf));
end;
end;
function TAioProvider.ReadBytes(out Buf: TBytes): Boolean;
var
Readed: LongWord;
Tmp: TBytes;
ReadSz: Integer;
begin
Result := True;
ReadSz := Read(nil, 0);
if ReadSz = 0 then
ReadSz := DEF_READ_SZ;
SetLength(Tmp, ReadSz);
Readed := Read(@Tmp[0], -ReadSz);
if Readed = 0 then
Exit(False);
SetLength(Tmp, Readed);
Buf := Tmp;
end;
function TAioProvider.ReadDouble(out Buf: Double): Boolean;
begin
Result := Read(@Buf, SizeOf(Double)) = SizeOf(Double);
end;
function TAioProvider.ReadFull(Buf: Pointer; Size: LongWord): LongWord;
var
AccumSz, ReadedSz: LongWord;
Offset: PByte;
begin
AccumSz := 0;
Offset := Buf;
while AccumSz < Size do begin
ReadedSz := ReadPending(Offset, Size - AccumSz);
if ReadedSz = 0 then
Break;
Inc(AccumSz, ReadedSz);
Inc(Offset, ReadedSz);
end;
Result := AccumSz;
end;
function TAioProvider.ReadInteger(out Buf: Integer): Boolean;
begin
Result := Read(@Buf, SizeOf(Integer)) = SizeOf(Integer)
end;
function TAioProvider.ReadLn: string;
begin
if not ReadString(FEncoding, Result, FEOL) then
raise AEOF.Create('EOF');
end;
function TAioProvider.ReadLn(out S: string): Boolean;
begin
Result := ReadString(FEncoding, S, FEOL)
end;
function TAioProvider.ReadLns(const EOLs: array of string): TGenerator<string>;
var
I: Integer;
begin
if Length(EOLs) = 0 then
raise EArgumentException.Create('EOL collection is empty');
SetLength(FEOLs, Length(EOLs));
for I := 0 to High(EOLs) do
FEOLs[I] := EOLs[I];
Result := TGenerator<string>.Create(ReadLnYieldedEOLs)
end;
function TAioProvider.ReadLns: TGenerator<string>;
begin
Result := TGenerator<string>.Create(ReadLnYielded)
end;
procedure TAioProvider.ReadLnYielded;
var
S: string;
begin
while ReadString(FEncoding, S, FEOL) do
TGenerator<string>.Yield(S)
end;
procedure TAioProvider.ReadLnYieldedEOLs;
var
S: string;
begin
while _ReadString(FEncoding, S, FEOLs) do
TGenerator<string>.Yield(S)
end;
function TAioProvider.ReadPending(Buf: Pointer; Size: LongWord): LongWord;
var
Check: Boolean;
begin
if not FIgnoreInternalBuf and (Length(FInternalBuf) > 0) then begin
Result := Length(FInternalBuf);
Move(FInternalBuf[0], Buf^, Result);
SetLength(FInternalBuf, 0);
Exit;
end;
if not FUseDgramApi then
Check := GetCurrentHub.Read(GetFd, Buf, Size, Cb, Self, FPosition)
else
Check := GetCurrentHub.ReadFrom(GetFd, Buf, Size, GetDgramReadAddress, Cb, Self);
if not Check then begin
OperationAborted;
Exit(0);
end;
case FOnAfterRead.WaitFor of
wrSignaled: begin
case FReadIO.LastError of
0: begin
if FReadIO.NumOfBytes > 0 then
Exit(FReadIO.NumOfBytes)
else begin
OperationAborted;
Exit(0);
end;
end
else begin
SetLastError(FReadIO.LastError);
DoError(FReadIO.LastError, ioRead);
OperationAborted;
Exit(0)
end
end
end
else begin
Result := 0;
end;
end;
end;
function TAioProvider.ReadRegEx(const Pattern: string): TGenerator<string>;
begin
Result := TGenerator<string>.Create(ReadRegExYielded, [True, Pattern])
end;
function TAioProvider.ReadRegEx(const RegEx: TRegEx): TGenerator<string>;
begin
FRegEx := RegEx;
Result := TGenerator<string>.Create(ReadRegExYielded, [False])
end;
procedure TAioProvider.ReadRegExYielded(const A: array of const);
var
UsePattern: Boolean;
S: string;
RegEx: TRegEx;
begin
UsePattern := A[0].AsBoolean;
if UsePattern then
RegEx := TRegEx.Create(A[1].AsString)
else
RegEx := FRegEx;
while ReadRegEx(RegEx, S) do
TGenerator<string>.Yield(S);
end;
function TAioProvider.ReadRegEx(const Pattern: string; out S: string): Boolean;
var
RegEx: TRegEx;
begin
RegEx := TRegEx.Create(Pattern);
Result := ReadRegEx(RegEx, S)
end;
function TAioProvider.ReadRegEx(const RegEx: TRegEx; out S: string): Boolean;
var
Str: string;
B: TBytes;
Offs: Integer;
Match: TMatch;
function FindMatch: Boolean;
begin
Result := False;
if RegEx.IsMatch(Str) then begin
Match := RegEx.Match(Str);
S := Match.Value;
Offs := Match.Index + Match.Length;
Str := Str.Substring(Offs);
FInternalBuf := FEncoding.GetBytes(Str);
Exit(True)
end;
end;
begin
Result := False;
if Length(FInternalBuf) > 0 then begin
Str := FEncoding.GetString(FInternalBuf);
if FindMatch then
Exit(True);
end;
FIgnoreInternalBuf := True;
while ReadBytes(B) do begin
Offs := Length(FInternalBuf);
SetLength(FInternalBuf, Length(FInternalBuf) + Length(B));
Move(B[0], FInternalBuf[Offs], Length(B));
Str := FEncoding.GetString(FInternalBuf);
if FindMatch then
Exit(True);
end;
FIgnoreInternalBuf := False;
end;
function TAioProvider.ReadSingle(out Buf: Single): Boolean;
begin
Result := Read(@Buf, SizeOf(Single)) = SizeOf(Single)
end;
function TAioProvider.ReadSmallInt(out Buf: SmallInt): Boolean;
begin
Result := Read(@Buf, SizeOf(SmallInt)) = SizeOf(SmallInt)
end;
function TAioProvider.ReadString(Enc: TEncoding; out Buf: string;
const EOL: string): Boolean;
begin
Result := _ReadString(Enc, Buf, [EOL])
end;
procedure TAioProvider.SetEncoding(Value: TEncoding);
var
NewEnc: TEncoding;
begin
if FEncCopied then
FEncoding.Free;
NewEnc := Value.Clone;
FEncCopied := NewEnc <> Value;
FEncoding := NewEnc;
end;
procedure TAioProvider.SetEOL(const Value: string);
begin
FEOL := Value
end;
procedure TAioProvider.SetPosition(const Value: Int64);
begin
FPosition := Value;
SetLength(FInternalBuf, 0);
end;
function TAioProvider.Write(Buf: Pointer; Size: Integer): LongWord;
begin
if Size > 0 then
Result := WriteFull(Buf, Size)
else if Size < 0 then
Result := WritePending(Buf, -Size)
else
Result := GetDriverSndBufSize;
end;
function TAioProvider.WriteByte(const Value: Byte): Boolean;
begin
Result := Write(@Value, SizeOf(Byte)) = SizeOf(Byte)
end;
function TAioProvider.WriteBytes(const Bytes: TBytes): Boolean;
begin
Result := Write(@Bytes[0], Length(Bytes)) = LongWord(Length(Bytes))
end;
function TAioProvider.WriteDouble(const Value: Double): Boolean;
begin
Result := Write(@Value, SizeOf(Double)) = SizeOf(Double)
end;
function TAioProvider.WriteFull(Buf: Pointer; Size: LongWord): LongWord;
var
AccumSz, WritedSz: LongWord;
Offset: PByte;
begin
AccumSz := 0;
Offset := Buf;
while AccumSz < Size do begin
WritedSz := WritePending(Offset, Size - AccumSz);
if WritedSz = 0 then
Break;
Inc(AccumSz, WritedSz);
Inc(Offset, WritedSz);
end;
Result := AccumSz;
end;
function TAioProvider.WriteInteger(const Value: Integer): Boolean;
begin
Result := Write(@Value, SizeOf(Integer)) = SizeOf(Integer)
end;
procedure TAioProvider.WriteLn(const S: array of string);
var
I: string;
begin
for I in S do
WriteLn(I);
end;
procedure TAioProvider.WriteLn(const S: string);
begin
WriteString(FEncoding, S, FEOL)
end;
function TAioProvider.WritePending(Buf: Pointer; Size: LongWord): LongWord;
var
Check: Boolean;
begin
try
if not FUseDgramApi then
Check := GetCurrentHub.Write(GetFd, Buf, Size, Cb, Self, FPosition)
else
Check := GetCurrentHub.WriteTo(GetFd, Buf, Size, GetDgramWriteAddress, Cb, Self);
if not Check then begin
OperationAborted;
Exit(0);
end;
case FOnAfterWrite.WaitFor of
wrSignaled: begin
case FWriteIO.LastError of
0: begin
if FWriteIO.NumOfBytes > 0 then
Exit(FWriteIO.NumOfBytes)
else begin
OperationAborted;
Exit(0);
end;
end
else begin
SetLastError(FWriteIO.LastError);
DoError(FWriteIO.LastError, ioWrite);
OperationAborted;
Exit(0)
end;
end
end
else begin
Result := 0;
end;
end;
except
on E: Exception do begin
raise Exception(AcquireExceptionObject)
end;
end;
end;
function TAioProvider.WriteSingle(const Value: Single): Boolean;
begin
Result := Write(@Value, SizeOf(Single)) = SizeOf(Single)
end;
function TAioProvider.WriteSmallInt(const Value: SmallInt): Boolean;
begin
Result := Write(@Value, SizeOf(SmallInt)) = SizeOf(SmallInt)
end;
function TAioProvider.WriteString(Enc: TEncoding; const Buf: string;
const EOL: string): Boolean;
begin
Result := WriteBytes(Enc.GetBytes(Buf + EOL))
end;
function TAioProvider._ReadString(Enc: TEncoding; out Buf: string;
const EOLs: array of string): Boolean;
var
S: string;
B: TBytes;
Offs: Integer;
function Find: Boolean;
var
Ps: Integer;
EOL: string;
begin
Ps := -1;
for EOL in EOLs do begin
Ps := S.IndexOf(EOL);
if Ps >= 0 then
Break;
end;
Result := Ps >= 0;
if Result then begin
Buf := S.Substring(0, Ps+Length(EOL));
S := S.Substring(Length(Buf));
FInternalBuf := Enc.GetBytes(S);
Buf := Copy(Buf, 1, Length(Buf) - Length(EOL));
Exit(True);
end
end;
begin
Result := False;
if Length(FInternalBuf) > 0 then begin
S := Enc.GetString(FInternalBuf);
if Find then
Exit(True);
end;