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
|
// Written in the D programming language.
/**
This is a submodule of $(MREF std, format).
It centers around a struct called $(LREF FormatSpec), which takes a
$(MREF_ALTTEXT format string, std,format) and provides tools for
parsing this string. Additionally this module contains a function
$(LREF singleSpec) which helps treating a single format specifier.
Copyright: Copyright The D Language Foundation 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/spec.d)
*/
module std.format.spec;
import std.traits : Unqual;
template FormatSpec(Char)
if (!is(Unqual!Char == Char))
{
alias FormatSpec = FormatSpec!(Unqual!Char);
}
/**
A general handler for format strings.
This handler centers around the function $(LREF writeUpToNextSpec),
which parses the $(MREF_ALTTEXT format string, std,format) until the
next format specifier is found. After the call, it provides
information about this format specifier in its numerous variables.
Params:
Char = the character type of the format string
*/
struct FormatSpec(Char)
if (is(Unqual!Char == Char))
{
import std.algorithm.searching : startsWith;
import std.ascii : isDigit;
import std.conv : parse, text, to;
import std.range.primitives;
/**
Minimum width.
_Default: `0`.
*/
int width = 0;
/**
Precision. Its semantic depends on the format character.
See $(MREF_ALTTEXT format string, std,format) for more details.
_Default: `UNSPECIFIED`.
*/
int precision = UNSPECIFIED;
/**
Number of elements between separators.
_Default: `UNSPECIFIED`.
*/
int separators = UNSPECIFIED;
/**
The separator charactar is supplied at runtime.
_Default: false.
*/
bool dynamicSeparatorChar = false;
/**
Set to `DYNAMIC` when the separator character is supplied at runtime.
_Default: `UNSPECIFIED`.
$(RED Warning:
`separatorCharPos` is deprecated. It will be removed in 2.107.0.
Please use `dynamicSeparatorChar` instead.)
*/
// @@@DEPRECATED_[2.107.0]@@@
deprecated("separatorCharPos will be removed in 2.107.0. Please use dynamicSeparatorChar instead.")
int separatorCharPos() { return dynamicSeparatorChar ? DYNAMIC : UNSPECIFIED; }
/// ditto
// @@@DEPRECATED_[2.107.0]@@@
deprecated("separatorCharPos will be removed in 2.107.0. Please use dynamicSeparatorChar instead.")
void separatorCharPos(int value) { dynamicSeparatorChar = value == DYNAMIC; }
/**
Character to use as separator.
_Default: `','`.
*/
dchar separatorChar = ',';
/**
Special value for `width`, `precision` and `separators`.
It flags that these values will be passed at runtime through
variadic arguments.
*/
enum int DYNAMIC = int.max;
/**
Special value for `precision` and `separators`.
It flags that these values have not been specified.
*/
enum int UNSPECIFIED = DYNAMIC - 1;
/**
The format character.
_Default: `'s'`.
*/
char spec = 's';
/**
Index of the argument for positional parameters.
Counting starts with `1`. Set to `0` if not used. Default: `0`.
*/
ubyte indexStart;
/**
Index of the last argument for positional parameter ranges.
Counting starts with `1`. Set to `0` if not used. Default: `0`.
*/
ubyte indexEnd;
version (StdDdoc)
{
/// The format specifier contained a `'-'`.
bool flDash;
/// The format specifier contained a `'0'`.
bool flZero;
/// The format specifier contained a space.
bool flSpace;
/// The format specifier contained a `'+'`.
bool flPlus;
/// The format specifier contained a `'#'`.
bool flHash;
/// The format specifier contained a `'='`.
bool flEqual;
/// The format specifier contained a `','`.
bool flSeparator;
// 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,
bool, "flEqual", 1,
bool, "flSeparator", 1,
ubyte, "", 1));
ubyte allFlags;
}
}
/// The inner format string of a nested format specifier.
const(Char)[] nested;
/**
The separator of a nested format specifier.
`null` means, there is no separator. `empty`, but not `null`,
means zero length separator.
*/
const(Char)[] sep;
/// Contains the part of the format string, that has not yet been parsed.
const(Char)[] trailing;
/// Sequence `"["` inserted before each range or range like structure.
enum immutable(Char)[] seqBefore = "[";
/// Sequence `"]"` inserted after each range or range like structure.
enum immutable(Char)[] seqAfter = "]";
/**
Sequence `":"` inserted between element key and element value of
an associative array.
*/
enum immutable(Char)[] keySeparator = ":";
/**
Sequence `", "` inserted between elements of a range, a range like
structure or the elements of an associative array.
*/
enum immutable(Char)[] seqSeparator = ", ";
/**
Creates a new `FormatSpec`.
The string is lazily evaluated. That means, nothing is done,
until $(LREF writeUpToNextSpec) is called.
Params:
fmt = a $(MREF_ALTTEXT format string, std,format)
*/
this(in Char[] fmt) @safe pure
{
trailing = fmt;
}
/**
Writes the format string to an output range until the next format
specifier is found and parse that format specifier.
See the $(MREF_ALTTEXT description of format strings, std,format) for more
details about the format specifier.
Params:
writer = an $(REF_ALTTEXT output range, isOutputRange, std, range, primitives),
where the format string is written to
OutputRange = type of the output range
Returns:
True, if a format specifier is found and false, if the end of the
format string has been reached.
Throws:
A $(REF_ALTTEXT FormatException, FormatException, std,format)
when parsing the format specifier did not succeed.
*/
bool writeUpToNextSpec(OutputRange)(ref OutputRange writer) scope
{
import std.format : enforceFmt;
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;
}
private void fillUp() scope
{
import std.format : enforceFmt, FormatException;
// Reset content
if (__ctfe)
{
flDash = false;
flZero = false;
flSpace = false;
flPlus = false;
flEqual = false;
flHash = false;
flSeparator = 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 FormatException(
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; // no separator
}
//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 '=': flEqual = 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++] == '$',
text("$ expected after '*", -width, "' in format string"));
}
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 = trailing.length - tmp.length;
if (tmp.startsWith('$'))
{
// index of the form %n$
indexEnd = indexStart = to!ubyte(widthOrArgIndex);
++i;
}
else if (tmp.startsWith(':'))
{
// two indexes of the form %m:n$, or one index of the form %m:$
indexStart = to!ubyte(widthOrArgIndex);
tmp = tmp[1 .. $];
if (tmp.startsWith('$'))
{
indexEnd = indexEnd.max;
}
else
{
indexEnd = parse!(typeof(indexEnd))(tmp);
}
i = trailing.length - tmp.length;
enforceFmt(trailing[i++] == '$',
"$ expected");
}
else
{
// width
width = to!int(widthOrArgIndex);
}
break;
case ',':
// Precision
++i;
flSeparator = true;
if (trailing[i] == '*')
{
++i;
// read result
separators = DYNAMIC;
}
else if (isDigit(trailing[i]))
{
auto tmp = trailing[i .. $];
separators = parse!int(tmp);
i = trailing.length - tmp.length;
}
else
{
// "," was specified, but nothing after it
separators = 3;
}
if (trailing[i] == '?')
{
dynamicSeparatorChar = true;
++i;
}
break;
case '.':
// Precision
if (trailing[++i] == '*')
{
if (isDigit(trailing[++i]))
{
// a '.*' followed by digits and '$' is a
// positional precision
trailing = trailing[i .. $];
i = 0;
precision = -parse!int(trailing);
enforceFmt(trailing[i++] == '$',
"$ expected");
}
else
{
// read result
precision = DYNAMIC;
}
}
else if (trailing[i] == '-')
{
// negative precision, as good as 0
precision = 0;
auto tmp = trailing[i .. $];
parse!int(tmp); // skip digits
i = trailing.length - tmp.length;
}
else if (isDigit(trailing[i]))
{
auto tmp = trailing[i .. $];
precision = parse!int(tmp);
i = trailing.length - tmp.length;
}
else
{
// "." was specified, but nothing after it
precision = 0;
}
break;
default:
// this is the format char
spec = cast(char) trailing[i++];
trailing = trailing[i .. $];
return;
} // end switch
} // end for
throw new FormatException(text("Incorrect format specifier: ", trailing));
}
//--------------------------------------------------------------------------
package bool readUpToNextSpec(R)(ref R r) scope
{
import std.ascii : isLower, isWhite;
import std.format : enforceFmt;
import std.utf : stride;
// Reset content
if (__ctfe)
{
flDash = false;
flZero = false;
flSpace = false;
flPlus = false;
flHash = false;
flEqual = false;
flSeparator = false;
}
else
{
allFlags = 0;
}
width = 0;
precision = UNSPECIFIED;
nested = null;
// Parse the spec
while (trailing.length)
{
const c = trailing[0];
if (c == '%' && trailing.length > 1)
{
const c2 = trailing[1];
if (c2 == '%')
{
assert(!r.empty, "Required at least one more input");
// Require a '%'
enforceFmt (r.front == '%',
text("parseToFormatSpec: Cannot find character '",
c2, "' in the input string."));
trailing = trailing[2 .. $];
r.popFront();
}
else
{
enforceFmt(isLower(c2) || c2 == '*' || c2 == '(',
text("'%", c2, "' not supported with formatted read"));
trailing = trailing[1 .. $];
fillUp();
return true;
}
}
else
{
if (c == ' ')
{
while (!r.empty && isWhite(r.front)) r.popFront();
//r = std.algorithm.find!(not!(isWhite))(r);
}
else
{
enforceFmt(!r.empty && r.front == trailing.front,
text("parseToFormatSpec: Cannot find character '",
c, "' in the input string."));
r.popFront();
}
trailing = trailing[stride(trailing, 0) .. $];
}
}
return false;
}
package string getCurFmtStr() const
{
import std.array : appender;
import std.format.write : formatValue;
auto w = appender!string();
auto f = FormatSpec!Char("%s"); // for stringnize
put(w, '%');
if (indexStart != 0)
{
formatValue(w, indexStart, f);
put(w, '$');
}
if (flDash) put(w, '-');
if (flZero) put(w, '0');
if (flSpace) put(w, ' ');
if (flPlus) put(w, '+');
if (flEqual) put(w, '=');
if (flHash) put(w, '#');
if (width != 0)
formatValue(w, width, f);
if (precision != FormatSpec!Char.UNSPECIFIED)
{
put(w, '.');
formatValue(w, precision, f);
}
if (flSeparator) put(w, ',');
if (separators != FormatSpec!Char.UNSPECIFIED)
formatValue(w, separators, f);
put(w, spec);
return w.data;
}
/**
Provides a string representation.
Returns:
The string representation.
*/
string toString() const @safe pure
{
import std.array : appender;
auto app = appender!string();
app.reserve(200 + trailing.length);
toString(app);
return app.data;
}
/**
Writes a string representation to an output range.
Params:
writer = an $(REF_ALTTEXT output range, isOutputRange, std, range, primitives),
where the representation is written to
OutputRange = type of the output range
*/
void toString(OutputRange)(ref OutputRange writer) const
if (isOutputRange!(OutputRange, char))
{
import std.format.write : formatValue;
auto s = singleSpec("%s");
put(writer, "address = ");
formatValue(writer, &this, s);
put(writer, "\nwidth = ");
formatValue(writer, width, s);
put(writer, "\nprecision = ");
formatValue(writer, precision, s);
put(writer, "\nspec = ");
formatValue(writer, spec, s);
put(writer, "\nindexStart = ");
formatValue(writer, indexStart, s);
put(writer, "\nindexEnd = ");
formatValue(writer, indexEnd, s);
put(writer, "\nflDash = ");
formatValue(writer, flDash, s);
put(writer, "\nflZero = ");
formatValue(writer, flZero, s);
put(writer, "\nflSpace = ");
formatValue(writer, flSpace, s);
put(writer, "\nflPlus = ");
formatValue(writer, flPlus, s);
put(writer, "\nflEqual = ");
formatValue(writer, flEqual, s);
put(writer, "\nflHash = ");
formatValue(writer, flHash, s);
put(writer, "\nflSeparator = ");
formatValue(writer, flSeparator, s);
put(writer, "\nnested = ");
formatValue(writer, nested, s);
put(writer, "\ntrailing = ");
formatValue(writer, trailing, s);
put(writer, '\n');
}
}
///
@safe pure unittest
{
import std.array : appender;
auto a = appender!(string)();
auto fmt = "Number: %6.4e\nString: %s";
auto f = FormatSpec!char(fmt);
assert(f.writeUpToNextSpec(a) == true);
assert(a.data == "Number: ");
assert(f.trailing == "\nString: %s");
assert(f.spec == 'e');
assert(f.width == 6);
assert(f.precision == 4);
assert(f.writeUpToNextSpec(a) == true);
assert(a.data == "Number: \nString: ");
assert(f.trailing == "");
assert(f.spec == 's');
assert(f.writeUpToNextSpec(a) == false);
assert(a.data == "Number: \nString: ");
}
@safe unittest
{
import std.array : appender;
import std.conv : text;
import std.exception : assertThrown;
import std.format : FormatException;
auto w = appender!(char[])();
auto f = FormatSpec!char("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!char("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");
// https://issues.dlang.org/show_bug.cgi?id=4775
f = FormatSpec!char("%%%s");
w.clear();
f.writeUpToNextSpec(w);
assert(w.data == "%" && f.trailing == "");
f = FormatSpec!char("%%%%%s%%");
w.clear();
while (f.writeUpToNextSpec(w)) continue;
assert(w.data == "%%%");
f = FormatSpec!char("a%%b%%c%");
w.clear();
assertThrown!FormatException(f.writeUpToNextSpec(w));
assert(w.data == "a%b%c" && f.trailing == "%");
}
// https://issues.dlang.org/show_bug.cgi?id=5237
@safe unittest
{
import std.array : appender;
auto w = appender!string();
auto f = FormatSpec!char("%.16f");
f.writeUpToNextSpec(w); // dummy eating
assert(f.spec == 'f');
auto fmt = f.getCurFmtStr();
assert(fmt == "%.16f");
}
// https://issues.dlang.org/show_bug.cgi?id=14059
@safe unittest
{
import std.array : appender;
import std.exception : assertThrown;
import std.format : FormatException;
auto a = appender!(string)();
auto f = FormatSpec!char("%-(%s%"); // %)")
assertThrown!FormatException(f.writeUpToNextSpec(a));
f = FormatSpec!char("%(%-"); // %)")
assertThrown!FormatException(f.writeUpToNextSpec(a));
}
@safe unittest
{
import std.array : appender;
import std.format : format;
auto a = appender!(string)();
auto f = FormatSpec!char("%,d");
f.writeUpToNextSpec(a);
assert(f.spec == 'd', format("%s", f.spec));
assert(f.precision == FormatSpec!char.UNSPECIFIED);
assert(f.separators == 3);
f = FormatSpec!char("%5,10f");
f.writeUpToNextSpec(a);
assert(f.spec == 'f', format("%s", f.spec));
assert(f.separators == 10);
assert(f.width == 5);
f = FormatSpec!char("%5,10.4f");
f.writeUpToNextSpec(a);
assert(f.spec == 'f', format("%s", f.spec));
assert(f.separators == 10);
assert(f.width == 5);
assert(f.precision == 4);
}
@safe pure unittest
{
import std.algorithm.searching : canFind, findSplitBefore;
auto expected = "width = 2" ~
"\nprecision = 5" ~
"\nspec = f" ~
"\nindexStart = 0" ~
"\nindexEnd = 0" ~
"\nflDash = false" ~
"\nflZero = false" ~
"\nflSpace = false" ~
"\nflPlus = false" ~
"\nflEqual = false" ~
"\nflHash = false" ~
"\nflSeparator = false" ~
"\nnested = " ~
"\ntrailing = \n";
auto spec = singleSpec("%2.5f");
auto res = spec.toString();
// make sure the address exists, then skip it
assert(res.canFind("address"));
assert(res.findSplitBefore("width")[1] == expected);
}
// https://issues.dlang.org/show_bug.cgi?id=15348
@safe pure unittest
{
import std.array : appender;
import std.exception : collectExceptionMsg;
import std.format : FormatException;
auto w = appender!(char[])();
auto f = FormatSpec!char("%*10d");
assert(collectExceptionMsg!FormatException(f.writeUpToNextSpec(w))
== "$ expected after '*10' in format string");
}
/**
Helper function that returns a `FormatSpec` for a single format specifier.
Params:
fmt = a $(MREF_ALTTEXT format string, std,format)
containing a single format specifier
Char = character type of `fmt`
Returns:
A $(LREF FormatSpec) with the format specifier parsed.
Throws:
A $(REF_ALTTEXT FormatException, FormatException, std,format) when the
format string contains no format specifier or more than a single format
specifier or when the format specifier is malformed.
*/
FormatSpec!Char singleSpec(Char)(Char[] fmt)
{
import std.conv : text;
import std.format : enforceFmt;
import std.range.primitives : empty, front;
enforceFmt(fmt.length >= 2, "fmt must be at least 2 characters long");
enforceFmt(fmt.front == '%', "fmt must start with a '%' character");
enforceFmt(fmt[1] != '%', "'%%' is not a permissible format specifier");
static struct DummyOutputRange
{
void put(C)(scope const C[] buf) {} // eat elements
}
auto a = DummyOutputRange();
auto spec = FormatSpec!Char(fmt);
//dummy write
spec.writeUpToNextSpec(a);
enforceFmt(spec.trailing.empty,
text("Trailing characters in fmt string: '", spec.trailing));
return spec;
}
///
@safe pure unittest
{
import std.array : appender;
import std.format.write : formatValue;
auto spec = singleSpec("%10.3e");
auto writer = appender!string();
writer.formatValue(42.0, spec);
assert(writer.data == " 4.200e+01");
}
@safe pure unittest
{
import std.exception : assertThrown;
import std.format : FormatException;
auto spec = singleSpec("%2.3e");
assert(spec.trailing == "");
assert(spec.spec == 'e');
assert(spec.width == 2);
assert(spec.precision == 3);
assertThrown!FormatException(singleSpec(""));
assertThrown!FormatException(singleSpec("%"));
assertThrown!FormatException(singleSpec("%2.3"));
assertThrown!FormatException(singleSpec("2.3e"));
assertThrown!FormatException(singleSpec("Test%2.3e"));
assertThrown!FormatException(singleSpec("%2.3eTest"));
assertThrown!FormatException(singleSpec("%%"));
}
// @@@DEPRECATED_[2.107.0]@@@
deprecated("enforceValidFormatSpec was accidentally made public and will be removed in 2.107.0")
void enforceValidFormatSpec(T, Char)(scope const ref FormatSpec!Char f)
{
import std.format.internal.write : evfs = enforceValidFormatSpec;
evfs!T(f);
}
@safe unittest
{
import std.exception : collectExceptionMsg;
import std.format : format, FormatException;
// width/precision
assert(collectExceptionMsg!FormatException(format("%*.d", 5.1, 2))
== "integer width expected, not double for argument #1");
assert(collectExceptionMsg!FormatException(format("%-1*.d", 5.1, 2))
== "integer width expected, not double for argument #1");
assert(collectExceptionMsg!FormatException(format("%.*d", '5', 2))
== "integer precision expected, not char for argument #1");
assert(collectExceptionMsg!FormatException(format("%-1.*d", 4.7, 3))
== "integer precision expected, not double for argument #1");
assert(collectExceptionMsg!FormatException(format("%.*d", 5))
== "Orphan format specifier: %d");
assert(collectExceptionMsg!FormatException(format("%*.*d", 5))
== "Missing integer precision argument");
// dynamicSeparatorChar
assert(collectExceptionMsg!FormatException(format("%,?d", 5))
== "separator character expected, not int for argument #1");
assert(collectExceptionMsg!FormatException(format("%,?d", '?'))
== "Orphan format specifier: %d");
assert(collectExceptionMsg!FormatException(format("%.*,*?d", 5))
== "Missing separator digit width argument");
}
|