From 98b25ee17e56c8e2bf0fd01a05f4dbd9989be260 Mon Sep 17 00:00:00 2001 From: John Colvin Date: Wed, 25 Oct 2023 13:49:38 -0400 Subject: [PATCH] add util: StringStreamEnumerable --- .../Collections/StringStreamEnumerable.cs | 19 ++++++++ .../Collections/StringStreamEnumerator.cs | 45 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 src/client/spark_core/Collections/StringStreamEnumerable.cs create mode 100644 src/client/spark_core/Collections/StringStreamEnumerator.cs diff --git a/src/client/spark_core/Collections/StringStreamEnumerable.cs b/src/client/spark_core/Collections/StringStreamEnumerable.cs new file mode 100644 index 000000000..cd1daf983 --- /dev/null +++ b/src/client/spark_core/Collections/StringStreamEnumerable.cs @@ -0,0 +1,19 @@ +#nullable enable +namespace Spark.Core.Collections { + using System.Collections; + using System.Collections.Generic; + using System.IO; + + public class StringStreamEnumerable : IEnumerable { + readonly StreamReader reader; + + public StringStreamEnumerable(StreamReader reader) => + this.reader = reader; + + public IEnumerator GetEnumerator() => + new StringStreamEnumerator(reader); + + IEnumerator IEnumerable.GetEnumerator() => + GetEnumerator(); + } +} diff --git a/src/client/spark_core/Collections/StringStreamEnumerator.cs b/src/client/spark_core/Collections/StringStreamEnumerator.cs new file mode 100644 index 000000000..2b383a2a9 --- /dev/null +++ b/src/client/spark_core/Collections/StringStreamEnumerator.cs @@ -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 { + StreamReader? readerBacking; + string? current; + bool isDone; + + public StringStreamEnumerator(Stream stream, Func? 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; + } + } +}