Output range of ranges to single buffer

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 13 13:20:51 PST 2016


On Wed, Jan 13, 2016 at 10:15:03PM +0100, Jacob Carlborg via Digitalmars-d-learn wrote:
> Is it possible to somehow output a range of ranges to a single string
> buffer? For example, converting an array of integers to a string with
> the same representation as the source code.
> 
> import std.algorithm;
> import std.conv;
> import std.string;
> 
> void main()
> {
>     auto a = [1, 2, 3, 4, 5];
>     auto b = '[' ~ a.map!(e => e.to!string).join(", ") ~ ']';
>     assert(b == "[1, 2, 3, 4, 5]");
> }
> 
> The above code is straight forward. But I would like to avoid creating
> the intermediate strings, "e.to!string", and instead put the converted
> integer and the result of join directly in the same buffer.

Isn't that just a matter of replacing each of the segments with their
range equivalents? Also, std.format.formattedWrite will do
writeln-formatting into a buffer (well, any output range, really) -- I'm
pretty sure it doesn't allocate, at least for the simplest cases like
converting an integer. So you should be able to do something like this:

	auto data = [ 1, 2, 3, 4, 5 ];
	char[] buf = ...;
	formattedWrite(buf, "[%(%d, %)]", data);


T

-- 
Customer support: the art of getting your clients to pay for your own incompetence.


More information about the Digitalmars-d-learn mailing list