summaryrefslogtreecommitdiff
path: root/Other/NodeEditorExamples/Assets/UNEB/Utility/FiniteStack.cs
blob: 2faac0f1c4156977ca07e15562607fc5814cf59b (plain)
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

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

namespace UNEB.Utility
{
    /// <summary>
    /// A simple stack with a limited capacity.
    /// In order to make more room, the first element (not the top) in the stack is removed.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class FiniteStack<T> : IEnumerable<T>
    {
        private LinkedList<T> _container;
        private int _capacity;

        /// <summary>
        /// Called when the stack runs out of space and removes
        /// the first item (bottom of stack) to make room.
        /// </summary>
        public event Action<T> OnRemoveBottomItem;

        public FiniteStack(int capacity)
        {
            _container = new LinkedList<T>();
            _capacity = capacity;
        }

        public void Push(T value)
        {
            _container.AddLast(value);

            // Out of room, remove the first element in the stack.
            if (_container.Count == _capacity) {

                T first = _container.First.Value;
                _container.RemoveFirst();

                if (OnRemoveBottomItem != null)
                    OnRemoveBottomItem(first);
            }
        }

        public T Peek()
        {
            return _container.Last.Value;
        }

        public T Pop()
        {
            var lastVal = _container.Last.Value;
            _container.RemoveLast();

            return lastVal;
        }

        public void Clear()
        {
            _container.Clear();
        }

        public int Count
        {
            get { return _container.Count; }
        }

        public IEnumerator<T> GetEnumerator()
        {
            return _container.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _container.GetEnumerator();
        }
    }
}