Last active
February 19, 2019 23:16
-
-
Save mjs3339/0819bae2eef80fd26bb7292b539b6e75 to your computer and use it in GitHub Desktop.
C# Tiny HashSet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[DebuggerTypeProxy(typeof(HashSetDebugViewInt<>))] | |
[DebuggerDisplay("Count = {Count}")] | |
[Serializable] | |
public class TinyHashSet<T> : TinySet<T>, IEnumerable<T> | |
{ | |
public TinyHashSet() : this(EqualityComparer<T>.Default) | |
{ | |
} | |
public TinyHashSet(IEqualityComparer<T> comparer) | |
{ | |
if(Comparer == null) | |
Comparer = EqualityComparer<T>.Default; | |
Comparer = comparer; | |
} | |
public TinyHashSet(IEnumerable<T> collection) | |
{ | |
Comparer = EqualityComparer<T>.Default; | |
foreach(var item in collection) | |
Add(item); | |
} | |
IEnumerator<T> IEnumerable<T>.GetEnumerator() | |
{ | |
return new Enumerator(this); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return new Enumerator(this); | |
} | |
/// <summary> | |
/// Will not include duplicate entries. | |
/// </summary> | |
public void AddUnique(IEnumerable<T> collection) | |
{ | |
foreach(var item in collection) | |
Add(item); | |
} | |
public Enumerator GetEnumerator() | |
{ | |
return new Enumerator(this); | |
} | |
[Serializable] | |
public struct Enumerator : IEnumerator<T> | |
{ | |
private readonly TinyHashSet<T> ths; | |
private int index; | |
public T Current{get; private set;} | |
object IEnumerator.Current | |
{ | |
get | |
{ | |
if(index == 0 || index == ths.Count + 1) | |
throw new InvalidOperationException($"Enumerator out of range: {index}"); | |
return Current; | |
} | |
} | |
internal Enumerator(TinyHashSet<T> set) | |
{ | |
ths = set; | |
index = 0; | |
Current = default; | |
} | |
public void Dispose() | |
{ | |
} | |
public bool MoveNext() | |
{ | |
if(index < ths.Count) | |
{ | |
Current = ths.Slots[index].Value; | |
index++; | |
return true; | |
} | |
index = ths.Count + 1; | |
Current = default; | |
return false; | |
} | |
void IEnumerator.Reset() | |
{ | |
index = 0; | |
Current = default; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment