-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdevice.d
2052 lines (1839 loc) · 37.9 KB
/
device.d
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
/*
Source,Pool,Sinkの3つを基本I/Fと置く
→Buffered-sinkは明示的に扱えるようにする?
それぞれがやり取りする要素の型は任意だが、Fileはubyteをやり取りする
(D言語的にはvoid[]でもいいかも→Rangeを考えるとやりたくない)
基本的なFilter
・Encodedはubyteを任意型にcastする機能を提供する
・Bufferedはバッファリングを行う
filter chainのサポート
Bufferedの例:
(1) 構築済みのdeviceをwrapする
auto f = File("test.txt", "r");
auto sf = sinked(f);
auto bf = bufferd(sf, 2048);
(2) 静的に決定したfilterを構築する
alias Buffered!Sinked BufferedSink;
auto bf = BufferedSink!File("test.txt", "r", 2048)
*/
module xtk.device;
import std.array, std.algorithm, std.range, std.traits;
import std.exception;
import std.stdio;
version(Windows) import xtk.windows;
import xtk.format : format;
import xtk.workaround;
debug = Workarounds;
debug (Workarounds)
{
debug = Issue5661; // replace of std.algorithm.move
debug = Issue5663; // replace of std.array.Appender.put
debug (Issue5661) alias issue5661fix_move move;
debug (Issue5663) alias issue5663fix_Appender Appender;
}
import xtk.meta : isTemplate;
/**
Returns $(D true) if $(D_PARAM D) is a $(I source). A Source must define the
primitive $(D pull).
*/
template isSource(D)
{
enum isSource = __traits(hasMember, D, "pull");
}
///ditto
template isSource(D, E)
{
enum isSource = is(typeof({
D d;
E[] buf;
while (d.pull(buf)){}
}()));
}
/**
In definition, initial state of pool has 0 length $(D available).$(BR)
You can assume that pool is not $(D fetch)-ed yet.$(BR)
定義では、poolの初期状態は長さ0の$(D available)を持つ。$(BR)
これはpoolがまだ一度も$(D fetch)されたことがないと見なすことができる。$(BR)
*/
template isPool(D)
{
enum isPool = is(typeof({
D d;
while (d.fetch())
{
auto buf = d.available;
size_t n;
d.consume(n);
}
}()));
}
/**
Returns $(D true) if $(D_PARAM D) is a $(I sink). A Source must define the
primitive $(D push).
*/
template isSink(D)
{
enum isSink = __traits(hasMember, D, "push");
}
///ditto
template isSink(D, E)
{
enum isSink = is(typeof({
D d;
const(E)[] buf;
do{}while (d.push(buf))
}()));
}
/**
Device supports both primitives of source and sink.
*/
template isDevice(D)
{
enum isDevice = isSource!D && isSink!D;
}
/**
Retruns element type of device.
Naming:
More good naming.
*/
template UnitType(D)
if (isSource!D || isPool!D || isSink!D)
{
static if (isSource!D)
alias Unqual!(typeof(ParameterTypeTuple!(typeof(D.init.pull))[0].init[0])) UnitType;
static if (isPool!D)
alias Unqual!(typeof(D.init.available[0])) UnitType;
static if (isSink!D)
{
alias Unqual!(typeof(ParameterTypeTuple!(typeof(D.init.push))[0].init[0])) UnitType;
}
}
// seek whence...
enum SeekPos {
Set,
Cur,
End
}
/**
Check that $(D_PARAM D) is seekable source or sink.
Seekable device supports $(D seek) primitive.
*/
template isSeekable(D)
{
enum isSeekable = is(typeof({
D d;
d.seek(0, SeekPos.Set);
}()));
}
/**
File is seekable device
*/
struct File
{
import std.utf;
import std.typecons;
private:
HANDLE hFile;
size_t* pRefCounter;
public:
/**
*/
this(HANDLE h)
{
hFile = h;
pRefCounter = new size_t();
*pRefCounter = 1;
}
this(string fname, in char[] mode = "r")
{
int share = FILE_SHARE_READ | FILE_SHARE_WRITE;
int access = void;
int createMode = void;
// fopenにはOPEN_ALWAYSに相当するModeはない?
switch (mode)
{
case "r":
access = GENERIC_READ;
createMode = OPEN_EXISTING;
break;
case "w":
access = GENERIC_WRITE;
createMode = CREATE_ALWAYS;
break;
case "a":
assert(0);
case "r+":
access = GENERIC_READ | GENERIC_WRITE;
createMode = OPEN_EXISTING;
break;
case "w+":
access = GENERIC_READ | GENERIC_WRITE;
createMode = CREATE_ALWAYS;
break;
case "a+":
assert(0);
// do not have binary mode(binary access only)
// case "rb":
// case "wb":
// case "ab":
// case "rb+": case "r+b":
// case "wb+": case "w+b":
// case "ab+": case "a+b":
}
hFile = CreateFileW(
std.utf.toUTF16z(fname), access, share, null, createMode, 0, null);
pRefCounter = new size_t();
*pRefCounter = 1;
}
this(this)
{
if (pRefCounter) ++(*pRefCounter);
}
~this()
{
if (pRefCounter)
{
if (--(*pRefCounter) == 0)
{
//delete pRefCounter; // trivial: delegate management to GC.
CloseHandle(cast(HANDLE)hFile);
}
//pRefCounter = null; // trivial: do not need
}
}
/**
Request n number of elements.
Returns:
$(UL
$(LI $(D true ) : You can request next pull.)
$(LI $(D false) : No element exists.))
*/
bool pull(ref ubyte[] buf)
{
DWORD size = void;
debug writefln("ReadFile : buf.ptr=%08X, len=%s", cast(uint)buf.ptr, len);
if (ReadFile(hFile, buf.ptr, buf.length, &size, null))
{
debug(File)
writefln("pull ok : hFile=%08X, buf.length=%s, size=%s, GetLastError()=%s",
cast(uint)hFile, buf.length, size, GetLastError());
buf = buf[0 .. size];
return (size > 0); // valid on only blocking read
}
else
{
switch (GetLastError())
{
case ERROR_BROKEN_PIPE:
return false;
default:
break;
}
//debug(File)
writefln("pull ng : hFile=%08X, size=%s, GetLastError()=%s",
cast(uint)hFile, size, GetLastError());
throw new Exception("pull(ref buf[]) error");
// // for overlapped I/O
// eof = (GetLastError() == ERROR_HANDLE_EOF);
}
}
/**
*/
bool push(ref const(ubyte)[] buf)
{
DWORD size = void;
if (WriteFile(hFile, buf.ptr, buf.length, &size, null))
{
buf = buf[size .. $];
return true; // (size == buf.length);
}
else
{
throw new Exception("push error"); //?
}
}
/**
*/
ulong seek(long offset, SeekPos whence)
{
version(Windows)
{
int hi = cast(int)(offset>>32);
uint low = SetFilePointer(hFile, cast(int)offset, &hi, whence);
if ((low == INVALID_SET_FILE_POINTER) && (GetLastError() != 0))
throw new /*Seek*/Exception("unable to move file pointer");
ulong result = (cast(ulong)hi << 32) + low;
}
else
version (Posix)
{
auto result = lseek(hFile, cast(int)offset, whence);
if (result == cast(typeof(result))-1)
throw new /*Seek*/Exception("unable to move file pointer");
}
return cast(ulong)result;
}
}
static assert(isSource!File);
static assert(isSink!File);
static assert(isDevice!File);
/**
Modifiers to limit primitives of $(D_PARAM D) to source.
*/
Sourced!D sourced(D)(D device)
{
return Sourced!D(device);
}
/// ditto
template Sourced(alias D) if (isTemplate!D)
{
template Sourced(Args...)
{
alias .Sourced!(D!Args) Sourced;
}
}
/// ditto
struct Sourced(D)
if (isSource!D && isSink!D)
{
private:
alias UnitType!D E;
D device;
public:
/**
*/
this(Device)(Device d) if (is(Device == D))
{
move(d, device);
}
/**
Delegate construction to $(D_PARAM D).
*/
this(A...)(A args)
{
__ctor(D(args));
}
/**
*/
bool pull(ref E[] buf)
{
return device.pull(buf);
}
}
// ditto
template Sourced(D) if (isSource!D && !isSink!D)
{
alias D Sourced;
}
/**
Modifiers to limit primitives of $(D_PARAM D) to sink.
*/
Sinked!D sinked(D)(D device)
{
return Sinked!D(device);
}
/// ditto
template Sinked(alias D) if (isTemplate!D)
{
template Sinked(Args...)
{
alias .Sinked!(D!Args) Sinked;
}
}
/// ditto
struct Sinked(D)
if (isSource!D && isSink!D)
{
private:
alias UnitType!D E;
D device;
public:
/**
*/
this(Device)(Device d) if (is(Device == D))
{
move(d, device);
}
/**
Delegate construction to $(D_PARAM D).
*/
this(A...)(A args)
{
__ctor(D(args));
}
/**
*/
bool push(ref const(E)[] buf)
{
return device.push(buf);
}
}
// ditto
template Sinked(D) if (!isSource!D && isSink!D)
{
alias D Sinked;
}
/**
*/
Encoded!(Device, E) encoded(E, Device)(Device device)
{
return typeof(return)(move(device));
}
/// ditto
template Encoded(alias D) if (isTemplate!D)
{
template Encoded(Args...)
{
alias .Encoded!(D!Args) Encoded;
}
}
/// ditto
struct Encoded(Device, E)
{
private:
Device device;
public:
/**
*/
this(D)(D d) if (is(D == Device))
{
move(d, device);
}
/**
*/
this(A...)(A args)
{
__ctor(Device(args));
}
static if (isSource!Device)
/**
*/
bool pull(ref E[] buf)
{
auto v = cast(ubyte[])buf;
auto result = device.pull(v);
if (result)
{
// writefln("encoded.pull : buf = %(%02X %)", cast(ubyte[])buf);
static if (E.sizeof > 1) assert(v.length % E.sizeof == 0);
buf = cast(E[])v;
}
return result;
}
static if (isPool!Device)
{
/**
primitives of pool.
*/
bool fetch()
{
return device.fetch();
}
/// ditto
@property const(E)[] available() const
{
return cast(const(E)[])device.available;
}
/// ditto
void consume(size_t n)
{
device.consume(E.sizeof * n);
}
}
static if (isSink!Device)
/**
primitive of sink.
*/
bool push(ref const(E)[] data)
{
auto v = cast(const(ubyte)[])data;
auto result = device.push(v);
static if (E.sizeof > 1) assert(v.length % E.sizeof == 0);
data = data[$ - v.length / E.sizeof .. $];
return result;
}
static if (isSeekable!Device)
/**
*/
ulong seek(long offset, SeekPos whence)
{
return device.seek(offset, whence);
}
}
/**
*/
Buffered!(D) buffered(D)(D device, size_t bufferSize = 4096)
{
return typeof(return)(move(device), bufferSize);
}
/// ditto
template Buffered(alias D) if (isTemplate!D)
{
template Buffered(Args...)
{
alias .Buffered!(D!Args) Buffered;
}
}
/// ditto
struct Buffered(D)
if (isSource!D || isSink!D)
{
private:
alias UnitType!D E;
D device;
E[] buffer;
static if (isSink !D) size_t rsv_start = 0, rsv_end = 0;
static if (isSource!D) size_t ava_start = 0, ava_end = 0;
static if (isDevice!D) long base_pos = 0;
public:
/**
*/
this(Device)(Device d, size_t bufferSize) if (is(Device == D))
{
move(d, device);
buffer.length = bufferSize;
}
/**
*/
this(A...)(A args, size_t bufferSize)
{
__ctor(D(args), bufferSize);
}
static if (isSink!D)
~this()
{
while (reserves.length > 0)
flush();
}
static if (isSource!D)
/**
primitives of pool.
*/
bool fetch()
body
{
static if (isDevice!D)
bool empty_reserves = (reserves.length == 0);
else
enum empty_reserves = true;
if (empty_reserves && available.length == 0)
{
static if (isDevice!D) base_pos += ava_end;
static if (isDevice!D) rsv_start = rsv_end = 0;
ava_start = ava_end = 0;
}
static if (isDevice!D)
device.seek(base_pos + ava_end, SeekPos.Set);
auto v = buffer[ava_end .. $];
auto result = device.pull(v);
if (result)
{
ava_end += v.length;
}
return result;
}
static if (isSource!D)
/// ditto
@property const(E)[] available() const
{
return buffer[ava_start .. ava_end];
}
static if (isSource!D)
/// ditto
void consume(size_t n)
in { assert(n <= available.length); }
body
{
ava_start += n;
}
static if (isSink!D)
{
/*
primitives of output pool?
*/
private @property E[] usable()
{
static if (isDevice!D)
return buffer[ava_start .. $];
else
return buffer[rsv_end .. $];
}
private @property const(E)[] reserves()
{
return buffer[rsv_start .. rsv_end];
}
// ditto
private void commit(size_t n)
{
static if (isDevice!D)
{
assert(ava_start + n <= buffer.length);
ava_start += n;
ava_end = max(ava_end, ava_start);
rsv_end = ava_start;
}
else
{
assert(rsv_end + n <= buffer.length);
rsv_end += n;
}
}
}
static if (isSink!D)
/**
flush buffer.
primitives of output pool?
*/
bool flush()
in { assert(reserves.length > 0); }
body
{
static if (isDevice!D)
device.seek(base_pos + rsv_start, SeekPos.Set);
auto rsv = buffer[rsv_start .. rsv_end];
auto result = device.push(rsv);
if (result)
{
rsv_start = rsv_end - rsv.length;
static if (isDevice!D)
bool empty_available = (available.length == 0);
else
enum empty_available = true;
if (reserves.length == 0 && empty_available)
{
static if (isDevice!D) base_pos += ava_end;
static if (isDevice!D) ava_start = ava_end = 0;
rsv_start = rsv_end = 0;
}
}
return result;
}
static if (isSink!D)
/**
primitive of sink.
*/
bool push(const(E)[] data)
{
// return device.push(data);
while (data.length > 0)
{
if (usable.length == 0)
if (!flush()) goto Exit;
auto len = min(data.length, usable.length);
usable[0 .. len] = data[0 .. len];
data = data[len .. $];
commit(len);
}
if (usable.length == 0)
if (!flush()) goto Exit;
return true;
Exit:
return false;
}
}
/*shared */static this()
{
din = Sourced!File(GetStdHandle(STD_INPUT_HANDLE));
dout = Sinked !File(GetStdHandle(STD_OUTPUT_HANDLE));
derr = Sinked !File(GetStdHandle(STD_ERROR_HANDLE));
}
//__gshared
//{
Sourced!File din;
Sinked !File dout;
Sinked !File derr;
//}
/**
Convert pool to input range.
Convert sink to output range.
Design:
Rangeはコンストラクト直後にemptyが取れる、つまりPoolでいうfetch済みである必要があるが、
Poolは未fetchであることが必要なので互いの要件が矛盾する。よってPoolはInputRangeを
同時に提供できないため、これをWrapするRangedが必要となる。
Design:
OutputRangeはデータがすべて書き込まれるまでSinkのpushを繰り返す。
Design:
RangedはSourceを直接Rangeには変換しない。
これはバッファリングが必要になるためで、これはBufferedが担当する。
(バッファリングのサイズはUserSideが解決するべきと考え、deviceモジュールは暗黙に面倒を見ない)
*/
Ranged!D ranged(D)(D device)
{
static if (isDeviced!D)
return device.original;
else
return Ranged!D(move(device));
}
/// ditto
template Ranged(alias D) if (isTemplate!D)
{
template Ranged(Args...)
{
alias .Ranged!(D!Args) Ranged;
}
}
/// ditto
struct Ranged(D)
if (!isDeviced!D && (isPool!D || isSink!D))
{
private:
alias D Original;
alias device original;
alias UnitType!D E;
D device;
bool eof;
public:
/**
*/
this(Device)(Device d) if (is(Device == D))
{
move(d, device);
static if (isPool!D)
eof = !device.fetch();
}
/**
*/
this(A...)(A args)
{
__ctor(D(args));
}
static if (isPool!D)
{
/**
primitives of input range.
*/
@property bool empty() const
{
return eof;
}
/// ditto
@property E front()
{
return device.available[0];
}
/// ditto
void popFront()
{
device.consume(1);
if (device.available.length == 0)
eof = !device.fetch();
}
}
static if (isSink!D)
{
/**
primitive of output range.
*/
void put(const(E) data)
{
put((&data)[0 .. 1]);
}
/// ditto
void put(const(E)[] data)
{
while (data.length > 0)
{
if (!device.push(data))
throw new Exception("");
}
}
}
}
unittest
{
scope(failure) std.stdio.writefln("unittest@%s:%s failed", __FILE__, __LINE__);
auto fname = "dummy.txt";
{ auto r = ranged(Sinked!File(fname, "w"));
ubyte[] data = [1,2,3];
r.put(data);
}
{ auto r = ranged(buffered(Sourced!File(fname, "r"), 1024));
auto i = 1;
foreach (e; r)
{
static assert(is(typeof(e) == ubyte));
assert(e == i++);
}
}
std.file.remove(fname);
}
// ditto
template Ranged(D) if (isDeviced!D)
{
alias D.Original Ranged;
}
unittest
{
int[] a;
auto a2 = ranged(deviced(a));
static assert(is(typeof(a2) == int[]));
}
/*
*/
template isRanged(R)
{
static if (is(R _ : Ranged!D, D))
enum isRanged = true;
else
enum isRanged = false;
}
unittest
{
static struct DummySink
{
bool push(ref const(int)[] data){ return false; }
}
static assert(isSink!DummySink);
auto d = DummySink();
auto r = ranged(d);
static assert(isRanged!(typeof(r)));
}
/**
converts range to device (source, pool, sink)
Design:
$(D Deviced) can receive an array, but doesn't treat $(D ElementType!(E[])),
but also $(D E).
*/
Deviced!R deviced(R)(R range)
{
static if (isRanged!R)
return range.original;
else
return Deviced!R(move(range));
}
/// ditto
template Deviced(alias D) if (isTemplate!D)
{
template Deviced(Args...)
{
alias .Deviced!(D!Args) Deviced;
}
}
/// ditto
struct Deviced(R)
if (!isRanged!R && (isInputRange!R || __traits(hasMember, R, "put")))
{
private:
alias R Original;
alias range original;
R range;
static if (isInputRange!R)
{
static if (isArray!R)
alias typeof(R.init[0]) E;
else
alias ElementType!R E;
}
public:
this(R)(R r) if (is(R == R))
{
move(r, range);
}
this(A...)(A args)
{
__ctor(R(args));
}
static if (isInputRange!R)
{
/**
*/
bool pull(ref E[] data)
{
if (range.empty)
return false;
else
{
static if (isArray!R)
{
auto len = min(range.length, data.length);
data[0 .. len] = range[0 .. len];
range = range[len .. $];
}
else
{
while (data.length && !range.empty)
{
data[0] = range.front;
range.popFront();
}
}
return true;
}
}
}
static if (isArray!R)
{
/**
*/
@property const(E)[] available() const
{
return range;
}
/**
*/
bool fetch()
{
return !range.empty;
}
/**
*/
void consume(size_t n)
{
range.popFrontN(n);
}
}
bool push(E)(ref const(E)[] data)
if (isOutputRange!(R, E))
{
if (range.empty)
return false;
int written;
static if (isArray!R)
{
written = (data.length > range.length ? range.length : data.length);
range[0 .. written] = data[0 .. written];
range = range[written .. $];
}
else
{