add util: StringStreamEnumerable

This commit is contained in:
John Colvin committed 2024-01-13 12:56:31 -05:00
1 parent 99106a8a73
commit 98b25ee17e
2 files changed
+64

No files matched your search

@@ -0,0 +1,19 @@
#nullable enable
namespace Spark.Core.Collections {
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class StringStreamEnumerable : IEnumerable<string> {
readonly StreamReader reader;
public StringStreamEnumerable(StreamReader reader) =>
this.reader = reader;
public IEnumerator<string> GetEnumerator() =>
new StringStreamEnumerator(reader);
IEnumerator IEnumerable.GetEnumerator() =>
GetEnumerator();
}
}
@@ -0,0 +1,45 @@
#nullable enable
namespace Spark.Core.Collections {
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading;
public class StringStreamEnumerator : IEnumerator<string> {
StreamReader? readerBacking;
string? current;
bool isDone;
public StringStreamEnumerator(Stream stream, Func<string, bool>? isTerminalLine = null)
: this(new StreamReader(stream)) { }
public StringStreamEnumerator(StreamReader reader) =>
readerBacking = reader;
public string Current =>
current ?? throw new InvalidOperationException();
object IEnumerator.Current => Current;
StreamReader reader =>
readerBacking ?? throw new ObjectDisposedException(GetType().FullName);
public bool MoveNext() {
current = reader.ReadLine();
isDone = current is null;
return !isDone;
}
public void Reset() =>
// Can't reset the StreamReader
throw new NotSupportedException();
// Thread-safe, idempotent
public void Dispose() {
Interlocked.Exchange(ref readerBacking, null)?.Dispose();
current = null;
isDone = true;
}
}
}