Skip to content

Instantly share code, notes, and snippets.

@jnm2
Last active August 1, 2024 03:24
Show Gist options
  • Save jnm2/73d378c5b52547728de1148d72de522a to your computer and use it in GitHub Desktop.
Save jnm2/73d378c5b52547728de1148d72de522a to your computer and use it in GitHub Desktop.
public ref struct LineEnumerator(ReadOnlySpan<char> text)
{
private ReadOnlySpan<char> text = text == default ? "" : text;
public bool MoveNext()
{
if (text == default)
return false;
var nextEnd = text.IndexOf('\n');
if (nextEnd != -1)
{
Current = text[..(nextEnd + 1)];
currentWithoutLineEnding = default;
text = text[(nextEnd + 1)..];
}
else
{
Current = text;
currentWithoutLineEnding = text;
text = default;
}
return true;
}
public ReadOnlySpan<char> Current { get; private set; }
private ReadOnlySpan<char> currentWithoutLineEnding;
public ReadOnlySpan<char> CurrentWithoutLineEnding
{
get
{
if (currentWithoutLineEnding == default)
{
var hasCrlf = Current is [.., '\r', _];
currentWithoutLineEnding = Current[..^(hasCrlf ? 2 : 1)];
}
return currentWithoutLineEnding;
}
}
}
public readonly ref struct LineEnumerable(ReadOnlySpan<char> text)
{
private readonly ReadOnlySpan<char> text = text;
public LineEnumerator GetEnumerator() => new(text);
}
public static class LineEnumerableExtensions
{
public static LineEnumerable EnumerateLines(this ReadOnlySpan<char> text) => new(text);
public static LineEnumerable EnumerateLines(this string text) => new(text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment