DotnetStandardStreams/source/DotnetStreams/ListTextSource.cs
2025-05-15 13:27:49 -06:00

72 lines
1.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotnetStreams
{
public class ListTextSource : ITextSource
{
private bool isEof;
private readonly IEnumerable<string> source;
private IEnumerator<string>? enumerator;
//private string lastValue;
private bool firstIsRead;
private string nextLine;
public ListTextSource(IEnumerable<string> source)
{
this.source = source;
enumerator = null;
firstIsRead = false;
nextLine = string.Empty;
}
public virtual void Open()
{
}
public virtual IEnumerable<string> ReadAll()
{
return source.AsEnumerable();
}
public virtual string Read()
{
if (enumerator == null)
enumerator = source.GetEnumerator();
string thisLine;
if (!firstIsRead)
{
// Read the first, put it in the "last" buffer.
isEof = !enumerator.MoveNext();
nextLine = enumerator.Current;
firstIsRead = true;
}
thisLine = nextLine;
if (!isEof)
{
isEof = !enumerator.MoveNext();
if (!isEof)
nextLine = enumerator.Current;
else
nextLine = string.Empty;
}
return thisLine;
}
public virtual bool Eof() => isEof;
public virtual void Close()
{
enumerator = null;
isEof = false;
}
}
}