Skip to content

Instantly share code, notes, and snippets.

@usausa
Created August 17, 2020 10:08
Show Gist options
  • Save usausa/d362e5292ef45d672c746d8e9bed9f41 to your computer and use it in GitHub Desktop.
Save usausa/d362e5292ef45d672c746d8e9bed9f41 to your computer and use it in GitHub Desktop.
public struct WrapEnumerator<T> : IEnumerator<T>
{
private readonly IEnumerator<T> source;
private bool first;
public WrapEnumerator(IEnumerator<T> source)
{
this.source = source;
first = true;
}
public bool MoveNext()
{
if (first)
{
first = false;
return source != null;
}
return source.MoveNext();
}
public void Reset() => throw new NotSupportedException();
public T Current => source.Current;
object IEnumerator.Current => Current;
public void Dispose()
{
source?.Dispose();
}
}
public readonly struct WrapEnumerable<T> : IEnumerable<T>
{
private readonly IEnumerator<T> source;
public bool HasValue { get; }
public WrapEnumerable(IEnumerable<T> source)
{
var enumerator = source.GetEnumerator();
try
{
HasValue = enumerator.MoveNext();
if (!HasValue)
{
enumerator.Dispose();
this.source = null;
}
else
{
this.source = enumerator;
}
}
catch (Exception)
{
enumerator.Dispose();
throw;
}
}
public IEnumerator<T> GetEnumerator() => new WrapEnumerator<T>(HasValue ? source : null);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment