A game about forced loneliness, made by TACStudios
1using System;
2using System.Collections.Generic;
3
4namespace Unity.VisualScripting
5{
6 public static class DictionaryPool<TKey, TValue>
7 {
8 private static readonly object @lock = new object();
9 private static readonly Stack<Dictionary<TKey, TValue>> free = new Stack<Dictionary<TKey, TValue>>();
10 private static readonly HashSet<Dictionary<TKey, TValue>> busy = new HashSet<Dictionary<TKey, TValue>>();
11
12 // Do not allow an IDictionary parameter here to avoid allocation on foreach
13 public static Dictionary<TKey, TValue> New(Dictionary<TKey, TValue> source = null)
14 {
15 lock (@lock)
16 {
17 if (free.Count == 0)
18 {
19 free.Push(new Dictionary<TKey, TValue>());
20 }
21
22 var dictionary = free.Pop();
23
24 busy.Add(dictionary);
25
26 if (source != null)
27 {
28 foreach (var kvp in source)
29 {
30 dictionary.Add(kvp.Key, kvp.Value);
31 }
32 }
33
34 return dictionary;
35 }
36 }
37
38 public static void Free(Dictionary<TKey, TValue> dictionary)
39 {
40 lock (@lock)
41 {
42 if (!busy.Contains(dictionary))
43 {
44 throw new ArgumentException("The dictionary to free is not in use by the pool.", nameof(dictionary));
45 }
46
47 dictionary.Clear();
48
49 busy.Remove(dictionary);
50
51 free.Push(dictionary);
52 }
53 }
54 }
55}