Skip to content

Commit

Permalink
Implement IEnumerable<T>
Browse files Browse the repository at this point in the history
  • Loading branch information
blowfishpro committed Aug 27, 2017
1 parent 8685da9 commit 038db23
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 1 deletion.
45 changes: 44 additions & 1 deletion Collections/ImmutableStack.cs
@@ -1,9 +1,48 @@
using System;
using System.Collections;
using System.Collections.Generic;

namespace ModuleManager.Collections
{
public class ImmutableStack<T>
public class ImmutableStack<T> : IEnumerable<T>
{
public struct Enumerator : IEnumerator<T>
{
private ImmutableStack<T> head;
private ImmutableStack<T> currentStack;

public Enumerator(ImmutableStack<T> stack)
{
head = stack;
currentStack = null;
}

public T Current => currentStack.value;
object IEnumerator.Current => Current;

public void Dispose() { }

public bool MoveNext()
{
if (currentStack == null)
{
currentStack = head;
return true;
}
else if (!currentStack.IsRoot)
{
currentStack = currentStack.parent;
return true;
}
else
{
return false;
}
}

public void Reset() => currentStack = null;
}

public readonly T value;
public readonly ImmutableStack<T> parent;

Expand Down Expand Up @@ -33,5 +72,9 @@ public ImmutableStack<T> Pop()
}

public ImmutableStack<T> ReplaceValue(T newValue) => new ImmutableStack<T>(newValue, parent);

public Enumerator GetEnumerator() => new Enumerator(this);
IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
26 changes: 26 additions & 0 deletions Extensions/NodeStackExtensions.cs
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NodeStack = ModuleManager.Collections.ImmutableStack<ConfigNode>;

namespace ModuleManager.Extensions
{
public static class NodeStackExtensions
{
public static string GetPath(this NodeStack stack)
{
int length = stack.Sum(node => node.name.Length) + stack.Depth - 1;
StringBuilder sb = new StringBuilder(length);

foreach (ConfigNode node in stack)
{
string nodeName = node.name;
sb.Insert(0, node.name);
if (sb.Length < sb.Capacity) sb.Insert(0, '/');
}

return sb.ToString();
}
}
}

0 comments on commit 038db23

Please sign in to comment.