Skip to content

Commit

Permalink
Merge pull request #5 from bridgefield/immutable-list-performance
Browse files Browse the repository at this point in the history
  • Loading branch information
apfohl authored Dec 11, 2021
2 parents e2ab762 + 604c1b3 commit 84f76ba
Showing 1 changed file with 44 additions and 8 deletions.
52 changes: 44 additions & 8 deletions FoundationalBits/Messaging/ImmutableList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,8 @@ public TResult Match<TResult>(Func<TResult> empty, Func<T, IBucket, TResult> hea

private sealed record TailedBucket(T Head, IBucket Tail) : IBucket
{
public IEnumerable<T> AsEnumerable()
{
yield return Head;
foreach (var item in Tail.AsEnumerable())
{
yield return item;
}
}
public IEnumerable<T> AsEnumerable() =>
new TailedBucketEnumerable(this);

public ImmutableList<T> ToList() => new(this);

Expand All @@ -72,5 +66,47 @@ public TResult Match<TResult>(
Func<TResult> empty,
Func<T, IBucket, TResult> headAndTail) => headAndTail(Head, Tail);
}

private sealed class TailedBucketEnumerable : IEnumerable<T>
{
private readonly TailedBucket bucket;

public TailedBucketEnumerable(TailedBucket bucket) => this.bucket = bucket;

public IEnumerator<T> GetEnumerator() => new TailedBucketEnumerator(bucket);

IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

private sealed class TailedBucketEnumerator : IEnumerator<T>
{
private TailedBucket currentBucket;
private bool started;
private bool hasMore = true;

public TailedBucketEnumerator(TailedBucket currentBucket) => this.currentBucket = currentBucket;

public bool MoveNext()
{
if (!started)
started = true;
else if (currentBucket.Tail is TailedBucket tail)
currentBucket = tail;
else
hasMore = false;

return hasMore;
}

public void Reset()
{
}

public T Current => currentBucket.Head;

object IEnumerator.Current => Current;

public void Dispose() => Reset();
}
}
}

0 comments on commit 84f76ba

Please sign in to comment.