using System; using System.Collections.Generic; namespace Unity.VisualScripting { public static class HashSetPool { private static readonly object @lock = new object(); private static readonly Stack> free = new Stack>(); private static readonly HashSet> busy = new HashSet>(); public static HashSet New() { lock (@lock) { if (free.Count == 0) { free.Push(new HashSet()); } var hashSet = free.Pop(); busy.Add(hashSet); return hashSet; } } public static void Free(HashSet hashSet) { lock (@lock) { if (!busy.Remove(hashSet)) { throw new ArgumentException("The hash set to free is not in use by the pool.", nameof(hashSet)); } hashSet.Clear(); free.Push(hashSet); } } } public static class XHashSetPool { public static HashSet ToHashSetPooled(this IEnumerable source) { var hashSet = HashSetPool.New(); foreach (var item in source) { hashSet.Add(item); } return hashSet; } public static void Free(this HashSet hashSet) { HashSetPool.Free(hashSet); } } }