A game about forced loneliness, made by TACStudios
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5namespace Unity.VisualScripting
6{
7 public static class ArrayPool<T>
8 {
9 private static readonly object @lock = new object();
10 private static readonly Dictionary<int, Stack<T[]>> free = new Dictionary<int, Stack<T[]>>();
11 private static readonly HashSet<T[]> busy = new HashSet<T[]>();
12
13 public static T[] New(int length)
14 {
15 lock (@lock)
16 {
17 if (!free.ContainsKey(length))
18 {
19 free.Add(length, new Stack<T[]>());
20 }
21
22 if (free[length].Count == 0)
23 {
24 free[length].Push(new T[length]);
25 }
26
27 var array = free[length].Pop();
28
29 busy.Add(array);
30
31 return array;
32 }
33 }
34
35 public static void Free(T[] array)
36 {
37 lock (@lock)
38 {
39 if (!busy.Contains(array))
40 {
41 throw new ArgumentException("The array to free is not in use by the pool.", nameof(array));
42 }
43
44 for (var i = 0; i < array.Length; i++)
45 {
46 array[i] = default(T);
47 }
48
49 busy.Remove(array);
50
51 free[array.Length].Push(array);
52 }
53 }
54 }
55
56 public static class XArrayPool
57 {
58 public static T[] ToArrayPooled<T>(this IEnumerable<T> source)
59 {
60 var array = ArrayPool<T>.New(source.Count());
61
62 var i = 0;
63
64 foreach (var item in source)
65 {
66 array[i++] = item;
67 }
68
69 return array;
70 }
71
72 public static void Free<T>(this T[] array)
73 {
74 ArrayPool<T>.Free(array);
75 }
76 }
77}