Can't recreate a range?

Casey noman at email.com
Thu Apr 30 13:04:47 UTC 2020


Here's a minimal code example that duplicates the issue:

import std.array, std.range, std.stdio, std.traits, std.string;

auto readStream(Range)(auto ref Range r) if 
(isInputRange!(Unqual!Range))
{
	struct StreamRange(Range)
	{
		alias R = Unqual!Range;
		R _input;

		auto buff = appender!string;

		this(R input)
		{
			this._input = input;
		}

		bool empty()
		{
			return this._input.empty;
		}

		string front()
		{
			if (buff.capacity == 0)
			{
				bool iterate = true;
				bool doCapture = false;
				buff.reserve(1000);

				while (iterate)
				{
					if (this._input.empty)
						break;

					auto value = this._input.front;
					if (value.strip == "<main>")
					{
						doCapture = true;
						buff.put(value.strip);
						buff.put("\n");
					}
					else if (value.strip == "</main>")
					{
						buff.put(value.strip);
						doCapture = false;
						iterate = false;
					}
					else if (doCapture)
					{
						buff.put(value.strip);
						buff.put("\n");
					}
					this._input.popFront();
				}
			}
			return buff[];
		}

		void popFront()
		{
			buff = appender!string;
		}
	}

	return StreamRange!(Range)(r);
}

unittest
{
	auto range = readStream(File("test1.xml").byLine);
	int count = 0;
	while (!range.empty)
	{
		writeln(range.front);
		count++;
		writeln("Current count: ", count);
		range.popFront();
	}
	assert(count == 1);
}

unittest
{
	auto range = readStream(File("test2.xml").byLine);
	int count = 0;
	while (!range.empty)
	{
		writeln(range.front);
		count++;
		writeln("Current count: ", count);
		range.popFront();
	}
	assert(count == 1);
}


Here are the two XML files (very simple):

<?xml version="1.0">
<main>
	<text>Here is some text for the first file.</text>
</main>

<?xml version="1.0">
<main>
	<text>Here is some text for the second file.</text>
</main>

I've even tried putting wrapping the code that is being tested in 
a function and looping over it with different parameters 
(filename and expected count) without any luck either.  I've also 
tried declaring the file handle separate and ensuring it was 
closed.  No luck.


More information about the Digitalmars-d-learn mailing list