using System; using System.Collections.Generic; using System.Linq; namespace Unity.VisualScripting { public static class ArrayPool { private static readonly object @lock = new object(); private static readonly Dictionary> free = new Dictionary>(); private static readonly HashSet busy = new HashSet(); public static T[] New(int length) { lock (@lock) { if (!free.ContainsKey(length)) { free.Add(length, new Stack()); } if (free[length].Count == 0) { free[length].Push(new T[length]); } var array = free[length].Pop(); busy.Add(array); return array; } } public static void Free(T[] array) { lock (@lock) { if (!busy.Contains(array)) { throw new ArgumentException("The array to free is not in use by the pool.", nameof(array)); } for (var i = 0; i < array.Length; i++) { array[i] = default(T); } busy.Remove(array); free[array.Length].Push(array); } } } public static class XArrayPool { public static T[] ToArrayPooled(this IEnumerable source) { var array = ArrayPool.New(source.Count()); var i = 0; foreach (var item in source) { array[i++] = item; } return array; } public static void Free(this T[] array) { ArrayPool.Free(array); } } }