Skip to content

Commit

Permalink
Faster and smaller write/writeln for integrals
Browse files Browse the repository at this point in the history
  • Loading branch information
andralex committed Jun 7, 2011
1 parent 44fc065 commit 0812b4f
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
38 changes: 37 additions & 1 deletion std/conv.d
Expand Up @@ -3301,7 +3301,7 @@ if (staticIndexOf!(Unqual!S, int, long) >= 0 && isSomeString!T)
return to!T(cast(Unsigned!(S)) value);
alias Unqual!(typeof(T.init[0])) Char;

// Cache read-only data only for const and immutable - mutable
// Cache read-only data only for const and immutable; mutable
// data is supposed to use allocation in all cases
static if (is(ElementType!T == const) || is(ElementType!T == immutable))
{
Expand Down Expand Up @@ -4229,3 +4229,39 @@ unittest
emplace!Foo(&foo, 2U);
assert(foo.num == 2);
}

// Undocumented for the time being
void toTextRange(T, W)(T value, W writer)
if (isIntegral!T && isOutputRange!(W, char))
{
Unqual!(Unsigned!T) v = void;
if (value < 0)
{
put(writer, '-');
v = -value;
}
else
{
v = value;
}

if (v < 10 && v < hexdigits.length)
{
put(writer, hexdigits[cast(size_t) v]);
return;
}

char[v.sizeof * 4] buffer = void;
auto i = buffer.length;

do
{
auto c = cast(ubyte) (v % 10);
v = v / 10;
i--;
buffer[i] = cast(char) (c + '0');
} while (v);

put(writer, buffer[i .. $]);
}

22 changes: 18 additions & 4 deletions std/stdio.d
Expand Up @@ -651,12 +651,26 @@ arguments in text format to the file. */
auto w = lockingTextWriter();
foreach (arg; args)
{
static if (isSomeString!(typeof(arg)))
alias typeof(arg) A;
static if (isSomeString!A)
{
put(w, arg);
}
else static if (isIntegral!A)
{
toTextRange(arg, w);
}
else static if (is(A : char))
{
put(w, arg);
}
else static if (isSomeChar!A)
{
w.put(arg);
put(w, arg);
}
else
{
// Most general case
std.format.formattedWrite(w, "%s", arg);
}
}
Expand Down Expand Up @@ -1473,7 +1487,7 @@ unittest
if (false) writeln();
}

/// ditto
// Specialization for strings - a very frequent case
void writeln(T...)(T args)
if (T.length == 1 && is(typeof(args[0]) : const(char)[]))
{
Expand All @@ -1486,7 +1500,7 @@ unittest
if (false) writeln("wyda");
}

/// Ditto
// Most general instance
void writeln(T...)(T args)
if (T.length > 1 || T.length == 1 && !is(typeof(args[0]) : const(char)[]))
{
Expand Down

0 comments on commit 0812b4f

Please sign in to comment.