Created
August 17, 2020 10:08
-
-
Save usausa/d362e5292ef45d672c746d8e9bed9f41 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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