[RFC] replaceInto

Dmitry Olshansky dmitry.olsh at gmail.com
Sun Mar 4 12:48:52 PST 2012


This is proposal was dictated by a simple sudden need when designing 
with ranges in mind. It's to introduce into Phobos the idiomatic 
function replaceInto taking an output range to store the result in.

The signature revolves around:
void replace(..., Sink)(..., Sink sink)
if(... && isOutputRange!Sink)

Motivating example (std.array replace):

auto writer = stdout.lockingTextWriter; //or pick an Appender
foreach(line; stdin.byLine)
	writer.put(replace(line, "Nick", "Nicholas"));


Skiping hardcoded strings, and lockingTextWriter (it has problems) at 
the very deep level we see - what exactly? A horrible inefficiency, of 
course! There is no need to allocate space for replaced string and even 
doing it on buffer in-place risks allocation.

With proposed replaceInto:

auto writer = stdout.lockingTextWriter; //or pick an Appender
foreach(line; stdin.byLine)
	replaceInto(line, "Nick", "Nicholas", writer);

Look ma, no allocations!

Same goes for e.g. std.regex replace, coincidence, coincidence :)

P.S. A DIP 9 flashback?


-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list