/
stream.d
2941 lines (2681 loc) · 84.6 KB
/
stream.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
// Written in the D programming language
/**
* Source: $(PHOBOSSRC std/_stream.d)
* Macros:
* WIKI = Phobos/StdStream
*/
/*
* Copyright (c) 2001-2005
* Pavel "EvilOne" Minayev
* with buffering and endian support added by Ben Hinkle
* with buffered readLine performance improvements by Dave Fladebo
* with opApply inspired by (and mostly copied from) Regan Heath
* with bug fixes and MemoryStream/SliceStream enhancements by Derick Eddington
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Author makes no representations about
* the suitability of this software for any purpose. It is provided
* "as is" without express or implied warranty.
*/
module std.stream;
/* Class structure:
* InputStream interface for reading
* OutputStream interface for writing
* Stream abstract base of stream implementations
* File an OS file stream
* FilterStream a base-class for wrappers around another stream
* BufferedStream a buffered stream wrapping another stream
* BufferedFile a buffered File
* EndianStream a wrapper stream for swapping byte order and BOMs
* SliceStream a portion of another stream
* MemoryStream a stream entirely stored in main memory
* TArrayStream a stream wrapping an array-like buffer
*/
/// A base class for stream exceptions.
class StreamException: Exception {
/// Construct a StreamException with given error message.
this(string msg) { super(msg); }
}
/// Thrown when unable to read data from Stream.
class ReadException: StreamException {
/// Construct a ReadException with given error message.
this(string msg) { super(msg); }
}
/// Thrown when unable to write data to Stream.
class WriteException: StreamException {
/// Construct a WriteException with given error message.
this(string msg) { super(msg); }
}
/// Thrown when unable to move Stream pointer.
class SeekException: StreamException {
/// Construct a SeekException with given error message.
this(string msg) { super(msg); }
}
// seek whence...
enum SeekPos {
Set,
Current,
End
}
private {
import std.conv;
import std.ascii;
import std.format;
import std.system; // for Endian enumeration
import std.utf;
import core.bitop; // for bswap
import core.vararg;
}
version (Windows) {
private import std.file;
}
/// InputStream is the interface for readable streams.
interface InputStream {
/***
* Read exactly size bytes into the buffer.
*
* Throws a ReadException if it is not correct.
*/
void readExact(void* buffer, size_t size);
/***
* Read a block of data big enough to fill the given array buffer.
*
* Returns: the actual number of bytes read. Unfilled bytes are not modified.
*/
size_t read(ubyte[] buffer);
/***
* Read a basic type or counted string.
*
* Throw a ReadException if it could not be read.
* Outside of byte, ubyte, and char, the format is
* implementation-specific and should not be used except as opposite actions
* to write.
*/
void read(out byte x);
void read(out ubyte x); /// ditto
void read(out short x); /// ditto
void read(out ushort x); /// ditto
void read(out int x); /// ditto
void read(out uint x); /// ditto
void read(out long x); /// ditto
void read(out ulong x); /// ditto
void read(out float x); /// ditto
void read(out double x); /// ditto
void read(out real x); /// ditto
void read(out ifloat x); /// ditto
void read(out idouble x); /// ditto
void read(out ireal x); /// ditto
void read(out cfloat x); /// ditto
void read(out cdouble x); /// ditto
void read(out creal x); /// ditto
void read(out char x); /// ditto
void read(out wchar x); /// ditto
void read(out dchar x); /// ditto
// reads a string, written earlier by write()
void read(out char[] s); /// ditto
// reads a Unicode string, written earlier by write()
void read(out wchar[] s); /// ditto
/***
* Read a line that is terminated with some combination of carriage return and
* line feed or end-of-file.
*
* The terminators are not included. The wchar version
* is identical. The optional buffer parameter is filled (reallocating
* it if necessary) and a slice of the result is returned.
*/
char[] readLine();
char[] readLine(char[] result); /// ditto
wchar[] readLineW(); /// ditto
wchar[] readLineW(wchar[] result); /// ditto
/***
* Overload foreach statements to read the stream line by line and call the
* supplied delegate with each line or with each line with line number.
*
* The string passed in line may be reused between calls to the delegate.
* Line numbering starts at 1.
* Breaking out of the foreach will leave the stream
* position at the beginning of the next line to be read.
* For example, to echo a file line-by-line with line numbers run:
* ------------------------------------
* Stream file = new BufferedFile("sample.txt");
* foreach(ulong n, char[] line; file)
* {
* writefln("line %d: %s", n, line);
* }
* file.close();
* ------------------------------------
*/
// iterate through the stream line-by-line
int opApply(scope int delegate(ref char[] line) dg);
int opApply(scope int delegate(ref ulong n, ref char[] line) dg); /// ditto
int opApply(scope int delegate(ref wchar[] line) dg); /// ditto
int opApply(scope int delegate(ref ulong n, ref wchar[] line) dg); /// ditto
/// Read a string of the given length,
/// throwing ReadException if there was a problem.
char[] readString(size_t length);
/***
* Read a string of the given length, throwing ReadException if there was a
* problem.
*
* The file format is implementation-specific and should not be used
* except as opposite actions to <b>write</b>.
*/
wchar[] readStringW(size_t length);
/***
* Read and return the next character in the stream.
*
* This is the only method that will handle ungetc properly.
* getcw's format is implementation-specific.
* If EOF is reached then getc returns char.init and getcw returns wchar.init.
*/
char getc();
wchar getcw(); /// ditto
/***
* Push a character back onto the stream.
*
* They will be returned in first-in last-out order from getc/getcw.
* Only has effect on further calls to getc() and getcw().
*/
char ungetc(char c);
wchar ungetcw(wchar c); /// ditto
/***
* Scan a string from the input using a similar form to C's scanf
* and <a href="std_format.html">std.format</a>.
*
* An argument of type string is interpreted as a format string.
* All other arguments must be pointer types.
* If a format string is not present a default will be supplied computed from
* the base type of the pointer type. An argument of type string* is filled
* (possibly with appending characters) and a slice of the result is assigned
* back into the argument. For example the following readf statements
* are equivalent:
* --------------------------
* int x;
* double y;
* string s;
* file.readf(&x, " hello ", &y, &s);
* file.readf("%d hello %f %s", &x, &y, &s);
* file.readf("%d hello %f", &x, &y, "%s", &s);
* --------------------------
*/
int vreadf(TypeInfo[] arguments, void* args);
int readf(...); /// ditto
/// Retrieve the number of bytes available for immediate reading.
size_t available();
/***
* Return whether the current file position is the same as the end of the
* file.
*
* This does not require actually reading past the end, as with stdio. For
* non-seekable streams this might only return true after attempting to read
* past the end.
*/
bool eof();
bool isOpen(); /// Return true if the stream is currently open.
}
/// Interface for writable streams.
interface OutputStream {
/***
* Write exactly size bytes from buffer, or throw a WriteException if that
* could not be done.
*/
void writeExact(const void* buffer, size_t size);
/***
* Write as much of the buffer as possible,
* returning the number of bytes written.
*/
size_t write(const(ubyte)[] buffer);
/***
* Write a basic type.
*
* Outside of byte, ubyte, and char, the format is implementation-specific
* and should only be used in conjunction with read.
* Throw WriteException on error.
*/
void write(byte x);
void write(ubyte x); /// ditto
void write(short x); /// ditto
void write(ushort x); /// ditto
void write(int x); /// ditto
void write(uint x); /// ditto
void write(long x); /// ditto
void write(ulong x); /// ditto
void write(float x); /// ditto
void write(double x); /// ditto
void write(real x); /// ditto
void write(ifloat x); /// ditto
void write(idouble x); /// ditto
void write(ireal x); /// ditto
void write(cfloat x); /// ditto
void write(cdouble x); /// ditto
void write(creal x); /// ditto
void write(char x); /// ditto
void write(wchar x); /// ditto
void write(dchar x); /// ditto
/***
* Writes a string, together with its length.
*
* The format is implementation-specific
* and should only be used in conjunction with read.
* Throw WriteException on error.
*/
void write(const(char)[] s);
void write(const(wchar)[] s); /// ditto
/***
* Write a line of text,
* appending the line with an operating-system-specific line ending.
*
* Throws WriteException on error.
*/
void writeLine(const(char)[] s);
/***
* Write a line of text,
* appending the line with an operating-system-specific line ending.
*
* The format is implementation-specific.
* Throws WriteException on error.
*/
void writeLineW(const(wchar)[] s);
/***
* Write a string of text.
*
* Throws WriteException if it could not be fully written.
*/
void writeString(const(char)[] s);
/***
* Write a string of text.
*
* The format is implementation-specific.
* Throws WriteException if it could not be fully written.
*/
void writeStringW(const(wchar)[] s);
/***
* Print a formatted string into the stream using printf-style syntax,
* returning the number of bytes written.
*/
size_t vprintf(const(char)[] format, va_list args);
size_t printf(const(char)[] format, ...); /// ditto
/***
* Print a formatted string into the stream using writef-style syntax.
* References: <a href="std_format.html">std.format</a>.
* Returns: self to chain with other stream commands like flush.
*/
OutputStream writef(...);
OutputStream writefln(...); /// ditto
OutputStream writefx(TypeInfo[] arguments, void* argptr, int newline = false); /// ditto
void flush(); /// Flush pending output if appropriate.
void close(); /// Close the stream, flushing output if appropriate.
bool isOpen(); /// Return true if the stream is currently open.
}
/***
* Stream is the base abstract class from which the other stream classes derive.
*
* Stream's byte order is the format native to the computer.
*
* Reading:
* These methods require that the readable flag be set.
* Problems with reading result in a ReadException being thrown.
* Stream implements the InputStream interface in addition to the
* readBlock method.
*
* Writing:
* These methods require that the writeable flag be set. Problems with writing
* result in a WriteException being thrown. Stream implements the OutputStream
* interface in addition to the following methods:
* writeBlock
* copyFrom
* copyFrom
*
* Seeking:
* These methods require that the seekable flag be set.
* Problems with seeking result in a SeekException being thrown.
* seek, seekSet, seekCur, seekEnd, position, size, toString, toHash
*/
// not really abstract, but its instances will do nothing useful
class Stream : InputStream, OutputStream {
private import std.string, crc32, std.c.stdlib, std.c.stdio;
// stream abilities
bool readable = false; /// Indicates whether this stream can be read from.
bool writeable = false; /// Indicates whether this stream can be written to.
bool seekable = false; /// Indicates whether this stream can be seeked within.
protected bool isopen = true; /// Indicates whether this stream is open.
protected bool readEOF = false; /** Indicates whether this stream is at eof
* after the last read attempt.
*/
protected bool prevCr = false; /** For a non-seekable stream indicates that
* the last readLine or readLineW ended on a
* '\r' character.
*/
this() {}
/***
* Read up to size bytes into the buffer and return the number of bytes
* actually read. A return value of 0 indicates end-of-file.
*/
abstract size_t readBlock(void* buffer, size_t size);
// reads block of data of specified size,
// throws ReadException on error
void readExact(void* buffer, size_t size) {
for(;;) {
if (!size) return;
size_t readsize = readBlock(buffer, size); // return 0 on eof
if (readsize == 0) break;
buffer += readsize;
size -= readsize;
}
if (size != 0)
throw new ReadException("not enough data in stream");
}
// reads block of data big enough to fill the given
// array, returns actual number of bytes read
size_t read(ubyte[] buffer) {
return readBlock(buffer.ptr, buffer.length);
}
// read a single value of desired type,
// throw ReadException on error
void read(out byte x) { readExact(&x, x.sizeof); }
void read(out ubyte x) { readExact(&x, x.sizeof); }
void read(out short x) { readExact(&x, x.sizeof); }
void read(out ushort x) { readExact(&x, x.sizeof); }
void read(out int x) { readExact(&x, x.sizeof); }
void read(out uint x) { readExact(&x, x.sizeof); }
void read(out long x) { readExact(&x, x.sizeof); }
void read(out ulong x) { readExact(&x, x.sizeof); }
void read(out float x) { readExact(&x, x.sizeof); }
void read(out double x) { readExact(&x, x.sizeof); }
void read(out real x) { readExact(&x, x.sizeof); }
void read(out ifloat x) { readExact(&x, x.sizeof); }
void read(out idouble x) { readExact(&x, x.sizeof); }
void read(out ireal x) { readExact(&x, x.sizeof); }
void read(out cfloat x) { readExact(&x, x.sizeof); }
void read(out cdouble x) { readExact(&x, x.sizeof); }
void read(out creal x) { readExact(&x, x.sizeof); }
void read(out char x) { readExact(&x, x.sizeof); }
void read(out wchar x) { readExact(&x, x.sizeof); }
void read(out dchar x) { readExact(&x, x.sizeof); }
// reads a string, written earlier by write()
void read(out char[] s) {
size_t len;
read(len);
s = readString(len);
}
// reads a Unicode string, written earlier by write()
void read(out wchar[] s) {
size_t len;
read(len);
s = readStringW(len);
}
// reads a line, terminated by either CR, LF, CR/LF, or EOF
char[] readLine() {
return readLine(null);
}
// reads a line, terminated by either CR, LF, CR/LF, or EOF
// reusing the memory in buffer if result will fit and otherwise
// allocates a new string
char[] readLine(char[] result) {
size_t strlen = 0;
char ch = getc();
while (readable) {
switch (ch) {
case '\r':
if (seekable) {
ch = getc();
if (ch != '\n')
ungetc(ch);
} else {
prevCr = true;
}
goto case;
case '\n':
case char.init:
result.length = strlen;
return result;
default:
if (strlen < result.length) {
result[strlen] = ch;
} else {
result ~= ch;
}
strlen++;
}
ch = getc();
}
result.length = strlen;
return result;
}
// reads a Unicode line, terminated by either CR, LF, CR/LF,
// or EOF; pretty much the same as the above, working with
// wchars rather than chars
wchar[] readLineW() {
return readLineW(null);
}
// reads a Unicode line, terminated by either CR, LF, CR/LF,
// or EOF;
// fills supplied buffer if line fits and otherwise allocates a new string.
wchar[] readLineW(wchar[] result) {
size_t strlen = 0;
wchar c = getcw();
while (readable) {
switch (c) {
case '\r':
if (seekable) {
c = getcw();
if (c != '\n')
ungetcw(c);
} else {
prevCr = true;
}
goto case;
case '\n':
case wchar.init:
result.length = strlen;
return result;
default:
if (strlen < result.length) {
result[strlen] = c;
} else {
result ~= c;
}
strlen++;
}
c = getcw();
}
result.length = strlen;
return result;
}
// iterate through the stream line-by-line - due to Regan Heath
int opApply(scope int delegate(ref char[] line) dg) {
int res = 0;
char[128] buf;
while (!eof()) {
char[] line = readLine(buf);
res = dg(line);
if (res) break;
}
return res;
}
// iterate through the stream line-by-line with line count and string
int opApply(scope int delegate(ref ulong n, ref char[] line) dg) {
int res = 0;
ulong n = 1;
char[128] buf;
while (!eof()) {
auto line = readLine(buf);
res = dg(n,line);
if (res) break;
n++;
}
return res;
}
// iterate through the stream line-by-line with wchar[]
int opApply(scope int delegate(ref wchar[] line) dg) {
int res = 0;
wchar[128] buf;
while (!eof()) {
auto line = readLineW(buf);
res = dg(line);
if (res) break;
}
return res;
}
// iterate through the stream line-by-line with line count and wchar[]
int opApply(scope int delegate(ref ulong n, ref wchar[] line) dg) {
int res = 0;
ulong n = 1;
wchar[128] buf;
while (!eof()) {
auto line = readLineW(buf);
res = dg(n,line);
if (res) break;
n++;
}
return res;
}
// reads a string of given length, throws
// ReadException on error
char[] readString(size_t length) {
char[] result = new char[length];
readExact(result.ptr, length);
return result;
}
// reads a Unicode string of given length, throws
// ReadException on error
wchar[] readStringW(size_t length) {
auto result = new wchar[length];
readExact(result.ptr, result.length * wchar.sizeof);
return result;
}
// unget buffer
private wchar[] unget;
final bool ungetAvailable() { return unget.length > 1; }
// reads and returns next character from the stream,
// handles characters pushed back by ungetc()
// returns char.init on eof.
char getc() {
char c;
if (prevCr) {
prevCr = false;
c = getc();
if (c != '\n')
return c;
}
if (unget.length > 1) {
c = cast(char)unget[unget.length - 1];
unget.length = unget.length - 1;
} else {
readBlock(&c,1);
}
return c;
}
// reads and returns next Unicode character from the
// stream, handles characters pushed back by ungetc()
// returns wchar.init on eof.
wchar getcw() {
wchar c;
if (prevCr) {
prevCr = false;
c = getcw();
if (c != '\n')
return c;
}
if (unget.length > 1) {
c = unget[unget.length - 1];
unget.length = unget.length - 1;
} else {
void* buf = &c;
size_t n = readBlock(buf,2);
if (n == 1 && readBlock(buf+1,1) == 0)
throw new ReadException("not enough data in stream");
}
return c;
}
// pushes back character c into the stream; only has
// effect on further calls to getc() and getcw()
char ungetc(char c) {
if (c == c.init) return c;
// first byte is a dummy so that we never set length to 0
if (unget.length == 0)
unget.length = 1;
unget ~= c;
return c;
}
// pushes back Unicode character c into the stream; only
// has effect on further calls to getc() and getcw()
wchar ungetcw(wchar c) {
if (c == c.init) return c;
// first byte is a dummy so that we never set length to 0
if (unget.length == 0)
unget.length = 1;
unget ~= c;
return c;
}
int vreadf(TypeInfo[] arguments, void* args) {
string fmt;
int j = 0;
int count = 0, i = 0;
char c = getc();
while ((j < arguments.length || i < fmt.length) && !eof()) {
if (fmt.length == 0 || i == fmt.length) {
i = 0;
if (arguments[j] is typeid(char[])) {
fmt = va_arg!(string)(args);
j++;
continue;
} else if (arguments[j] is typeid(int*) ||
arguments[j] is typeid(byte*) ||
arguments[j] is typeid(short*) ||
arguments[j] is typeid(long*)) {
fmt = "%d";
} else if (arguments[j] is typeid(uint*) ||
arguments[j] is typeid(ubyte*) ||
arguments[j] is typeid(ushort*) ||
arguments[j] is typeid(ulong*)) {
fmt = "%d";
} else if (arguments[j] is typeid(float*) ||
arguments[j] is typeid(double*) ||
arguments[j] is typeid(real*)) {
fmt = "%f";
} else if (arguments[j] is typeid(char[]*) ||
arguments[j] is typeid(wchar[]*) ||
arguments[j] is typeid(dchar[]*)) {
fmt = "%s";
} else if (arguments[j] is typeid(char*)) {
fmt = "%c";
}
}
if (fmt[i] == '%') { // a field
i++;
bool suppress = false;
if (fmt[i] == '*') { // suppress assignment
suppress = true;
i++;
}
// read field width
int width = 0;
while (isDigit(fmt[i])) {
width = width * 10 + (fmt[i] - '0');
i++;
}
if (width == 0)
width = -1;
// skip any modifier if present
if (fmt[i] == 'h' || fmt[i] == 'l' || fmt[i] == 'L')
i++;
// check the typechar and act accordingly
switch (fmt[i]) {
case 'd': // decimal/hexadecimal/octal integer
case 'D':
case 'u':
case 'U':
case 'o':
case 'O':
case 'x':
case 'X':
case 'i':
case 'I':
{
while (isWhite(c)) {
c = getc();
count++;
}
bool neg = false;
if (c == '-') {
neg = true;
c = getc();
count++;
} else if (c == '+') {
c = getc();
count++;
}
char ifmt = cast(char)(fmt[i] | 0x20);
if (ifmt == 'i') { // undetermined base
if (c == '0') { // octal or hex
c = getc();
count++;
if (c == 'x' || c == 'X') { // hex
ifmt = 'x';
c = getc();
count++;
} else { // octal
ifmt = 'o';
}
}
else // decimal
ifmt = 'd';
}
long n = 0;
switch (ifmt)
{
case 'd': // decimal
case 'u': {
while (isDigit(c) && width) {
n = n * 10 + (c - '0');
width--;
c = getc();
count++;
}
} break;
case 'o': { // octal
while (isOctalDigit(c) && width) {
n = n * 8 + (c - '0');
width--;
c = getc();
count++;
}
} break;
case 'x': { // hexadecimal
while (isHexDigit(c) && width) {
n *= 0x10;
if (isDigit(c))
n += c - '0';
else
n += 0xA + (c | 0x20) - 'a';
width--;
c = getc();
count++;
}
} break;
default:
assert(0);
}
if (neg)
n = -n;
if (arguments[j] is typeid(int*)) {
int* p = va_arg!(int*)(args);
*p = cast(int)n;
} else if (arguments[j] is typeid(short*)) {
short* p = va_arg!(short*)(args);
*p = cast(short)n;
} else if (arguments[j] is typeid(byte*)) {
byte* p = va_arg!(byte*)(args);
*p = cast(byte)n;
} else if (arguments[j] is typeid(long*)) {
long* p = va_arg!(long*)(args);
*p = n;
} else if (arguments[j] is typeid(uint*)) {
uint* p = va_arg!(uint*)(args);
*p = cast(uint)n;
} else if (arguments[j] is typeid(ushort*)) {
ushort* p = va_arg!(ushort*)(args);
*p = cast(ushort)n;
} else if (arguments[j] is typeid(ubyte*)) {
ubyte* p = va_arg!(ubyte*)(args);
*p = cast(ubyte)n;
} else if (arguments[j] is typeid(ulong*)) {
ulong* p = va_arg!(ulong*)(args);
*p = cast(ulong)n;
}
j++;
i++;
} break;
case 'f': // float
case 'F':
case 'e':
case 'E':
case 'g':
case 'G':
{
while (isWhite(c)) {
c = getc();
count++;
}
bool neg = false;
if (c == '-') {
neg = true;
c = getc();
count++;
} else if (c == '+') {
c = getc();
count++;
}
real n = 0;
while (isDigit(c) && width) {
n = n * 10 + (c - '0');
width--;
c = getc();
count++;
}
if (width && c == '.') {
width--;
c = getc();
count++;
double frac = 1;
while (isDigit(c) && width) {
n = n * 10 + (c - '0');
frac *= 10;
width--;
c = getc();
count++;
}
n /= frac;
}
if (width && (c == 'e' || c == 'E')) {
width--;
c = getc();
count++;
if (width) {
bool expneg = false;
if (c == '-') {
expneg = true;
width--;
c = getc();
count++;
} else if (c == '+') {
width--;
c = getc();
count++;
}
real exp = 0;
while (isDigit(c) && width) {
exp = exp * 10 + (c - '0');
width--;
c = getc();
count++;
}
if (expneg) {
while (exp--)
n /= 10;
} else {
while (exp--)
n *= 10;
}
}
}
if (neg)
n = -n;
if (arguments[j] is typeid(float*)) {
float* p = va_arg!(float*)(args);
*p = n;
} else if (arguments[j] is typeid(double*)) {
double* p = va_arg!(double*)(args);
*p = n;
} else if (arguments[j] is typeid(real*)) {
real* p = va_arg!(real*)(args);
*p = n;
}
j++;
i++;
} break;
case 's': { // string
while (isWhite(c)) {
c = getc();
count++;
}
char[] s;
char[]* p;
size_t strlen;
if (arguments[j] is typeid(char[]*)) {
p = va_arg!(char[]*)(args);
s = *p;
}
while (!isWhite(c) && c != char.init) {
if (strlen < s.length) {
s[strlen] = c;
} else {
s ~= c;
}
strlen++;
c = getc();
count++;
}
s = s[0 .. strlen];
if (arguments[j] is typeid(char[]*)) {
*p = s;
} else if (arguments[j] is typeid(char*)) {
s ~= 0;
auto q = va_arg!(char*)(args);
q[0 .. s.length] = s[];
} else if (arguments[j] is typeid(wchar[]*)) {
auto q = va_arg!(const(wchar)[]*)(args);
*q = toUTF16(s);
} else if (arguments[j] is typeid(dchar[]*)) {
auto q = va_arg!(const(dchar)[]*)(args);
*q = toUTF32(s);
}
j++;
i++;
} break;
case 'c': { // character(s)
char* s = va_arg!(char*)(args);
if (width < 0)
width = 1;
else
while (isWhite(c)) {
c = getc();
count++;
}
while (width-- && !eof()) {
*(s++) = c;
c = getc();
count++;
}
j++;
i++;
} break;