Debian Codegraph @

libphobos/src/std/format/write.d

raw
1 // Written in the D programming language.
2
3 /**
4 This is a submodule of $(MREF std, format).
5
6 It provides two functions for writing formatted output: $(LREF
7 formatValue) and $(LREF formattedWrite). The former writes a single
8 value. The latter writes several values at once, interspersed with
9 unformatted text.
10
11 The following combinations of format characters and types are
12 available:
13
14 $(BOOKTABLE ,
15 $(TR $(TH) $(TH s) $(TH c) $(TH d, u, b, o) $(TH x, X) $(TH e, E, f, F, g, G, a, A) $(TH r) $(TH compound))
16 $(TR $(TD `bool`) $(TD yes) $(TD $(MDASH)) $(TD yes) $(TD yes) $(TD $(MDASH)) $(TD yes) $(TD $(MDASH)))
17 $(TR $(TD `null`) $(TD yes) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)))
18 $(TR $(TD $(I integer)) $(TD yes) $(TD $(MDASH)) $(TD yes) $(TD yes) $(TD yes) $(TD yes) $(TD $(MDASH)))
19 $(TR $(TD $(I floating point)) $(TD yes) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD yes) $(TD yes) $(TD $(MDASH)))
20 $(TR $(TD $(I character)) $(TD yes) $(TD yes) $(TD yes) $(TD yes) $(TD $(MDASH)) $(TD yes) $(TD $(MDASH)))
21 $(TR $(TD $(I string)) $(TD yes) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD yes) $(TD yes))
22 $(TR $(TD $(I array)) $(TD yes) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD yes) $(TD yes))
23 $(TR $(TD $(I associative array)) $(TD yes) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD yes))
24 $(TR $(TD $(I pointer)) $(TD yes) $(TD $(MDASH)) $(TD $(MDASH)) $(TD yes) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)))
25 $(TR $(TD $(I SIMD vectors)) $(TD yes) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD yes) $(TD yes))
26 $(TR $(TD $(I delegates)) $(TD yes) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD $(MDASH)) $(TD yes) $(TD yes))
27 )
28
29 Enums can be used with all format characters of the base type.
30
31 $(H3 $(LNAME2 aggregates, Structs, Unions, Classes, and Interfaces))
32
33 Aggregate types can define various `toString` functions. If this
34 function takes a $(REF_ALTTEXT FormatSpec, FormatSpec, std, format,
35 spec) or a $(I format string) as argument, the function decides
36 which format characters are accepted. If no `toString` is defined and
37 the aggregate is an $(REF_ALTTEXT input range, isInputRange, std,
38 range, primitives), it is treated like a range, that is $(B 's'), $(B
39 'r') and a compound specifier are accepted. In all other cases
40 aggregate types only accept $(B 's').
41
42 `toString` should have one of the following signatures:
43
44 ---
45 void toString(Writer, Char)(ref Writer w, const ref FormatSpec!Char fmt)
46 void toString(Writer)(ref Writer w)
47 string toString();
48 ---
49
50 Where `Writer` is an $(REF_ALTTEXT output range, isOutputRange,
51 std,range,primitives) which accepts characters $(LPAREN)of type
52 `Char` in the first version$(RPAREN). The template type does not have
53 to be called `Writer`.
54
55 Sometimes it's not possible to use a template, for example when
56 `toString` overrides `Object.toString`. In this case, the following
57 $(LPAREN)slower and less flexible$(RPAREN) functions can be used:
58
59 ---
60 void toString(void delegate(const(char)[]) sink, const ref FormatSpec!char fmt);
61 void toString(void delegate(const(char)[]) sink, string fmt);
62 void toString(void delegate(const(char)[]) sink);
63 ---
64
65 When several of the above `toString` versions are available, the
66 versions with `Writer` take precedence over the versions with a
67 `sink`. `string toString()` has the lowest priority.
68
69 If none of the above mentioned `toString` versions are available, the
70 aggregates will be formatted by other means, in the following
71 order:
72
73 If an aggregate is an $(REF_ALTTEXT input range, isInputRange, std,
74 range, primitives), it is formatted like an input range.
75
76 If an aggregate is a builtin type (using `alias this`), it is formatted
77 like the builtin type.
78
79 If all else fails, structs are formatted like `Type(field1, field2, ...)`,
80 classes and interfaces are formatted with their fully qualified name
81 and unions with their base name.
82
83 Copyright: Copyright The D Language Foundation 2000-2013.
84
85 License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
86
87 Authors: $(HTTP walterbright.com, Walter Bright), $(HTTP erdani.com,
88 Andrei Alexandrescu), and Kenji Hara
89
90 Source: $(PHOBOSSRC std/format/write.d)
91 */
92 module std.format.write;
93
94 /**
95 `bool`s are formatted as `"true"` or `"false"` with `%s` and like the
96 `byte`s 1 and 0 with all other format characters.
97 */
98 @safe pure unittest
99 {
100 import std.array : appender;
101 import std.format.spec : singleSpec;
102
103 auto w1 = appender!string();
104 auto spec1 = singleSpec("%s");
105 formatValue(w1, true, spec1);
106
107 assert(w1.data == "true");
108
109 auto w2 = appender!string();
110 auto spec2 = singleSpec("%#x");
111 formatValue(w2, true, spec2);
112
113 assert(w2.data == "0x1");
114 }
115
116 /// The `null` literal is formatted as `"null"`.
117 @safe pure unittest
118 {
119 import std.array : appender;
120 import std.format.spec : singleSpec;
121
122 auto w = appender!string();
123 auto spec = singleSpec("%s");
124 formatValue(w, null, spec);
125
126 assert(w.data == "null");
127 }
128
129 /**
130 Integrals are formatted in (signed) every day notation with `%s` and
131 `%d` and as an (unsigned) image of the underlying bit representation
132 with `%b` (binary), `%u` (decimal), `%o` (octal), and `%x` (hexadecimal).
133 */
134 @safe pure unittest
135 {
136 import std.array : appender;
137 import std.format.spec : singleSpec;
138
139 auto w1 = appender!string();
140 auto spec1 = singleSpec("%d");
141 formatValue(w1, -1337, spec1);
142
143 assert(w1.data == "-1337");
144
145 auto w2 = appender!string();
146 auto spec2 = singleSpec("%x");
147 formatValue(w2, -1337, spec2);
148
149 assert(w2.data == "fffffac7");
150 }
151
152 /**
153 Floating-point values are formatted in natural notation with `%f`, in
154 scientific notation with `%e`, in short notation with `%g`, and in
155 hexadecimal scientific notation with `%a`. If a rounding mode is
156 available, they are rounded according to this rounding mode, otherwise
157 they are rounded to the nearest value, ties to even.
158 */
159 @safe unittest
160 {
161 import std.array : appender;
162 import std.format.spec : singleSpec;
163
164 auto w1 = appender!string();
165 auto spec1 = singleSpec("%.3f");
166 formatValue(w1, 1337.7779, spec1);
167
168 assert(w1.data == "1337.778");
169
170 auto w2 = appender!string();
171 auto spec2 = singleSpec("%.3e");
172 formatValue(w2, 1337.7779, spec2);
173
174 assert(w2.data == "1.338e+03");
175
176 auto w3 = appender!string();
177 auto spec3 = singleSpec("%.3g");
178 formatValue(w3, 1337.7779, spec3);
179
180 assert(w3.data == "1.34e+03");
181
182 auto w4 = appender!string();
183 auto spec4 = singleSpec("%.3a");
184 formatValue(w4, 1337.7779, spec4);
185
186 assert(w4.data == "0x1.4e7p+10");
187 }
188
189 /**
190 Individual characters (`char`, `wchar`, or `dchar`) are formatted as
191 Unicode characters with `%s` and `%c` and as integers (`ubyte`,
192 `ushort`, `uint`) with all other format characters. With
193 $(MREF_ALTTEXT compound specifiers, std,format) characters are
194 treated differently.
195 */
196 @safe pure unittest
197 {
198 import std.array : appender;
199 import std.format.spec : singleSpec;
200
201 auto w1 = appender!string();
202 auto spec1 = singleSpec("%c");
203 formatValue(w1, 'ì', spec1);
204
205 assert(w1.data == "ì");
206
207 auto w2 = appender!string();
208 auto spec2 = singleSpec("%#x");
209 formatValue(w2, 'ì', spec2);
210
211 assert(w2.data == "0xec");
212 }
213
214 /**
215 Strings are formatted as a sequence of characters with `%s`.
216 Non-printable characters are not escaped. With a compound specifier
217 the string is treated like a range of characters. With $(MREF_ALTTEXT
218 compound specifiers, std,format) strings are treated differently.
219 */
220 @safe pure unittest
221 {
222 import std.array : appender;
223 import std.format.spec : singleSpec;
224
225 auto w1 = appender!string();
226 auto spec1 = singleSpec("%s");
227 formatValue(w1, "hello", spec1);
228
229 assert(w1.data == "hello");
230
231 auto w2 = appender!string();
232 auto spec2 = singleSpec("%(%#x%|/%)");
233 formatValue(w2, "hello", spec2);
234
235 assert(w2.data == "0x68/0x65/0x6c/0x6c/0x6f");
236 }
237
238 /// Static arrays are formatted as dynamic arrays.
239 @safe pure unittest
240 {
241 import std.array : appender;
242 import std.format.spec : singleSpec;
243
244 auto w = appender!string();
245 auto spec = singleSpec("%s");
246 int[2] two = [1, 2];
247 formatValue(w, two, spec);
248
249 assert(w.data == "[1, 2]");
250 }
251
252 /**
253 Dynamic arrays are formatted as input ranges.
254 */
255 @safe pure unittest
256 {
257 import std.array : appender;
258 import std.format.spec : singleSpec;
259
260 auto w1 = appender!string();
261 auto spec1 = singleSpec("%s");
262 auto two = [1, 2];
263 formatValue(w1, two, spec1);
264
265 assert(w1.data == "[1, 2]");
266
267 auto w2 = appender!string();
268 auto spec2 = singleSpec("%(%g%|, %)");
269 auto consts = [3.1415926, 299792458, 6.67430e-11];
270 formatValue(w2, consts, spec2);
271
272 assert(w2.data == "3.14159, 2.99792e+08, 6.6743e-11");
273
274 // void[] is treated like ubyte[]
275 auto w3 = appender!string();
276 auto spec3 = singleSpec("%s");
277 void[] val = cast(void[]) cast(ubyte[])[1, 2, 3];
278 formatValue(w3, val, spec3);
279
280 assert(w3.data == "[1, 2, 3]");
281 }
282
283 /**
284 Associative arrays are formatted by using `':'` and `", "` as
285 separators, enclosed by `'['` and `']'` when used with `%s`. It's
286 also possible to use a compound specifier for better control.
287
288 Please note, that the order of the elements is not defined, therefore
289 the result of this function might differ.
290 */
291 @safe pure unittest
292 {
293 import std.array : appender;
294 import std.format.spec : singleSpec;
295
296 auto aa = [10:17.5, 20:9.99];
297
298 auto w1 = appender!string();
299 auto spec1 = singleSpec("%s");
300 formatValue(w1, aa, spec1);
301
302 assert(w1.data == "[10:17.5, 20:9.99]" || w1.data == "[20:9.99, 10:17.5]");
303
304 auto w2 = appender!string();
305 auto spec2 = singleSpec("%(%x = %.0e%| # %)");
306 formatValue(w2, aa, spec2);
307
308 assert(w2.data == "a = 2e+01 # 14 = 1e+01" || w2.data == "14 = 1e+01 # a = 2e+01");
309 }
310
311 /**
312 `enum`s are formatted as their name when used with `%s` and like
313 their base value else.
314 */
315 @safe pure unittest
316 {
317 import std.array : appender;
318 import std.format.spec : singleSpec;
319
320 enum A { first, second, third }
321
322 auto w1 = appender!string();
323 auto spec1 = singleSpec("%s");
324 formatValue(w1, A.second, spec1);
325
326 assert(w1.data == "second");
327
328 auto w2 = appender!string();
329 auto spec2 = singleSpec("%d");
330 formatValue(w2, A.second, spec2);
331
332 assert(w2.data == "1");
333
334 // values of an enum that have no name are formatted with %s using a cast
335 A a = A.third;
336 a++;
337
338 auto w3 = appender!string();
339 auto spec3 = singleSpec("%s");
340 formatValue(w3, a, spec3);
341
342 assert(w3.data == "cast(A)3");
343 }
344
345 /**
346 `structs`, `unions`, `classes` and `interfaces` can be formatted in
347 several different ways. The following example highlights `struct`
348 formatting, however, it applies to other aggregates as well.
349 */
350 @safe unittest
351 {
352 import std.array : appender;
353 import std.format.spec : FormatSpec, singleSpec;
354
355 // Using a `toString` with a writer
356 static struct Point1
357 {
358 import std.range.primitives : isOutputRange, put;
359
360 int x, y;
361
362 void toString(W)(ref W writer, scope const ref FormatSpec!char f)
363 if (isOutputRange!(W, char))
364 {
365 put(writer, "(");
366 formatValue(writer, x, f);
367 put(writer, ",");
368 formatValue(writer, y, f);
369 put(writer, ")");
370 }
371 }
372
373 auto w1 = appender!string();
374 auto spec1 = singleSpec("%s");
375 auto p1 = Point1(16, 11);
376
377 formatValue(w1, p1, spec1);
378 assert(w1.data == "(16,11)");
379
380 // Using a `toString` with a sink
381 static struct Point2
382 {
383 int x, y;
384
385 void toString(scope void delegate(scope const(char)[]) @safe sink,
386 scope const FormatSpec!char fmt) const
387 {
388 sink("(");
389 sink.formatValue(x, fmt);
390 sink(",");
391 sink.formatValue(y, fmt);
392 sink(")");
393 }
394 }
395
396 auto w2 = appender!string();
397 auto spec2 = singleSpec("%03d");
398 auto p2 = Point2(16,11);
399
400 formatValue(w2, p2, spec2);
401 assert(w2.data == "(016,011)");
402
403 // Using `string toString()`
404 static struct Point3
405 {
406 int x, y;
407
408 string toString()
409 {
410 import std.conv : to;
411
412 return "(" ~ to!string(x) ~ "," ~ to!string(y) ~ ")";
413 }
414 }
415
416 auto w3 = appender!string();
417 auto spec3 = singleSpec("%s"); // has to be %s
418 auto p3 = Point3(16,11);
419
420 formatValue(w3, p3, spec3);
421 assert(w3.data == "(16,11)");
422
423 // without `toString`
424 static struct Point4
425 {
426 int x, y;
427 }
428
429 auto w4 = appender!string();
430 auto spec4 = singleSpec("%s"); // has to be %s
431 auto p4 = Point4(16,11);
432
433 formatValue(w4, p4, spec3);
434 assert(w4.data == "Point4(16, 11)");
435 }
436
437 /// Pointers are formatted as hexadecimal integers.
438 @safe pure unittest
439 {
440 import std.array : appender;
441 import std.format.spec : singleSpec;
442
443 auto w1 = appender!string();
444 auto spec1 = singleSpec("%s");
445 auto p1 = () @trusted { return cast(void*) 0xFFEECCAA; } ();
446 formatValue(w1, p1, spec1);
447
448 assert(w1.data == "FFEECCAA");
449
450 // null pointers are printed as `"null"` when used with `%s` and as hexadecimal integer else
451 auto w2 = appender!string();
452 auto spec2 = singleSpec("%s");
453 auto p2 = () @trusted { return cast(void*) 0x00000000; } ();
454 formatValue(w2, p2, spec2);
455
456 assert(w2.data == "null");
457
458 auto w3 = appender!string();
459 auto spec3 = singleSpec("%x");
460 formatValue(w3, p2, spec3);
461
462 assert(w3.data == "0");
463 }
464
465 /// SIMD vectors are formatted as arrays.
466 @safe unittest
467 {
468 import core.simd; // cannot be selective, because float4 might not be defined
469 import std.array : appender;
470 import std.format.spec : singleSpec;
471
472 auto w = appender!string();
473 auto spec = singleSpec("%s");
474
475 static if (is(float4))
476 {
477 version (X86) {}
478 else
479 {
480 float4 f4;
481 f4.array[0] = 1;
482 f4.array[1] = 2;
483 f4.array[2] = 3;
484 f4.array[3] = 4;
485
486 formatValue(w, f4, spec);
487 assert(w.data == "[1, 2, 3, 4]");
488 }
489 }
490 }
491
492 import std.format.internal.write;
493
494 import std.format.spec : FormatSpec;
495 import std.traits : isSomeString;
496
497 /**
498 Converts its arguments according to a format string and writes
499 the result to an output range.
500
501 The second version of `formattedWrite` takes the format string as a
502 template argument. In this case, it is checked for consistency at
503 compile-time.
504
505 Params:
506 w = an $(REF_ALTTEXT output range, isOutputRange, std, range, primitives),
507 where the formatted result is written to
508 fmt = a $(MREF_ALTTEXT format string, std,format)
509 args = a variadic list of arguments to be formatted
510 Writer = the type of the writer `w`
511 Char = character type of `fmt`
512 Args = a variadic list of types of the arguments
513
514 Returns:
515 The index of the last argument that was formatted. If no positional
516 arguments are used, this is the number of arguments that where formatted.
517
518 Throws:
519 A $(REF_ALTTEXT FormatException, FormatException, std, format)
520 if formatting did not succeed.
521
522 Note:
523 In theory this function should be `@nogc`. But with the current
524 implementation there are some cases where allocations occur.
525 See $(REF_ALTTEXT $(D sformat), sformat, std, format) for more details.
526 */
527 uint formattedWrite(Writer, Char, Args...)(auto ref Writer w, const scope Char[] fmt, Args args)
528 {
529 import std.conv : text;
530 import std.format : enforceFmt, FormatException;
531 import std.traits : isSomeChar;
532
533 auto spec = FormatSpec!Char(fmt);
534
535 // Are we already done with formats? Then just dump each parameter in turn
536 uint currentArg = 0;
537 bool lastWasConsumeAll;
538
539 while (spec.writeUpToNextSpec(w))
540 {
541 if (currentArg == Args.length && !spec.indexStart)
542 {
543 // leftover spec?
544 enforceFmt(fmt.length == 0,
545 text("Orphan format specifier: %", spec.spec));
546 break;
547 }
548
549 if (spec.width == spec.DYNAMIC)
550 {
551 auto width = getNthInt!"integer width"(currentArg, args);
552 if (width < 0)
553 {
554 spec.flDash = true;
555 width = -width;
556 }
557 spec.width = width;
558 ++currentArg;
559 }
560 else if (spec.width < 0)
561 {
562 // means: get width as a positional parameter
563 auto index = cast(uint) -spec.width;
564 assert(index > 0, "The index must be greater than zero");
565 auto width = getNthInt!"integer width"(index - 1, args);
566 if (currentArg < index) currentArg = index;
567 if (width < 0)
568 {
569 spec.flDash = true;
570 width = -width;
571 }
572 spec.width = width;
573 }
574
575 if (spec.precision == spec.DYNAMIC)
576 {
577 auto precision = getNthInt!"integer precision"(currentArg, args);
578 if (precision >= 0) spec.precision = precision;
579 // else negative precision is same as no precision
580 else spec.precision = spec.UNSPECIFIED;
581 ++currentArg;
582 }
583 else if (spec.precision < 0)
584 {
585 // means: get precision as a positional parameter
586 auto index = cast(uint) -spec.precision;
587 assert(index > 0, "The precision must be greater than zero");
588 auto precision = getNthInt!"integer precision"(index- 1, args);
589 if (currentArg < index) currentArg = index;
590 if (precision >= 0) spec.precision = precision;
591 // else negative precision is same as no precision
592 else spec.precision = spec.UNSPECIFIED;
593 }
594
595 if (spec.separators == spec.DYNAMIC)
596 {
597 auto separators = getNthInt!"separator digit width"(currentArg, args);
598 spec.separators = separators;
599 ++currentArg;
600 }
601
602 if (spec.dynamicSeparatorChar)
603 {
604 auto separatorChar =
605 getNth!("separator character", isSomeChar, dchar)(currentArg, args);
606 spec.separatorChar = separatorChar;
607 spec.dynamicSeparatorChar = false;
608 ++currentArg;
609 }
610
611 if (currentArg == Args.length && !spec.indexStart)
612 {
613 // leftover spec?
614 enforceFmt(fmt.length == 0,
615 text("Orphan format specifier: %", spec.spec));
616 break;
617 }
618
619 // Format an argument
620 // This switch uses a static foreach to generate a jump table.
621 // Currently `spec.indexStart` use the special value '0' to signal
622 // we should use the current argument. An enhancement would be to
623 // always store the index.
624 size_t index = currentArg;
625 if (spec.indexStart != 0)
626 index = spec.indexStart - 1;
627 else
628 ++currentArg;
629 SWITCH: switch (index)
630 {
631 foreach (i, Tunused; Args)
632 {
633 case i:
634 formatValue(w, args[i], spec);
635 if (currentArg < spec.indexEnd)
636 currentArg = spec.indexEnd;
637 // A little know feature of format is to format a range
638 // of arguments, e.g. `%1:3$` will format the first 3
639 // arguments. Since they have to be consecutive we can
640 // just use explicit fallthrough to cover that case.
641 if (i + 1 < spec.indexEnd)
642 {
643 // You cannot goto case if the next case is the default
644 static if (i + 1 < Args.length)
645 goto case;
646 else
647 goto default;
648 }
649 else
650 break SWITCH;
651 }
652 default:
653 if (spec.indexEnd == spec.indexEnd.max)
654 {
655 lastWasConsumeAll = true;
656 break;
657 }
658 else if (spec.indexEnd == spec.indexStart)
659 throw new FormatException(
660 text("Positional specifier %", spec.indexStart, '$', spec.spec,
661 " index exceeds ", Args.length));
662 else
663 throw new FormatException(
664 text("Positional specifier %", spec.indexStart, ":", spec.indexEnd, '$', spec.spec,
665 " index exceeds ", Args.length));
666 }
667 }
668
669 return lastWasConsumeAll ? Args.length : currentArg;
670 }
671
672 ///
673 @safe pure unittest
674 {
675 import std.array : appender;
676
677 auto writer1 = appender!string();
678 formattedWrite(writer1, "%s is the ultimate %s.", 42, "answer");
679 assert(writer1[] == "42 is the ultimate answer.");
680
681 auto writer2 = appender!string();
682 formattedWrite(writer2, "Increase: %7.2f %%", 17.4285);
683 assert(writer2[] == "Increase: 17.43 %");
684 }
685
686 /// ditto
687 uint formattedWrite(alias fmt, Writer, Args...)(auto ref Writer w, Args args)
688 if (isSomeString!(typeof(fmt)))
689 {
690 import std.format : checkFormatException;
691
692 alias e = checkFormatException!(fmt, Args);
693 static assert(!e, e);
694 return .formattedWrite(w, fmt, args);
695 }
696
697 /// The format string can be checked at compile-time:
698 @safe pure unittest
699 {
700 import std.array : appender;
701
702 auto writer = appender!string();
703 writer.formattedWrite!"%d is the ultimate %s."(42, "answer");
704 assert(writer[] == "42 is the ultimate answer.");
705
706 // This line doesn't compile, because 3.14 cannot be formatted with %d:
707 // writer.formattedWrite!"%d is the ultimate %s."(3.14, "answer");
708 }
709
710 @safe pure unittest
711 {
712 import std.array : appender;
713
714 auto stream = appender!string();
715 formattedWrite(stream, "%s", 1.1);
716 assert(stream.data == "1.1", stream.data);
717 }
718
719 @safe pure unittest
720 {
721 import std.array;
722
723 auto w = appender!string();
724 formattedWrite(w, "%s %d", "@safe/pure", 42);
725 assert(w.data == "@safe/pure 42");
726 }
727
728 @safe pure unittest
729 {
730 char[20] buf;
731 auto w = buf[];
732 formattedWrite(w, "%s %d", "@safe/pure", 42);
733 assert(buf[0 .. $ - w.length] == "@safe/pure 42");
734 }
735
736 @safe pure unittest
737 {
738 import std.algorithm.iteration : map;
739 import std.array : appender;
740
741 auto stream = appender!string();
742 formattedWrite(stream, "%s", map!"a*a"([2, 3, 5]));
743 assert(stream.data == "[4, 9, 25]", stream.data);
744
745 // Test shared data.
746 stream = appender!string();
747 shared int s = 6;
748 formattedWrite(stream, "%s", s);
749 assert(stream.data == "6");
750 }
751
752 @safe pure unittest
753 {
754 // testing positional parameters
755 import std.array : appender;
756 import std.exception : collectExceptionMsg;
757 import std.format : FormatException;
758
759 auto w = appender!(char[])();
760 formattedWrite(w,
761 "Numbers %2$s and %1$s are reversed and %1$s%2$s repeated",
762 42, 0);
763 assert(w.data == "Numbers 0 and 42 are reversed and 420 repeated",
764 w.data);
765 assert(collectExceptionMsg!FormatException(formattedWrite(w, "%1$s, %3$s", 1, 2))
766 == "Positional specifier %3$s index exceeds 2");
767
768 w.clear();
769 formattedWrite(w, "asd%s", 23);
770 assert(w.data == "asd23", w.data);
771 w.clear();
772 formattedWrite(w, "%s%s", 23, 45);
773 assert(w.data == "2345", w.data);
774 }
775
776 // https://issues.dlang.org/show_bug.cgi?id=3479
777 @safe unittest
778 {
779 import std.array : appender;
780
781 auto stream = appender!(char[])();
782 formattedWrite(stream, "%2$.*1$d", 12, 10);
783 assert(stream.data == "000000000010", stream.data);
784 }
785
786 // https://issues.dlang.org/show_bug.cgi?id=6893
787 @safe unittest
788 {
789 import std.array : appender;
790
791 enum E : ulong { A, B, C }
792 auto stream = appender!(char[])();
793 formattedWrite(stream, "%s", E.C);
794 assert(stream.data == "C");
795 }
796
797 @safe pure unittest
798 {
799 import std.array : appender;
800
801 auto stream = appender!string();
802 formattedWrite(stream, "%u", 42);
803 assert(stream.data == "42", stream.data);
804 }
805
806 @safe pure unittest
807 {
808 // testing raw writes
809 import std.array : appender;
810
811 auto w = appender!(char[])();
812 uint a = 0x02030405;
813 formattedWrite(w, "%+r", a);
814 assert(w.data.length == 4 && w.data[0] == 2 && w.data[1] == 3
815 && w.data[2] == 4 && w.data[3] == 5);
816
817 w.clear();
818 formattedWrite(w, "%-r", a);
819 assert(w.data.length == 4 && w.data[0] == 5 && w.data[1] == 4
820 && w.data[2] == 3 && w.data[3] == 2);
821 }
822
823 @safe unittest
824 {
825 import std.array : appender;
826 import std.conv : text, octal;
827
828 auto stream = appender!(char[])();
829
830 formattedWrite(stream, "hello world! %s %s ", true, 57, 1_000_000_000, 'x', " foo");
831 assert(stream.data == "hello world! true 57 ", stream.data);
832 stream.clear();
833
834 formattedWrite(stream, "%g %A %s", 1.67, -1.28, float.nan);
835 assert(stream.data == "1.67 -0X1.47AE147AE147BP+0 nan", stream.data);
836 stream.clear();
837
838 formattedWrite(stream, "%x %X", 0x1234AF, 0xAFAFAFAF);
839 assert(stream.data == "1234af AFAFAFAF");
840 stream.clear();
841
842 formattedWrite(stream, "%b %o", 0x1234AF, 0xAFAFAFAF);
843 assert(stream.data == "100100011010010101111 25753727657");
844 stream.clear();
845
846 formattedWrite(stream, "%d %s", 0x1234AF, 0xAFAFAFAF);
847 assert(stream.data == "1193135 2947526575");
848 stream.clear();
849
850 formattedWrite(stream, "%a %A", 1.32, 6.78f);
851 assert(stream.data == "0x1.51eb851eb851fp+0 0X1.B1EB86P+2");
852 stream.clear();
853
854 formattedWrite(stream, "%#06.*f", 2, 12.345);
855 assert(stream.data == "012.35");
856 stream.clear();
857
858 formattedWrite(stream, "%#0*.*f", 6, 2, 12.345);
859 assert(stream.data == "012.35");
860 stream.clear();
861
862 const real constreal = 1;
863 formattedWrite(stream, "%g",constreal);
864 assert(stream.data == "1");
865 stream.clear();
866
867 formattedWrite(stream, "%7.4g:", 12.678);
868 assert(stream.data == " 12.68:");
869 stream.clear();
870
871 formattedWrite(stream, "%7.4g:", 12.678L);
872 assert(stream.data == " 12.68:");
873 stream.clear();
874
875 formattedWrite(stream, "%04f|%05d|%#05x|%#5x", -4.0, -10, 1, 1);
876 assert(stream.data == "-4.000000|-0010|0x001| 0x1", stream.data);
877 stream.clear();
878
879 int i;
880 string s;
881
882 i = -10;
883 formattedWrite(stream, "%d|%3d|%03d|%1d|%01.4f", i, i, i, i, cast(double) i);
884 assert(stream.data == "-10|-10|-10|-10|-10.0000");
885 stream.clear();
886
887 i = -5;
888 formattedWrite(stream, "%d|%3d|%03d|%1d|%01.4f", i, i, i, i, cast(double) i);
889 assert(stream.data == "-5| -5|-05|-5|-5.0000");
890 stream.clear();
891
892 i = 0;
893 formattedWrite(stream, "%d|%3d|%03d|%1d|%01.4f", i, i, i, i, cast(double) i);
894 assert(stream.data == "0| 0|000|0|0.0000");
895 stream.clear();
896
897 i = 5;
898 formattedWrite(stream, "%d|%3d|%03d|%1d|%01.4f", i, i, i, i, cast(double) i);
899 assert(stream.data == "5| 5|005|5|5.0000");
900 stream.clear();
901
902 i = 10;
903 formattedWrite(stream, "%d|%3d|%03d|%1d|%01.4f", i, i, i, i, cast(double) i);
904 assert(stream.data == "10| 10|010|10|10.0000");
905 stream.clear();
906
907 formattedWrite(stream, "%.0d", 0);
908 assert(stream.data == "0");
909 stream.clear();
910
911 formattedWrite(stream, "%.g", .34);
912 assert(stream.data == "0.3");
913 stream.clear();
914
915 stream.clear();
916 formattedWrite(stream, "%.0g", .34);
917 assert(stream.data == "0.3");
918
919 stream.clear();
920 formattedWrite(stream, "%.2g", .34);
921 assert(stream.data == "0.34");
922
923 stream.clear();
924 formattedWrite(stream, "%0.0008f", 1e-08);
925 assert(stream.data == "0.00000001");
926
927 stream.clear();
928 formattedWrite(stream, "%0.0008f", 1e-05);
929 assert(stream.data == "0.00001000");
930
931 s = "helloworld";
932 string r;
933 stream.clear();
934 formattedWrite(stream, "%.2s", s[0 .. 5]);
935 assert(stream.data == "he");
936 stream.clear();
937 formattedWrite(stream, "%.20s", s[0 .. 5]);
938 assert(stream.data == "hello");
939 stream.clear();
940 formattedWrite(stream, "%8s", s[0 .. 5]);
941 assert(stream.data == " hello");
942
943 byte[] arrbyte = new byte[4];
944 arrbyte[0] = 100;
945 arrbyte[1] = -99;
946 arrbyte[3] = 0;
947 stream.clear();
948 formattedWrite(stream, "%s", arrbyte);
949 assert(stream.data == "[100, -99, 0, 0]", stream.data);
950
951 ubyte[] arrubyte = new ubyte[4];
952 arrubyte[0] = 100;
953 arrubyte[1] = 200;
954 arrubyte[3] = 0;
955 stream.clear();
956 formattedWrite(stream, "%s", arrubyte);
957 assert(stream.data == "[100, 200, 0, 0]", stream.data);
958
959 short[] arrshort = new short[4];
960 arrshort[0] = 100;
961 arrshort[1] = -999;
962 arrshort[3] = 0;
963 stream.clear();
964 formattedWrite(stream, "%s", arrshort);
965 assert(stream.data == "[100, -999, 0, 0]");
966 stream.clear();
967 formattedWrite(stream, "%s", arrshort);
968 assert(stream.data == "[100, -999, 0, 0]");
969
970 ushort[] arrushort = new ushort[4];
971 arrushort[0] = 100;
972 arrushort[1] = 20_000;
973 arrushort[3] = 0;
974 stream.clear();
975 formattedWrite(stream, "%s", arrushort);
976 assert(stream.data == "[100, 20000, 0, 0]");
977
978 int[] arrint = new int[4];
979 arrint[0] = 100;
980 arrint[1] = -999;
981 arrint[3] = 0;
982 stream.clear();
983 formattedWrite(stream, "%s", arrint);
984 assert(stream.data == "[100, -999, 0, 0]");
985 stream.clear();
986 formattedWrite(stream, "%s", arrint);
987 assert(stream.data == "[100, -999, 0, 0]");
988
989 long[] arrlong = new long[4];
990 arrlong[0] = 100;
991 arrlong[1] = -999;
992 arrlong[3] = 0;
993 stream.clear();
994 formattedWrite(stream, "%s", arrlong);
995 assert(stream.data == "[100, -999, 0, 0]");
996 stream.clear();
997 formattedWrite(stream, "%s",arrlong);
998 assert(stream.data == "[100, -999, 0, 0]");
999
1000 ulong[] arrulong = new ulong[4];
1001 arrulong[0] = 100;
1002 arrulong[1] = 999;
1003 arrulong[3] = 0;
1004 stream.clear();
1005 formattedWrite(stream, "%s", arrulong);
1006 assert(stream.data == "[100, 999, 0, 0]");
1007
1008 string[] arr2 = new string[4];
1009 arr2[0] = "hello";
1010 arr2[1] = "world";
1011 arr2[3] = "foo";
1012 stream.clear();
1013 formattedWrite(stream, "%s", arr2);
1014 assert(stream.data == `["hello", "world", "", "foo"]`, stream.data);
1015
1016 stream.clear();
1017 formattedWrite(stream, "%.8d", 7);
1018 assert(stream.data == "00000007");
1019
1020 stream.clear();
1021 formattedWrite(stream, "%.8x", 10);
1022 assert(stream.data == "0000000a");
1023
1024 stream.clear();
1025 formattedWrite(stream, "%-3d", 7);
1026 assert(stream.data == "7 ");
1027
1028 stream.clear();
1029 formattedWrite(stream, "%*d", -3, 7);
1030 assert(stream.data == "7 ");
1031
1032 stream.clear();
1033 formattedWrite(stream, "%.*d", -3, 7);
1034 assert(stream.data == "7");
1035
1036 stream.clear();
1037 formattedWrite(stream, "%s", "abc"c);
1038 assert(stream.data == "abc");
1039 stream.clear();
1040 formattedWrite(stream, "%s", "def"w);
1041 assert(stream.data == "def", text(stream.data.length));
1042 stream.clear();
1043 formattedWrite(stream, "%s", "ghi"d);
1044 assert(stream.data == "ghi");
1045
1046 @trusted void* deadBeef() { return cast(void*) 0xDEADBEEF; }
1047 stream.clear();
1048 formattedWrite(stream, "%s", deadBeef());
1049 assert(stream.data == "DEADBEEF", stream.data);
1050
1051 stream.clear();
1052 formattedWrite(stream, "%#x", 0xabcd);
1053 assert(stream.data == "0xabcd");
1054 stream.clear();
1055 formattedWrite(stream, "%#X", 0xABCD);
1056 assert(stream.data == "0XABCD");
1057
1058 stream.clear();
1059 formattedWrite(stream, "%#o", octal!12345);
1060 assert(stream.data == "012345");
1061 stream.clear();
1062 formattedWrite(stream, "%o", 9);
1063 assert(stream.data == "11");
1064
1065 stream.clear();
1066 formattedWrite(stream, "%+d", 123);
1067 assert(stream.data == "+123");
1068 stream.clear();
1069 formattedWrite(stream, "%+d", -123);
1070 assert(stream.data == "-123");
1071 stream.clear();
1072 formattedWrite(stream, "% d", 123);
1073 assert(stream.data == " 123");
1074 stream.clear();
1075 formattedWrite(stream, "% d", -123);
1076 assert(stream.data == "-123");
1077
1078 stream.clear();
1079 formattedWrite(stream, "%%");
1080 assert(stream.data == "%");
1081
1082 stream.clear();
1083 formattedWrite(stream, "%d", true);
1084 assert(stream.data == "1");
1085 stream.clear();
1086 formattedWrite(stream, "%d", false);
1087 assert(stream.data == "0");
1088
1089 stream.clear();
1090 formattedWrite(stream, "%d", 'a');
1091 assert(stream.data == "97", stream.data);
1092 wchar wc = 'a';
1093 stream.clear();
1094 formattedWrite(stream, "%d", wc);
1095 assert(stream.data == "97");
1096 dchar dc = 'a';
1097 stream.clear();
1098 formattedWrite(stream, "%d", dc);
1099 assert(stream.data == "97");
1100
1101 byte b = byte.max;
1102 stream.clear();
1103 formattedWrite(stream, "%x", b);
1104 assert(stream.data == "7f");
1105 stream.clear();
1106 formattedWrite(stream, "%x", ++b);
1107 assert(stream.data == "80");
1108 stream.clear();
1109 formattedWrite(stream, "%x", ++b);
1110 assert(stream.data == "81");
1111
1112 short sh = short.max;
1113 stream.clear();
1114 formattedWrite(stream, "%x", sh);
1115 assert(stream.data == "7fff");
1116 stream.clear();
1117 formattedWrite(stream, "%x", ++sh);
1118 assert(stream.data == "8000");
1119 stream.clear();
1120 formattedWrite(stream, "%x", ++sh);
1121 assert(stream.data == "8001");
1122
1123 i = int.max;
1124 stream.clear();
1125 formattedWrite(stream, "%x", i);
1126 assert(stream.data == "7fffffff");
1127 stream.clear();
1128 formattedWrite(stream, "%x", ++i);
1129 assert(stream.data == "80000000");
1130 stream.clear();
1131 formattedWrite(stream, "%x", ++i);
1132 assert(stream.data == "80000001");
1133
1134 stream.clear();
1135 formattedWrite(stream, "%x", 10);
1136 assert(stream.data == "a");
1137 stream.clear();
1138 formattedWrite(stream, "%X", 10);
1139 assert(stream.data == "A");
1140 stream.clear();
1141 formattedWrite(stream, "%x", 15);
1142 assert(stream.data == "f");
1143 stream.clear();
1144 formattedWrite(stream, "%X", 15);
1145 assert(stream.data == "F");
1146
1147 @trusted void ObjectTest()
1148 {
1149 Object c = null;
1150 stream.clear();
1151 formattedWrite(stream, "%s", c);
1152 assert(stream.data == "null");
1153 }
1154 ObjectTest();
1155
1156 enum TestEnum
1157 {
1158 Value1, Value2
1159 }
1160 stream.clear();
1161 formattedWrite(stream, "%s", TestEnum.Value2);
1162 assert(stream.data == "Value2", stream.data);
1163 stream.clear();
1164 formattedWrite(stream, "%s", cast(TestEnum) 5);
1165 assert(stream.data == "cast(TestEnum)5", stream.data);
1166
1167 //immutable(char[5])[int] aa = ([3:"hello", 4:"betty"]);
1168 //stream.clear();
1169 //formattedWrite(stream, "%s", aa.values);
1170 //assert(stream.data == "[[h,e,l,l,o],[b,e,t,t,y]]");
1171 //stream.clear();
1172 //formattedWrite(stream, "%s", aa);
1173 //assert(stream.data == "[3:[h,e,l,l,o],4:[b,e,t,t,y]]");
1174
1175 static const dchar[] ds = ['a','b'];
1176 for (int j = 0; j < ds.length; ++j)
1177 {
1178 stream.clear(); formattedWrite(stream, " %d", ds[j]);
1179 if (j == 0)
1180 assert(stream.data == " 97");
1181 else
1182 assert(stream.data == " 98");
1183 }
1184
1185 stream.clear();
1186 formattedWrite(stream, "%.-3d", 7);
1187 assert(stream.data == "7", ">" ~ stream.data ~ "<");
1188 }
1189
1190 @safe unittest
1191 {
1192 import std.array : appender;
1193 import std.meta : AliasSeq;
1194
1195 immutable(char[5])[int] aa = ([3:"hello", 4:"betty"]);
1196 assert(aa[3] == "hello");
1197 assert(aa[4] == "betty");
1198
1199 auto stream = appender!(char[])();
1200 alias AllNumerics =
1201 AliasSeq!(byte, ubyte, short, ushort, int, uint, long, ulong,
1202 float, double, real);
1203 foreach (T; AllNumerics)
1204 {
1205 T value = 1;
1206 stream.clear();
1207 formattedWrite(stream, "%s", value);
1208 assert(stream.data == "1");
1209 }
1210
1211 stream.clear();
1212 formattedWrite(stream, "%s", aa);
1213 }
1214
1215 // https://github.com/dlang/phobos/issues/10699
1216 @safe pure unittest
1217 {
1218 import std.array : appender;
1219 auto w = appender!(char[])();
1220
1221 uint count = formattedWrite(w, "%1:$d", 1, 2, 3);
1222 assert(count == 3);
1223 assert(w.data == "123");
1224 }
1225
1226 /**
1227 Formats a value of any type according to a format specifier and
1228 writes the result to an output range.
1229
1230 More details about how types are formatted, and how the format
1231 specifier influences the outcome, can be found in the definition of a
1232 $(MREF_ALTTEXT format string, std,format).
1233
1234 Params:
1235 w = an $(REF_ALTTEXT output range, isOutputRange, std, range, primitives) where
1236 the formatted value is written to
1237 val = the value to write
1238 f = a $(REF_ALTTEXT FormatSpec, FormatSpec, std, format, spec) defining the
1239 format specifier
1240 Writer = the type of the output range `w`
1241 T = the type of value `val`
1242 Char = the character type used for `f`
1243
1244 Throws:
1245 A $(LREF FormatException) if formatting did not succeed.
1246
1247 Note:
1248 In theory this function should be `@nogc`. But with the current
1249 implementation there are some cases where allocations occur.
1250 See $(REF_ALTTEXT $(D sformat), sformat, std, format) for more details.
1251
1252 See_Also:
1253 $(LREF formattedWrite) which formats several values at once.
1254 */
1255 void formatValue(Writer, T, Char)(auto ref Writer w, auto ref T val, scope const ref FormatSpec!Char f)
1256 {
1257 import std.format : enforceFmt;
1258
1259 enforceFmt(f.width != f.DYNAMIC && f.precision != f.DYNAMIC
1260 && f.separators != f.DYNAMIC && !f.dynamicSeparatorChar,
1261 "Dynamic argument not allowed for `formatValue`");
1262
1263 formatValueImpl(w, val, f);
1264 }
1265
1266 ///
1267 @safe pure unittest
1268 {
1269 import std.array : appender;
1270 import std.format.spec : singleSpec;
1271
1272 auto writer = appender!string();
1273 auto spec = singleSpec("%08b");
1274 writer.formatValue(42, spec);
1275 assert(writer.data == "00101010");
1276
1277 spec = singleSpec("%2s");
1278 writer.formatValue('=', spec);
1279 assert(writer.data == "00101010 =");
1280
1281 spec = singleSpec("%+14.6e");
1282 writer.formatValue(42.0, spec);
1283 assert(writer.data == "00101010 = +4.200000e+01");
1284 }
1285
1286 // https://issues.dlang.org/show_bug.cgi?id=15386
1287 @safe pure unittest
1288 {
1289 import std.array : appender;
1290 import std.format.spec : FormatSpec;
1291 import std.format : FormatException;
1292 import std.exception : assertThrown;
1293
1294 auto w = appender!(char[])();
1295 auto dor = appender!(char[])();
1296 auto fs = FormatSpec!char("%.*s");
1297 fs.writeUpToNextSpec(dor);
1298 assertThrown!FormatException(formatValue(w, 0, fs));
1299
1300 fs = FormatSpec!char("%*s");
1301 fs.writeUpToNextSpec(dor);
1302 assertThrown!FormatException(formatValue(w, 0, fs));
1303
1304 fs = FormatSpec!char("%,*s");
1305 fs.writeUpToNextSpec(dor);
1306 assertThrown!FormatException(formatValue(w, 0, fs));
1307
1308 fs = FormatSpec!char("%,?s");
1309 fs.writeUpToNextSpec(dor);
1310 assertThrown!FormatException(formatValue(w, 0, fs));
1311
1312 assertThrown!FormatException(formattedWrite(w, "%(%0*d%)", new int[1]));
1313 }
1314
1315 // https://issues.dlang.org/show_bug.cgi?id=22609
1316 @safe pure unittest
1317 {
1318 static enum State: ubyte { INACTIVE }
1319 static struct S {
1320 State state = State.INACTIVE;
1321 int generation = 1;
1322 alias state this;
1323 // DMDBUG: https://issues.dlang.org/show_bug.cgi?id=16657
1324 auto opEquals(S other) const { return state == other.state && generation == other.generation; }
1325 auto opEquals(State other) const { return state == other; }
1326 }
1327
1328 import std.array : appender;
1329 import std.format.spec : singleSpec;
1330
1331 auto writer = appender!string();
1332 const spec = singleSpec("%s");
1333 S a;
1334 writer.formatValue(a, spec);
1335 assert(writer.data == "0");
1336 }
1337
1338 // https://issues.dlang.org/show_bug.cgi?id=23400
1339 @safe pure unittest
1340 {
1341 import std.range : nullSink;
1342 import std.format.spec : singleSpec;
1343
1344 static struct S
1345 {
1346 // non-const opEquals method
1347 bool opEquals(S rhs) { return false; }
1348 }
1349
1350 enum E { a = S() }
1351
1352 E e;
1353 auto writer = nullSink;
1354 const spec = singleSpec("%s");
1355 writer.formatValue(e, spec);
1356 }