Skip to content

Commit 8928adc

Browse files
authored
Merge pull request #5102 from WalterBright/format-divide
std.format: optimize converting unsigned to string
2 parents b5d6ac1 + e406bd9 commit 8928adc

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

std/format.d

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1506,6 +1506,13 @@ private void formatUnsigned(Writer, T, Char)(Writer w, T arg, const ref FormatSp
15061506
*/
15071507
char[64] buffer = void; // 64 bits in base 2 at most
15081508
char[] digits;
1509+
if (arg < base && base <= 10 && arg)
1510+
{
1511+
// Most numbers are a single digit - avoid expensive divide
1512+
buffer[0] = cast(char)(arg + '0');
1513+
digits = buffer[0 .. 1];
1514+
}
1515+
else
15091516
{
15101517
size_t i = buffer.length;
15111518
while (arg)
@@ -1589,9 +1596,11 @@ private void formatUnsigned(Writer, T, Char)(Writer w, T arg, const ref FormatSp
15891596
{
15901597
assertCTFEable!(
15911598
{
1599+
formatTest(9, "9");
15921600
formatTest( 10, "10" );
15931601
});
15941602
}
1603+
15951604
@system unittest
15961605
{
15971606
class C1 { long val; alias val this; this(long v){ val = v; } }
@@ -1648,6 +1657,12 @@ private void formatUnsigned(Writer, T, Char)(Writer w, T arg, const ref FormatSp
16481657
Bar bar;
16491658
formattedWrite(&put, "%s", bar); // NG
16501659
assert(result == "Bar");
1660+
1661+
result = null;
1662+
1663+
int i = 9;
1664+
formattedWrite(&put, "%s", 9);
1665+
assert(result == "9");
16511666
}
16521667

16531668
/**

0 commit comments

Comments
 (0)