forked from sarbian/ModuleManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImmutableStack.cs
More file actions
82 lines (67 loc) · 2.26 KB
/
Copy pathImmutableStack.cs
File metadata and controls
82 lines (67 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using System;
using System.Collections;
using System.Collections.Generic;
namespace ModuleManager.Collections
{
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;
public ImmutableStack(T value)
{
this.value = value;
}
private ImmutableStack(T value, ImmutableStack<T> parent)
{
this.value = value;
this.parent = parent;
}
public bool IsRoot => parent == null;
public ImmutableStack<T> Root => IsRoot? this : parent.Root;
public int Depth => IsRoot ? 1 : parent.Depth + 1;
public ImmutableStack<T> Push(T newValue)
{
return new ImmutableStack<T>(newValue, this);
}
public ImmutableStack<T> Pop()
{
if (IsRoot) throw new InvalidOperationException("Cannot pop from the root of a stack");
return parent;
}
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();
}
}