forked from ldc-developers/phobos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat.d
6699 lines (5918 loc) · 193 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 $(D $(LREF formattedRead)))
$(TD Reads values according to the _format string from an InputRange.
))
$(TR $(TD $(D $(LREF formattedWrite)))
$(TD Formats its arguments according to the _format string and puts them
to an OutputRange.
))
)
Please see the documentation of function $(D $(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 $(D $(LREF _format)))
$(TD Returns a GC-allocated string with the formatting result.
))
$(TR $(TD $(D $(LREF sformat)))
$(TD Puts the formatting result into a preallocated array.
))
)
These two functions are publicly imported by $(LINK2 std_string.html,
std.string) to be easily available.
The functions $(D $(LREF formatValue)) and $(D $(LREF unformatValue)) are
used for the plumbing.
Macros: WIKI = Phobos/StdFormat
Copyright: Copyright Digital Mars 2000-2013.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(WEB walterbright.com, Walter Bright), $(WEB 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.range.primitives;
import std.traits;
import std.typetuple;
version(CRuntime_DigitalMars)
{
version = DigitalMarsC;
}
version (DigitalMarsC)
{
// This is DMC's internal floating point formatting function
extern (C)
{
extern shared char* function(int c, int flags, int precision,
in real* pdval,
char* buf, size_t* psl, int width) __pfloatfmt;
}
}
/**********************************************************************
* 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 $(XREF range,isOutputRange!(Writer, Char)).
The variadic arguments are normally consumed in order. POSIX-style
$(WEB 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
$(XREF array,Appender!string) and $(XREF stdio,LockingTextWriter).
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 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 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')
)
$(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 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 <tt>'true'</tt> or <tt>'false'</tt>.
<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].
</dl>
<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.
</dl>
</dl>
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.
Examples:
-------------------------
import std.array;
import std.format;
void main()
{
auto writer = appender!string();
formattedWrite(writer, "%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");
}
------------------------
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:
<pre class=console>
My items are 1 2 3.
My items are 1, 2, 3.
</pre>
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:
<pre class=console>
My items are -1-, -2-, -3-.
</pre>
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:
<pre class=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]]
</pre>
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:
<pre class=console>
My friends are ["John", "Nancy"].
My friends are "John", "Nancy".
My friends are John, Nancy.
</pre>
*/
uint formattedWrite(Writer, Char, A...)(Writer w, in Char[] fmt, A args)
{
import std.conv : text, to;
alias FPfmt = void function(Writer, const(void)*, ref FormatSpec!Char) @safe pure nothrow;
auto spec = FormatSpec!Char(fmt);
FPfmt[A.length] funs;
const(void)*[A.length] argsAddresses;
if (!__ctfe)
{
foreach (i, Arg; A)
{
funs[i] = ()@trusted{ return cast(FPfmt)&formatGeneric!(Writer, Arg, Char); }();
// We can safely cast away shared because all data is either
// immutable or completely owned by this function.
argsAddresses[i] = (ref arg)@trusted{ return cast(const void*) &arg; }(args[i]);
// Reflect formatting @safe/pure ability of each arguments to this function
if (0) formatValue(w, args[i], spec);
}
}
// Are we already done with formats? Then just dump each parameter in turn
uint currentArg = 0;
while (spec.writeUpToNextSpec(w))
{
if (currentArg == funs.length && !spec.indexStart)
{
// leftover spec?
enforceFmt(fmt.length == 0,
text("Orphan format specifier: %", spec.spec));
break;
}
if (spec.width == spec.DYNAMIC)
{
auto width = to!(typeof(spec.width))(getNthInt(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 = to!(typeof(spec.width))(getNthInt(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 = to!(typeof(spec.precision))(
getNthInt(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 = to!(typeof(spec.precision))(
getNthInt(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;
}
// Format!
if (spec.indexStart > 0)
{
// using positional parameters!
foreach (i; spec.indexStart - 1 .. spec.indexEnd)
{
if (funs.length <= i) break;
if (__ctfe)
formatNth(w, spec, i, args);
else
funs[i](w, argsAddresses[i], spec);
}
if (currentArg < spec.indexEnd) currentArg = spec.indexEnd;
}
else
{
if (__ctfe)
formatNth(w, spec, currentArg, args);
else
funs[currentArg](w, argsAddresses[currentArg], spec);
++currentArg;
}
}
return currentArg;
}
@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.
*/
uint formattedRead(R, Char, S...)(ref R r, const(Char)[] fmt, S args)
{
import std.typecons : isTuple;
auto spec = FormatSpec!Char(fmt);
static if (!S.length)
{
spec.readUpToNextSpec(r);
enforce(spec.trailing.empty);
return 0;
}
else
{
// 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;
}
alias A = typeof(*args[0]);
static if (isTuple!A)
{
foreach (i, T; A.Types)
{
(*args[0])[i] = unformatValue!(T)(r, spec);
skipUnstoredFields();
}
}
else
{
*args[0] = unformatValue!(A)(r, spec);
}
return 1 + formattedRead(r, spec.trailing, args[1 .. $]);
}
}
///
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);
}
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));
}
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
* specific formatting functions.
*/
struct FormatSpec(Char)
if (is(Unqual!Char == Char))
{
import std.ascii : isDigit;
import std.algorithm : startsWith;
import std.conv : parse, text, to;
/**
Minimum _width, default $(D 0).
*/
int width = 0;
/**
Precision. Its semantics depends on the argument type. For
floating point numbers, _precision dictates the number of
decimals printed.
*/
int precision = UNSPECIFIED;
/**
Special value for width and precision. $(D DYNAMIC) width or
precision means that they were specified with $(D '*') in the
format string and are passed at runtime through the varargs.
*/
enum int DYNAMIC = int.max;
/**
Special value for precision, meaning the format specifier
contained no explicit precision.
*/
enum int UNSPECIFIED = DYNAMIC - 1;
/**
The actual format specifier, $(D 's') by default.
*/
char spec = 's';
/**
Index of the argument for positional parameters, from $(D 1) to
$(D ubyte.max). ($(D 0) means not used).
*/
ubyte indexStart;
/**
Index of the last argument for positional parameter range, from
$(D 1) to $(D ubyte.max). ($(D 0) means not used).
*/
ubyte indexEnd;
version(StdDdoc)
{
/**
The format specifier contained a $(D '-') ($(D printf)
compatibility).
*/
bool flDash;
/**
The format specifier contained a $(D '0') ($(D printf)
compatibility).
*/
bool flZero;
/**
The format specifier contained a $(D ' ') ($(D printf)
compatibility).
*/
bool flSpace;
/**
The format specifier contained a $(D '+') ($(D printf)
compatibility).
*/
bool flPlus;
/**
The format specifier contained a $(D '#') ($(D printf)
compatibility).
*/
bool flHash;
// Fake field to allow compilation
ubyte allFlags;
}
else
{
union
{
import std.bitmanip : bitfields;
mixin(bitfields!(
bool, "flDash", 1,
bool, "flZero", 1,
bool, "flSpace", 1,
bool, "flPlus", 1,
bool, "flHash", 1,
ubyte, "", 3));
ubyte allFlags;
}
}
/**
In case of a compound format specifier starting with $(D
"%$(LPAREN)") and ending with $(D "%$(RPAREN)"), $(D _nested)
contains the string contained within the two separators.
*/
const(Char)[] nested;
/**
In case of a compound format specifier, $(D _sep) contains the
string positioning after $(D "%|").
*/
const(Char)[] sep;
/**
$(D _trailing) contains the rest of the format string.
*/
const(Char)[] trailing;
/*
This string is inserted before each sequence (e.g. array)
formatted (by default $(D "[")).
*/
enum immutable(Char)[] seqBefore = "[";
/*
This string is inserted after each sequence formatted (by
default $(D "]")).
*/
enum immutable(Char)[] seqAfter = "]";
/*
This string is inserted after each element keys of a sequence (by
default $(D ":")).
*/
enum immutable(Char)[] keySeparator = ":";
/*
This string is inserted in between elements of a sequence (by
default $(D ", ")).
*/
enum immutable(Char)[] seqSeparator = ", ";
/**
Construct a new $(D FormatSpec) using the format string $(D fmt), no
processing is done until needed.
*/
this(in Char[] fmt) @safe pure
{
trailing = fmt;
}
bool writeUpToNextSpec(OutputRange)(OutputRange writer)
{
if (trailing.empty)
return false;
for (size_t i = 0; i < trailing.length; ++i)
{
if (trailing[i] != '%') continue;
put(writer, trailing[0 .. i]);
trailing = trailing[i .. $];
enforceFmt(trailing.length >= 2, `Unterminated format specifier: "%"`);
trailing = trailing[1 .. $];
if (trailing[0] != '%')
{
// Spec found. Fill up the spec, and bailout
fillUp();
return true;
}
// Doubled! Reset and Keep going
i = 0;
}
// no format spec found
put(writer, trailing);
trailing = null;
return false;
}
unittest
{
import std.array;
auto w = appender!(char[])();
auto f = FormatSpec("abc%sdef%sghi");
f.writeUpToNextSpec(w);
assert(w.data == "abc", w.data);
assert(f.trailing == "def%sghi", text(f.trailing));
f.writeUpToNextSpec(w);
assert(w.data == "abcdef", w.data);
assert(f.trailing == "ghi");
// test with embedded %%s
f = FormatSpec("ab%%cd%%ef%sg%%h%sij");
w.clear();
f.writeUpToNextSpec(w);
assert(w.data == "ab%cd%ef" && f.trailing == "g%%h%sij", w.data);
f.writeUpToNextSpec(w);
assert(w.data == "ab%cd%efg%h" && f.trailing == "ij");
// bug4775
f = FormatSpec("%%%s");
w.clear();
f.writeUpToNextSpec(w);
assert(w.data == "%" && f.trailing == "");
f = FormatSpec("%%%%%s%%");
w.clear();
while (f.writeUpToNextSpec(w)) continue;
assert(w.data == "%%%");
f = FormatSpec("a%%b%%c%");
w.clear();
assertThrown!FormatException(f.writeUpToNextSpec(w));
assert(w.data == "a%b%c" && f.trailing == "%");
}
private void fillUp()
{
// Reset content
if (__ctfe)
{
flDash = false;
flZero = false;
flSpace = false;
flPlus = false;
flHash = false;
}
else
{
allFlags = 0;
}
width = 0;
precision = UNSPECIFIED;
nested = null;
// Parse the spec (we assume we're past '%' already)
for (size_t i = 0; i < trailing.length; )
{
switch (trailing[i])
{
case '(':
// Embedded format specifier.
auto j = i + 1;
// Get the matching balanced paren
for (uint innerParens;;)
{
enforceFmt(j + 1 < trailing.length,
text("Incorrect format specifier: %", trailing[i .. $]));
if (trailing[j++] != '%')
{
// skip, we're waiting for %( and %)
continue;
}
if (trailing[j] == '-') // for %-(
{
++j; // skip
enforceFmt(j < trailing.length,
text("Incorrect format specifier: %", trailing[i .. $]));
}
if (trailing[j] == ')')
{
if (innerParens-- == 0) break;
}
else if (trailing[j] == '|')
{
if (innerParens == 0) break;
}
else if (trailing[j] == '(')
{
++innerParens;
}
}
if (trailing[j] == '|')
{
auto k = j;
for (++j;;)
{
if (trailing[j++] != '%')
continue;
if (trailing[j] == '%')
++j;
else if (trailing[j] == ')')
break;
else
throw new Exception(
text("Incorrect format specifier: %",
trailing[j .. $]));
}
nested = trailing[i + 1 .. k - 1];
sep = trailing[k + 1 .. j - 1];
}
else
{
nested = trailing[i + 1 .. j - 1];
sep = null; // use null (issue 12135)
}
//this = FormatSpec(innerTrailingSpec);
spec = '(';
// We practically found the format specifier
trailing = trailing[j + 1 .. $];
return;
case '-': flDash = true; ++i; break;
case '+': flPlus = true; ++i; break;
case '#': flHash = true; ++i; break;
case '0': flZero = true; ++i; break;
case ' ': flSpace = true; ++i; break;
case '*':
if (isDigit(trailing[++i]))
{
// a '*' followed by digits and '$' is a
// positional format
trailing = trailing[1 .. $];
width = -parse!(typeof(width))(trailing);
i = 0;
enforceFmt(trailing[i++] == '$',
"$ expected");
}
else
{
// read result
width = DYNAMIC;
}
break;
case '1': .. case '9':
auto tmp = trailing[i .. $];
const widthOrArgIndex = parse!uint(tmp);
enforceFmt(tmp.length,
text("Incorrect format specifier %", trailing[i .. $]));
i = tmp.ptr - trailing.ptr;
if (tmp.startsWith('$'))
{
// index of the form %n$
indexEnd = indexStart = to!ubyte(widthOrArgIndex);
++i;
}
else if (tmp.startsWith(':'))
{