-
-
Notifications
You must be signed in to change notification settings - Fork 706
/
Copy pathformat.d
6160 lines (5376 loc) · 172 KB
/
format.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.
/**
This module implements the formatting functionality for strings and
I/O. It's comparable to C99's $(D vsprintf()) and uses a similar
_format encoding scheme.
For an introductory look at $(B std._format)'s capabilities and how to use
this module see the dedicated
$(LINK2 http://wiki.dlang.org/Defining_custom_print_format_specifiers, DWiki article).
This module centers around two functions:
$(BOOKTABLE ,
$(TR $(TH Function Name) $(TH Description)
)
$(TR $(TD $(LREF formattedRead))
$(TD Reads values according to the _format string from an InputRange.
))
$(TR $(TD $(LREF formattedWrite))
$(TD Formats its arguments according to the _format string and puts them
to an OutputRange.
))
)
Please see the documentation of function $(LREF formattedWrite) for a
description of the _format string.
Two functions have been added for convenience:
$(BOOKTABLE ,
$(TR $(TH Function Name) $(TH Description)
)
$(TR $(TD $(LREF _format))
$(TD Returns a GC-allocated string with the formatting result.
))
$(TR $(TD $(LREF sformat))
$(TD Puts the formatting result into a preallocated array.
))
)
These two functions are publicly imported by $(MREF std, string)
to be easily available.
The functions $(LREF formatValue) and $(LREF unformatValue) are
used for the plumbing.
Copyright: Copyright Digital Mars 2000-2013.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP walterbright.com, Walter Bright), $(HTTP erdani.com,
Andrei Alexandrescu), and Kenji Hara
Source: $(PHOBOSSRC std/_format.d)
*/
module std.format;
//debug=format; // uncomment to turn on debugging printf's
import core.vararg;
import std.exception;
import std.meta;
import std.range.primitives;
import std.traits;
/**********************************************************************
* Signals a mismatch between a format and its corresponding argument.
*/
class FormatException : Exception
{
@safe pure nothrow
this()
{
super("format error");
}
@safe pure nothrow
this(string msg, string fn = __FILE__, size_t ln = __LINE__, Throwable next = null)
{
super(msg, fn, ln, next);
}
}
private alias enforceFmt = enforceEx!FormatException;
/**********************************************************************
Interprets variadic argument list $(D args), formats them according
to $(D fmt), and sends the resulting characters to $(D w). The
encoding of the output is the same as $(D Char). The type $(D Writer)
must satisfy $(D $(REF isOutputRange, std,range,primitives)!(Writer, Char)).
The variadic arguments are normally consumed in order. POSIX-style
$(HTTP opengroup.org/onlinepubs/009695399/functions/printf.html,
positional parameter syntax) is also supported. Each argument is
formatted into a sequence of chars according to the format
specification, and the characters are passed to $(D w). As many
arguments as specified in the format string are consumed and
formatted. If there are fewer arguments than format specifiers, a
$(D FormatException) is thrown. If there are more remaining arguments
than needed by the format specification, they are ignored but only
if at least one argument was formatted.
The format string supports the formatting of array and nested array elements
via the grouping format specifiers $(B %() and $(B %)). Each
matching pair of $(B %() and $(B %)) corresponds with a single array
argument. The enclosed sub-format string is applied to individual array
elements. The trailing portion of the sub-format string following the
conversion specifier for the array element is interpreted as the array
delimiter, and is therefore omitted following the last array element. The
$(B %|) specifier may be used to explicitly indicate the start of the
delimiter, so that the preceding portion of the string will be included
following the last array element. (See below for explicit examples.)
Params:
w = Output is sent to this writer. Typical output writers include
$(REF Appender!string, std,array) and $(REF LockingTextWriter, std,stdio).
fmt = Format string.
args = Variadic argument list.
Returns: Formatted number of arguments.
Throws: Mismatched arguments and formats result in a $(D
FormatException) being thrown.
Format_String: <a name="format-string">$(I Format strings)</a>
consist of characters interspersed with $(I format
specifications). Characters are simply copied to the output (such
as putc) after any necessary conversion to the corresponding UTF-8
sequence.
The format string has the following grammar:
$(PRE
$(I FormatString):
$(I FormatStringItem)*
$(I FormatStringItem):
$(B '%%')
$(B '%') $(I Position) $(I Flags) $(I Width) $(I Separator) $(I Precision) $(I FormatChar)
$(B '%$(LPAREN)') $(I FormatString) $(B '%$(RPAREN)')
$(I OtherCharacterExceptPercent)
$(I Position):
$(I empty)
$(I Integer) $(B '$')
$(I Flags):
$(I empty)
$(B '-') $(I Flags)
$(B '+') $(I Flags)
$(B '#') $(I Flags)
$(B '0') $(I Flags)
$(B ' ') $(I Flags)
$(I Width):
$(I empty)
$(I Integer)
$(B '*')
$(I Separator):
$(I empty)
$(B ',')
$(B ',') $(B '?')
$(B ',') $(B '*') $(B '?')
$(B ',') $(I Integer) $(B '?')
$(B ',') $(B '*')
$(B ',') $(I Integer)
$(I Precision):
$(I empty)
$(B '.')
$(B '.') $(I Integer)
$(B '.*')
$(I Integer):
$(I Digit)
$(I Digit) $(I Integer)
$(I Digit):
$(B '0')|$(B '1')|$(B '2')|$(B '3')|$(B '4')|$(B '5')|$(B '6')|$(B '7')|$(B '8')|$(B '9')
$(I FormatChar):
$(B 's')|$(B 'c')|$(B 'b')|$(B 'd')|$(B 'o')|$(B 'x')|$(B 'X')|$(B 'e')|$(B 'E')|$(B 'f')|$(B 'F')|$(B 'g')|$(B 'G')|$(B 'a')|$(B 'A')|$(B '|')
)
$(BOOKTABLE Flags affect formatting depending on the specifier as
follows., $(TR $(TH Flag) $(TH Types affected) $(TH Semantics))
$(TR $(TD $(B '-')) $(TD numeric) $(TD Left justify the result in
the field. It overrides any $(B 0) flag.))
$(TR $(TD $(B '+')) $(TD numeric) $(TD Prefix positive numbers in
a signed conversion with a $(B +). It overrides any $(I space)
flag.))
$(TR $(TD $(B '#')) $(TD integral ($(B 'o'))) $(TD Add to
precision as necessary so that the first digit of the octal
formatting is a '0', even if both the argument and the $(I
Precision) are zero.))
$(TR $(TD $(B '#')) $(TD integral ($(B 'x'), $(B 'X'))) $(TD If
non-zero, prefix result with $(B 0x) ($(B 0X)).))
$(TR $(TD $(B '#')) $(TD floating) $(TD Always insert the decimal
point and print trailing zeros.))
$(TR $(TD $(B '0')) $(TD numeric) $(TD Use leading
zeros to pad rather than spaces (except for the floating point
values $(D nan) and $(D infinity)). Ignore if there's a $(I
Precision).))
$(TR $(TD $(B ' ')) $(TD numeric) $(TD Prefix positive
numbers in a signed conversion with a space.)))
$(DL
$(DT $(I Width))
$(DD
Specifies the minimum field width.
If the width is a $(B *), an additional argument of type $(B int),
preceding the actual argument, is taken as the width.
If the width is negative, it is as if the $(B -) was given
as a $(I Flags) character.)
$(DT $(I Precision))
$(DD Gives the precision for numeric conversions.
If the precision is a $(B *), an additional argument of type $(B int),
preceding the actual argument, is taken as the precision.
If it is negative, it is as if there was no $(I Precision) specifier.)
$(DT $(I Separator))
$(DD Inserts the separator symbols ',' every $(I X) digits, from right
to left, into numeric values to increase readability.
The fractional part of floating point values inserts the separator
from left to right.
Entering an integer after the ',' allows to specify $(I X).
If a '*' is placed after the ',' then $(I X) is specified by an
additional parameter to the format function.
Adding a '?' after the ',' or $(I X) specifier allows to specify
the separator character as an additional parameter.
)
$(DT $(I FormatChar))
$(DD
$(DL
$(DT $(B 's'))
$(DD The corresponding argument is formatted in a manner consistent
with its type:
$(DL
$(DT $(B bool))
$(DD The result is $(D "true") or $(D "false").)
$(DT integral types)
$(DD The $(B %d) format is used.)
$(DT floating point types)
$(DD The $(B %g) format is used.)
$(DT string types)
$(DD The result is the string converted to UTF-8.
A $(I Precision) specifies the maximum number of characters
to use in the result.)
$(DT structs)
$(DD If the struct defines a $(B toString()) method the result is
the string returned from this function. Otherwise the result is
StructName(field<sub>0</sub>, field<sub>1</sub>, ...) where
field<sub>n</sub> is the nth element formatted with the default
format.)
$(DT classes derived from $(B Object))
$(DD The result is the string returned from the class instance's
$(B .toString()) method.
A $(I Precision) specifies the maximum number of characters
to use in the result.)
$(DT unions)
$(DD If the union defines a $(B toString()) method the result is
the string returned from this function. Otherwise the result is
the name of the union, without its contents.)
$(DT non-string static and dynamic arrays)
$(DD The result is [s<sub>0</sub>, s<sub>1</sub>, ...]
where s<sub>n</sub> is the nth element
formatted with the default format.)
$(DT associative arrays)
$(DD The result is the equivalent of what the initializer
would look like for the contents of the associative array,
e.g.: ["red" : 10, "blue" : 20].)
))
$(DT $(B 'c'))
$(DD The corresponding argument must be a character type.)
$(DT $(B 'b','d','o','x','X'))
$(DD The corresponding argument must be an integral type
and is formatted as an integer. If the argument is a signed type
and the $(I FormatChar) is $(B d) it is converted to
a signed string of characters, otherwise it is treated as
unsigned. An argument of type $(B bool) is formatted as '1'
or '0'. The base used is binary for $(B b), octal for $(B o),
decimal
for $(B d), and hexadecimal for $(B x) or $(B X).
$(B x) formats using lower case letters, $(B X) uppercase.
If there are fewer resulting digits than the $(I Precision),
leading zeros are used as necessary.
If the $(I Precision) is 0 and the number is 0, no digits
result.)
$(DT $(B 'e','E'))
$(DD A floating point number is formatted as one digit before
the decimal point, $(I Precision) digits after, the $(I FormatChar),
±, followed by at least a two digit exponent:
$(I d.dddddd)e$(I ±dd).
If there is no $(I Precision), six
digits are generated after the decimal point.
If the $(I Precision) is 0, no decimal point is generated.)
$(DT $(B 'f','F'))
$(DD A floating point number is formatted in decimal notation.
The $(I Precision) specifies the number of digits generated
after the decimal point. It defaults to six. At least one digit
is generated before the decimal point. If the $(I Precision)
is zero, no decimal point is generated.)
$(DT $(B 'g','G'))
$(DD A floating point number is formatted in either $(B e) or
$(B f) format for $(B g); $(B E) or $(B F) format for
$(B G).
The $(B f) format is used if the exponent for an $(B e) format
is greater than -5 and less than the $(I Precision).
The $(I Precision) specifies the number of significant
digits, and defaults to six.
Trailing zeros are elided after the decimal point, if the fractional
part is zero then no decimal point is generated.)
$(DT $(B 'a','A'))
$(DD A floating point number is formatted in hexadecimal
exponential notation 0x$(I h.hhhhhh)p$(I ±d).
There is one hexadecimal digit before the decimal point, and as
many after as specified by the $(I Precision).
If the $(I Precision) is zero, no decimal point is generated.
If there is no $(I Precision), as many hexadecimal digits as
necessary to exactly represent the mantissa are generated.
The exponent is written in as few digits as possible,
but at least one, is in decimal, and represents a power of 2 as in
$(I h.hhhhhh)*2<sup>$(I ±d)</sup>.
The exponent for zero is zero.
The hexadecimal digits, x and p are in upper case if the
$(I FormatChar) is upper case.)
))
)
Floating point NaN's are formatted as $(B nan) if the
$(I FormatChar) is lower case, or $(B NAN) if upper.
Floating point infinities are formatted as $(B inf) or
$(B infinity) if the
$(I FormatChar) is lower case, or $(B INF) or $(B INFINITY) if upper.
The positional and non-positional styles can be mixed in the same
format string. (POSIX leaves this behavior undefined.) The internal
counter for non-positional parameters tracks the next parameter after
the largest positional parameter already used.
Example using array and nested array formatting:
-------------------------
import std.stdio;
void main()
{
writefln("My items are %(%s %).", [1,2,3]);
writefln("My items are %(%s, %).", [1,2,3]);
}
-------------------------
The output is:
$(CONSOLE
My items are 1 2 3.
My items are 1, 2, 3.
)
The trailing end of the sub-format string following the specifier for each
item is interpreted as the array delimiter, and is therefore omitted
following the last array item. The $(B %|) delimiter specifier may be used
to indicate where the delimiter begins, so that the portion of the format
string prior to it will be retained in the last array element:
-------------------------
import std.stdio;
void main()
{
writefln("My items are %(-%s-%|, %).", [1,2,3]);
}
-------------------------
which gives the output:
$(CONSOLE
My items are -1-, -2-, -3-.
)
These compound format specifiers may be nested in the case of a nested
array argument:
-------------------------
import std.stdio;
void main() {
auto mat = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
writefln("%(%(%d %)\n%)", mat);
writeln();
writefln("[%(%(%d %)\n %)]", mat);
writeln();
writefln("[%([%(%d %)]%|\n %)]", mat);
writeln();
}
-------------------------
The output is:
$(CONSOLE
1 2 3
4 5 6
7 8 9
[1 2 3
4 5 6
7 8 9]
[[1 2 3]
[4 5 6]
[7 8 9]]
)
Inside a compound format specifier, strings and characters are escaped
automatically. To avoid this behavior, add $(B '-') flag to
$(D "%$(LPAREN)").
-------------------------
import std.stdio;
void main()
{
writefln("My friends are %s.", ["John", "Nancy"]);
writefln("My friends are %(%s, %).", ["John", "Nancy"]);
writefln("My friends are %-(%s, %).", ["John", "Nancy"]);
}
-------------------------
which gives the output:
$(CONSOLE
My friends are ["John", "Nancy"].
My friends are "John", "Nancy".
My friends are John, Nancy.
)
*/
uint formattedWrite(alias fmt, Writer, A...)(auto ref Writer w, A args)
if (isSomeString!(typeof(fmt)))
{
alias e = checkFormatException!(fmt, A);
static assert(!e, e.msg);
return .formattedWrite(w, fmt, args);
}
/// The format string can be checked at compile-time (see $(LREF format) for details):
@safe pure unittest
{
import std.array : appender;
auto writer = appender!string();
writer.formattedWrite!"%s is the ultimate %s."(42, "answer");
assert(writer.data == "42 is the ultimate answer.");
// Clear the writer
writer = appender!string();
formattedWrite(writer, "Date: %2$s %1$s", "October", 5);
assert(writer.data == "Date: 5 October");
}
/// ditto
uint formattedWrite(Writer, Char, A...)(auto ref Writer w, in Char[] fmt, A args)
{
import std.conv : text;
auto spec = FormatSpec!Char(fmt);
// Are we already done with formats? Then just dump each parameter in turn
uint currentArg = 0;
while (spec.writeUpToNextSpec(w))
{
if (currentArg == A.length && !spec.indexStart)
{
// leftover spec?
enforceFmt(fmt.length == 0,
text("Orphan format specifier: %", spec.spec));
break;
}
if (spec.width == spec.DYNAMIC)
{
auto width = getNthInt!"integer width"(currentArg, args);
if (width < 0)
{
spec.flDash = true;
width = -width;
}
spec.width = width;
++currentArg;
}
else if (spec.width < 0)
{
// means: get width as a positional parameter
auto index = cast(uint) -spec.width;
assert(index > 0);
auto width = getNthInt!"integer width"(index - 1, args);
if (currentArg < index) currentArg = index;
if (width < 0)
{
spec.flDash = true;
width = -width;
}
spec.width = width;
}
if (spec.precision == spec.DYNAMIC)
{
auto precision = getNthInt!"integer precision"(currentArg, args);
if (precision >= 0) spec.precision = precision;
// else negative precision is same as no precision
else spec.precision = spec.UNSPECIFIED;
++currentArg;
}
else if (spec.precision < 0)
{
// means: get precision as a positional parameter
auto index = cast(uint) -spec.precision;
assert(index > 0);
auto precision = getNthInt!"integer precision"(index- 1, args);
if (currentArg < index) currentArg = index;
if (precision >= 0) spec.precision = precision;
// else negative precision is same as no precision
else spec.precision = spec.UNSPECIFIED;
}
if (spec.separators == spec.DYNAMIC)
{
auto separators = getNthInt!"separator digit width"(currentArg, args);
spec.separators = separators;
++currentArg;
}
if (spec.separatorCharPos == spec.DYNAMIC)
{
auto separatorChar =
getNth!("separator character", isSomeChar, dchar)(currentArg, args);
spec.separatorChar = separatorChar;
++currentArg;
}
if (currentArg == A.length && !spec.indexStart)
{
// leftover spec?
enforceFmt(fmt.length == 0,
text("Orphan format specifier: %", spec.spec));
break;
}
// Format an argument
// This switch uses a static foreach to generate a jump table.
// Currently `spec.indexStart` use the special value '0' to signal
// we should use the current argument. An enhancement would be to
// always store the index.
size_t index = currentArg;
if (spec.indexStart != 0)
index = spec.indexStart - 1;
else
++currentArg;
SWITCH: switch (index)
{
foreach (i, Tunused; A)
{
case i:
formatValue(w, args[i], spec);
if (currentArg < spec.indexEnd)
currentArg = spec.indexEnd;
// A little know feature of format is to format a range
// of arguments, e.g. `%1:3$` will format the first 3
// arguments. Since they have to be consecutive we can
// just use explicit fallthrough to cover that case.
if (i + 1 < spec.indexEnd)
{
// You cannot goto case if the next case is the default
static if (i + 1 < A.length)
goto case;
else
goto default;
}
else
break SWITCH;
}
default:
throw new FormatException(
text("Positional specifier %", spec.indexStart, '$', spec.spec,
" index exceeds ", A.length));
}
}
return currentArg;
}
///
@safe unittest
{
assert(format("%,d", 1000) == "1,000");
assert(format("%,f", 1234567.891011) == "1,234,567.891,011");
assert(format("%,?d", '?', 1000) == "1?000");
assert(format("%,1d", 1000) == "1,0,0,0", format("%,1d", 1000));
assert(format("%,*d", 4, -12345) == "-1,2345");
assert(format("%,*?d", 4, '_', -12345) == "-1_2345");
assert(format("%,6?d", '_', -12345678) == "-12_345678");
assert(format("%12,3.3f", 1234.5678) == " 1,234.568", "'" ~
format("%12,3.3f", 1234.5678) ~ "'");
}
@safe pure unittest
{
import std.array;
auto w = appender!string();
formattedWrite(w, "%s %d", "@safe/pure", 42);
assert(w.data == "@safe/pure 42");
}
/**
Reads characters from input range $(D r), converts them according
to $(D fmt), and writes them to $(D args).
Params:
r = The range to read from.
fmt = The format of the data to read.
args = The drain of the data read.
Returns:
On success, the function returns the number of variables filled. This count
can match the expected number of readings or fewer, even zero, if a
matching failure happens.
Throws:
An `Exception` if `S.length == 0` and `fmt` has format specifiers.
*/
uint formattedRead(alias fmt, R, S...)(auto ref R r, auto ref S args)
if (isSomeString!(typeof(fmt)))
{
alias e = checkFormatException!(fmt, S);
static assert(!e, e.msg);
return .formattedRead(r, fmt, args);
}
/// ditto
uint formattedRead(R, Char, S...)(auto ref R r, const(Char)[] fmt, auto ref S args)
{
import std.typecons : isTuple;
auto spec = FormatSpec!Char(fmt);
static if (!S.length)
{
spec.readUpToNextSpec(r);
enforce(spec.trailing.empty, "Trailing characters in formattedRead format string");
return 0;
}
else
{
enum hasPointer = isPointer!(typeof(args[0]));
// The function below accounts for '*' == fields meant to be
// read and skipped
void skipUnstoredFields()
{
for (;;)
{
spec.readUpToNextSpec(r);
if (spec.width != spec.DYNAMIC) break;
// must skip this field
skipData(r, spec);
}
}
skipUnstoredFields();
if (r.empty)
{
// Input is empty, nothing to read
return 0;
}
static if (hasPointer)
alias A = typeof(*args[0]);
else
alias A = typeof(args[0]);
static if (isTuple!A)
{
foreach (i, T; A.Types)
{
static if (hasPointer)
(*args[0])[i] = unformatValue!(T)(r, spec);
else
args[0][i] = unformatValue!(T)(r, spec);
skipUnstoredFields();
}
}
else
{
static if (hasPointer)
*args[0] = unformatValue!(A)(r, spec);
else
args[0] = unformatValue!(A)(r, spec);
}
return 1 + formattedRead(r, spec.trailing, args[1 .. $]);
}
}
/// The format string can be checked at compile-time (see $(LREF format) for details):
@safe pure unittest
{
string s = "hello!124:34.5";
string a;
int b;
double c;
s.formattedRead!"%s!%s:%s"(a, b, c);
assert(a == "hello" && b == 124 && c == 34.5);
}
@safe unittest
{
import std.math;
string s = " 1.2 3.4 ";
double x, y, z;
assert(formattedRead(s, " %s %s %s ", x, y, z) == 2);
assert(s.empty);
assert(approxEqual(x, 1.2));
assert(approxEqual(y, 3.4));
assert(isNaN(z));
}
// for backwards compatibility
@system pure unittest
{
string s = "hello!124:34.5";
string a;
int b;
double c;
formattedRead(s, "%s!%s:%s", &a, &b, &c);
assert(a == "hello" && b == 124 && c == 34.5);
// mix pointers and auto-ref
s = "world!200:42.25";
formattedRead(s, "%s!%s:%s", a, &b, &c);
assert(a == "world" && b == 200 && c == 42.25);
s = "world1!201:42.5";
formattedRead(s, "%s!%s:%s", &a, &b, c);
assert(a == "world1" && b == 201 && c == 42.5);
s = "world2!202:42.75";
formattedRead(s, "%s!%s:%s", a, b, &c);
assert(a == "world2" && b == 202 && c == 42.75);
}
// for backwards compatibility
@system pure unittest
{
import std.math;
string s = " 1.2 3.4 ";
double x, y, z;
assert(formattedRead(s, " %s %s %s ", &x, &y, &z) == 2);
assert(s.empty);
assert(approxEqual(x, 1.2));
assert(approxEqual(y, 3.4));
assert(isNaN(z));
}
@system pure unittest
{
string line;
bool f1;
line = "true";
formattedRead(line, "%s", &f1);
assert(f1);
line = "TrUE";
formattedRead(line, "%s", &f1);
assert(f1);
line = "false";
formattedRead(line, "%s", &f1);
assert(!f1);
line = "fALsE";
formattedRead(line, "%s", &f1);
assert(!f1);
line = "1";
formattedRead(line, "%d", &f1);
assert(f1);
line = "-1";
formattedRead(line, "%d", &f1);
assert(f1);
line = "0";
formattedRead(line, "%d", &f1);
assert(!f1);
line = "-0";
formattedRead(line, "%d", &f1);
assert(!f1);
}
@system pure unittest
{
union B
{
char[int.sizeof] untyped;
int typed;
}
B b;
b.typed = 5;
char[] input = b.untyped[];
int witness;
formattedRead(input, "%r", &witness);
assert(witness == b.typed);
}
@system pure unittest
{
union A
{
char[float.sizeof] untyped;
float typed;
}
A a;
a.typed = 5.5;
char[] input = a.untyped[];
float witness;
formattedRead(input, "%r", &witness);
assert(witness == a.typed);
}
@system pure unittest
{
import std.typecons;
char[] line = "1 2".dup;
int a, b;
formattedRead(line, "%s %s", &a, &b);
assert(a == 1 && b == 2);
line = "10 2 3".dup;
formattedRead(line, "%d ", &a);
assert(a == 10);
assert(line == "2 3");
Tuple!(int, float) t;
line = "1 2.125".dup;
formattedRead(line, "%d %g", &t);
assert(t[0] == 1 && t[1] == 2.125);
line = "1 7643 2.125".dup;
formattedRead(line, "%s %*u %s", &t);
assert(t[0] == 1 && t[1] == 2.125);
}
@system pure unittest
{
string line;
char c1, c2;
line = "abc";
formattedRead(line, "%s%c", &c1, &c2);
assert(c1 == 'a' && c2 == 'b');
assert(line == "c");
}
@system pure unittest
{
string line;
line = "[1,2,3]";
int[] s1;
formattedRead(line, "%s", &s1);
assert(s1 == [1,2,3]);
}
@system pure unittest
{
string line;
line = "[1,2,3]";
int[] s1;
formattedRead(line, "[%(%s,%)]", &s1);
assert(s1 == [1,2,3]);
line = `["hello", "world"]`;
string[] s2;
formattedRead(line, "[%(%s, %)]", &s2);
assert(s2 == ["hello", "world"]);
line = "123 456";
int[] s3;
formattedRead(line, "%(%s %)", &s3);
assert(s3 == [123, 456]);
line = "h,e,l,l,o; w,o,r,l,d";
string[] s4;
formattedRead(line, "%(%(%c,%); %)", &s4);
assert(s4 == ["hello", "world"]);
}
@system pure unittest
{
string line;
int[4] sa1;
line = `[1,2,3,4]`;
formattedRead(line, "%s", &sa1);
assert(sa1 == [1,2,3,4]);
int[4] sa2;
line = `[1,2,3]`;
assertThrown(formattedRead(line, "%s", &sa2));
int[4] sa3;
line = `[1,2,3,4,5]`;
assertThrown(formattedRead(line, "%s", &sa3));
}
@system pure unittest
{
string input;
int[4] sa1;
input = `[1,2,3,4]`;
formattedRead(input, "[%(%s,%)]", &sa1);
assert(sa1 == [1,2,3,4]);
int[4] sa2;
input = `[1,2,3]`;
assertThrown(formattedRead(input, "[%(%s,%)]", &sa2));
}
@system pure unittest
{
string line;
string s1, s2;
line = "hello, world";
formattedRead(line, "%s", &s1);
assert(s1 == "hello, world", s1);
line = "hello, world;yah";
formattedRead(line, "%s;%s", &s1, &s2);
assert(s1 == "hello, world", s1);
assert(s2 == "yah", s2);
line = `['h','e','l','l','o']`;
string s3;
formattedRead(line, "[%(%s,%)]", &s3);
assert(s3 == "hello");
line = `"hello"`;
string s4;
formattedRead(line, "\"%(%c%)\"", &s4);
assert(s4 == "hello");
}
@system pure unittest
{
string line;
string[int] aa1;
line = `[1:"hello", 2:"world"]`;
formattedRead(line, "%s", &aa1);
assert(aa1 == [1:"hello", 2:"world"]);
int[string] aa2;
line = `{"hello"=1; "world"=2}`;
formattedRead(line, "{%(%s=%s; %)}", &aa2);
assert(aa2 == ["hello":1, "world":2]);
int[string] aa3;
line = `{[hello=1]; [world=2]}`;
formattedRead(line, "{%([%(%c%)=%s]%|; %)}", &aa3);
assert(aa3 == ["hello":1, "world":2]);
}
// test rvalue using
@system pure unittest
{
string[int] aa1;
formattedRead!("%s")(`[1:"hello", 2:"world"]`, aa1);
assert(aa1 == [1:"hello", 2:"world"]);
int[string] aa2;
formattedRead(`{"hello"=1; "world"=2}`, "{%(%s=%s; %)}", aa2);
assert(aa2 == ["hello":1, "world":2]);
}
template FormatSpec(Char)
if (!is(Unqual!Char == Char))
{
alias FormatSpec = FormatSpec!(Unqual!Char);
}
/**
* A General handler for $(D printf) style format specifiers. Used for building more