-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathOrderedSet.cs
118 lines (99 loc) · 3.21 KB
/
OrderedSet.cs
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
using System;
using System.Collections;
using System.Collections.Generic;
namespace RuntimeUnityEditor.Core.ObjectTree
{
/// <summary>
/// Based on OrderedSet from answer https://stackoverflow.com/a/17853085 by AndreasHassing and George Mamaladze
/// </summary>
/// <inheritdoc />
internal class OrderedSet<T> : ICollection<T>
{
private readonly IDictionary<T, LinkedListNode<T>> _mDictionary;
private readonly LinkedList<T> _mLinkedList;
public OrderedSet()
: this(EqualityComparer<T>.Default)
{
}
public OrderedSet(IEqualityComparer<T> comparer)
{
_mDictionary = new Dictionary<T, LinkedListNode<T>>(comparer);
_mLinkedList = new LinkedList<T>();
}
public int Count => _mDictionary.Count;
public virtual bool IsReadOnly => _mDictionary.IsReadOnly;
void ICollection<T>.Add(T item)
{
AddLast(item);
}
public bool AddLast(T item)
{
if (_mDictionary.ContainsKey(item)) return false;
var node = _mLinkedList.AddLast(item);
_mDictionary.Add(item, node);
return true;
}
public bool InsertSorted(T item, IComparer<T> comparer)
{
if (_mDictionary.ContainsKey(item)) return false;
var currentNode = _mLinkedList.First;
while (currentNode != null)
{
if (comparer.Compare(currentNode.Value, item) >= 0)
{
_mLinkedList.AddBefore(currentNode, item);
break;
}
currentNode = currentNode.Next;
}
if (currentNode == null)
currentNode = _mLinkedList.AddLast(item);
_mDictionary.Add(item, currentNode);
return true;
}
public void Clear()
{
_mLinkedList.Clear();
_mDictionary.Clear();
}
public bool Remove(T item)
{
if (item == null) return false;
var found = _mDictionary.TryGetValue(item, out var node);
if (!found) return false;
_mDictionary.Remove(item);
_mLinkedList.Remove(node);
return true;
}
public IEnumerator<T> GetEnumerator()
{
return _mLinkedList.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool Contains(T item)
{
return item != null && _mDictionary.ContainsKey(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_mLinkedList.CopyTo(array, arrayIndex);
}
public void RemoveAll(Predicate<T> func)
{
var currentNode = _mLinkedList.First;
while (currentNode != null)
{
var nextNode = currentNode.Next;
if (func(currentNode.Value))
{
_mDictionary.Remove(currentNode.Value);
_mLinkedList.Remove(currentNode);
}
currentNode = nextNode;
}
}
}
}