Skip to content

Commit

Permalink
Fix RBTree enumeration
Browse files Browse the repository at this point in the history
Implement IEnumerable<T> to allow generic enumeration.

Also use a List for the enumerator to avoid internal multiple
enumeration with LINQ. (i.e. don't use ElementAt)
  • Loading branch information
jeremy-visionaid committed Sep 30, 2024
1 parent 3517b4b commit b7af36b
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions sources/OpenMcdf/RBTree/RBTree.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#define ASSERT

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

Expand Down Expand Up @@ -88,7 +89,7 @@ Color Color
void AssignValueTo(IRBNode other);
}

public class RBTree
public class RBTree : IEnumerable<IRBNode>
{
public IRBNode Root { get; set; }

Expand Down Expand Up @@ -513,25 +514,25 @@ private void DoVisitTreeNodes(Action<IRBNode> action, IRBNode walker)
public class RBTreeEnumerator : IEnumerator<IRBNode>
{
int position = -1;
private readonly Queue<IRBNode> heap = new Queue<IRBNode>();
private readonly List<IRBNode> list = new();

internal RBTreeEnumerator(RBTree tree)
{
tree.VisitTreeNodes(item => heap.Enqueue(item));
tree.VisitTreeNodes(item => list.Add(item));
}

public IRBNode Current => heap.ElementAt(position);

public void Dispose()
{
}

object System.Collections.IEnumerator.Current => heap.ElementAt(position);
public IRBNode Current => list[position];

object IEnumerator.Current => list[position];

public bool MoveNext()
{
position++;
return position < heap.Count;
return position < list.Count;
}

public void Reset()
Expand All @@ -540,10 +541,9 @@ public void Reset()
}
}

public RBTreeEnumerator GetEnumerator()
{
return new RBTreeEnumerator(this);
}
public IEnumerator<IRBNode> GetEnumerator() => new RBTreeEnumerator(this);

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

private const int INDENT_STEP = 15;

Expand Down

0 comments on commit b7af36b

Please sign in to comment.