Skip to content

Commit be1db03

Browse files
committed
std.conv: add writeText, writeWText, writeDText
These are variants of text, wtext, and dtext that write their output to an output range instead of returning a string. Fixes dlang#10550
1 parent 106f307 commit be1db03

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

std/conv.d

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ $(TR $(TD Strings) $(TD
1818
$(LREF text)
1919
$(LREF wtext)
2020
$(LREF dtext)
21+
$(LREF writeText)
22+
$(LREF writeWText)
23+
$(LREF writeDText)
2124
$(LREF hexString)
2225
))
2326
$(TR $(TD Numeric) $(TD
@@ -4834,6 +4837,75 @@ if (T.length > 0) { return textImpl!dstring(args); }
48344837
assert(dtext(cs, ' ', ws, " ", ds) == "今日は 여보세요 Здравствуйте"d);
48354838
}
48364839

4840+
/// Convenience functions for writing arguments to an output range as text.
4841+
void writeText(Sink, T...)(ref Sink sink, T args)
4842+
if (isOutputRange!(Sink, char) && T.length > 0)
4843+
{
4844+
sink.writeTextImpl!string(args);
4845+
}
4846+
4847+
/// ditto
4848+
void writeWText(Sink, T...)(ref Sink sink, T args)
4849+
if (isOutputRange!(Sink, wchar) && T.length > 0)
4850+
{
4851+
sink.writeTextImpl!wstring(args);
4852+
}
4853+
4854+
/// ditto
4855+
void writeDText(Sink, T...)(ref Sink sink, T args)
4856+
if (isOutputRange!(Sink, dchar) && T.length > 0)
4857+
{
4858+
sink.writeTextImpl!dstring(args);
4859+
}
4860+
4861+
///
4862+
@safe unittest
4863+
{
4864+
import std.array : appender;
4865+
4866+
auto output = appender!string();
4867+
output.writeText("The answer is ", 42);
4868+
4869+
assert(output.data == "The answer is 42");
4870+
}
4871+
4872+
///
4873+
@safe unittest
4874+
{
4875+
import std.array : appender;
4876+
4877+
const color = "red";
4878+
auto output = appender!string();
4879+
output.writeText(i"My favorite color is $(color)");
4880+
4881+
assert(output.data == "My favorite color is red");
4882+
}
4883+
4884+
@safe unittest
4885+
{
4886+
auto capp = appender!string();
4887+
auto wapp = appender!wstring();
4888+
auto dapp = appender!dstring();
4889+
4890+
capp.writeText(42, ' ', 1.5, ": xyz");
4891+
wapp.writeWText(42, ' ', 1.5, ": xyz");
4892+
dapp.writeDText(42, ' ', 1.5, ": xyz");
4893+
4894+
assert(capp.data == "42 1.5: xyz"c);
4895+
assert(wapp.data == "42 1.5: xyz"w);
4896+
assert(dapp.data == "42 1.5: xyz"d);
4897+
}
4898+
4899+
// Check range API compliance using OutputRange interface
4900+
@system unittest
4901+
{
4902+
import std.range.interfaces : OutputRange, outputRangeObject;
4903+
import std.range : nullSink;
4904+
4905+
OutputRange!char testOutput = outputRangeObject!char(nullSink);
4906+
testOutput.writeText(42, ' ', 1.5, ": xyz");
4907+
}
4908+
48374909
private S textImpl(S, U...)(U args)
48384910
{
48394911
static if (U.length == 0)

0 commit comments

Comments
 (0)