Revert old behaviour of `ReadToEnd`

This commit is contained in:
Dean Herbert 2022-07-06 19:53:19 +09:00
parent 12d396a513
commit 01bc6e5cb7
2 changed files with 20 additions and 7 deletions

View File

@ -108,13 +108,19 @@ public void TestReadToEndNoPeeks()
[Test]
public void TestReadToEndAfterReadsAndPeeks()
{
const string contents = "first line\r\nsecond line";
const string contents = "this line is gone\rthis one shouldn't be\r\nthese ones\ndefinitely not";
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(contents)))
using (var bufferedReader = new LineBufferedReader(stream))
{
bufferedReader.PeekLine();
Assert.Throws<InvalidOperationException>(() => bufferedReader.ReadToEnd());
Assert.AreEqual("this line is gone", bufferedReader.ReadLine());
Assert.AreEqual("this one shouldn't be", bufferedReader.PeekLine());
string[] endingLines = bufferedReader.ReadToEnd().Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
Assert.AreEqual(3, endingLines.Length);
Assert.AreEqual("this one shouldn't be", endingLines[0]);
Assert.AreEqual("these ones", endingLines[1]);
Assert.AreEqual("definitely not", endingLines[2]);
}
}
}

View File

@ -46,14 +46,21 @@ public LineBufferedReader(Stream stream, bool leaveOpen = false)
/// <summary>
/// Reads the stream to its end and returns the text read.
/// Not compatible with calls to <see cref="PeekLine"/>.
/// This includes any peeked but unconsumed lines.
/// </summary>
public string ReadToEnd()
{
if (peekedLine != null)
throw new InvalidOperationException($"Do not use {nameof(ReadToEnd)} when also peeking for lines.");
string remainingText = streamReader.ReadToEnd();
if (peekedLine == null)
return remainingText;
return streamReader.ReadToEnd();
var builder = new StringBuilder();
// this might not be completely correct due to varying platform line endings
builder.AppendLine(peekedLine);
builder.Append(remainingText);
return builder.ToString();
}
public void Dispose()