From b80820e50f5f1e3e6ecef5c7f97c0425824a28a8 Mon Sep 17 00:00:00 2001 From: Sebastian Wilzbach Date: Sun, 24 Dec 2017 11:21:16 +0100 Subject: [PATCH] std.range.nullSink - allow convenient use of the NullSink `nullSink` returns the `NullSink` by reference and thus allows using it directly in code which expects an OutputRange by reference. The pattern is providing convenience wrappers for struct construction is very common in Phobos, e.g. `rebindable`, `nullable`, `refCounted`, ... --- changelog/std-range-nullsink.dd | 20 +++++++++++++++++ std/range/package.d | 38 ++++++++++++++++++++++++++++++--- 2 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 changelog/std-range-nullsink.dd diff --git a/changelog/std-range-nullsink.dd b/changelog/std-range-nullsink.dd new file mode 100644 index 000000000..518009496 --- /dev/null +++ b/changelog/std-range-nullsink.dd @@ -0,0 +1,20 @@ +`nullSink` was added to `std.range` + +$(REF nullSink, std, range) is a convenience wrapper for $(REF NullSink, std,range) +and creates an output range that discards the data it receives. It's the range analog +of `/dev/null`. + +--- +import std.csv : csvNextToken; + +string line = "a,b,c"; + +// ignore the first column +line.csvNextToken(nullSink, ',', '"'); +line.popFront; + +// look at the second column +Appender!string app; +line.csvNextToken(app, ',', '"'); +assert(app.data == "b"); +--- diff --git a/std/range/package.d b/std/range/package.d index 8f2cd1966..b88a3014f 100644 --- a/std/range/package.d +++ b/std/range/package.d @@ -117,7 +117,7 @@ $(BOOKTABLE , loop. Similar to $(D zip), except that $(D lockstep) is designed especially for $(D foreach) loops. )) - $(TR $(TD $(LREF NullSink)) + $(TR $(TD $(LREF nullSink)) $(TD An output _range that discards the data it receives. )) $(TR $(TD $(LREF only)) @@ -11547,14 +11547,46 @@ struct NullSink void put(E)(E){} } +/// ditto +auto ref nullSink() +{ + static NullSink sink; + return sink; +} + /// -@safe unittest +@safe nothrow unittest { import std.algorithm.iteration : map; import std.algorithm.mutation : copy; - [4, 5, 6].map!(x => x * 2).copy(NullSink()); // data is discarded + [4, 5, 6].map!(x => x * 2).copy(nullSink); // data is discarded } +/// +@safe unittest +{ + import std.csv : csvNextToken; + + string line = "a,b,c"; + + // ignore the first column + line.csvNextToken(nullSink, ',', '"'); + line.popFront; + + // look at the second column + Appender!string app; + line.csvNextToken(app, ',', '"'); + assert(app.data == "b"); +} + +@safe unittest +{ + auto r = 10.iota + .tee(nullSink) + .dropOne; + + assert(r.front == 1); +} /++