A game about forced loneliness, made by TACStudios
1using System; 2using System.Collections.Generic; 3 4namespace Unity.VisualScripting 5{ 6 public static class HashSetPool<T> 7 { 8 private static readonly object @lock = new object(); 9 private static readonly Stack<HashSet<T>> free = new Stack<HashSet<T>>(); 10 private static readonly HashSet<HashSet<T>> busy = new HashSet<HashSet<T>>(); 11 12 public static HashSet<T> New() 13 { 14 lock (@lock) 15 { 16 if (free.Count == 0) 17 { 18 free.Push(new HashSet<T>()); 19 } 20 21 var hashSet = free.Pop(); 22 23 busy.Add(hashSet); 24 25 return hashSet; 26 } 27 } 28 29 public static void Free(HashSet<T> hashSet) 30 { 31 lock (@lock) 32 { 33 if (!busy.Remove(hashSet)) 34 { 35 throw new ArgumentException("The hash set to free is not in use by the pool.", nameof(hashSet)); 36 } 37 38 hashSet.Clear(); 39 40 free.Push(hashSet); 41 } 42 } 43 } 44 45 public static class XHashSetPool 46 { 47 public static HashSet<T> ToHashSetPooled<T>(this IEnumerable<T> source) 48 { 49 var hashSet = HashSetPool<T>.New(); 50 51 foreach (var item in source) 52 { 53 hashSet.Add(item); 54 } 55 56 return hashSet; 57 } 58 59 public static void Free<T>(this HashSet<T> hashSet) 60 { 61 HashSetPool<T>.Free(hashSet); 62 } 63 } 64}