MotionCollections.cs
Runtime/Collections/MotionCollections.cs
1 using System;
2 using System.Runtime.InteropServices;
3 using System.Threading;
4
5 namespace MeatMotion.Collections
6 {
7 [StructLayout(LayoutKind.Auto)]
8 #if UNITY_6000_7_OR_NEWER
9 [Unity.Scripting.LifecycleManagement.NoAutoStaticsCleanup] // Immutable.
10 #endif
11 public struct FastListCore<T>
12 {
13 public static readonly FastListCore<T> Empty = default;
14 T[] items;
15 int count;
16 public readonly int Length => count;
17 public readonly T this[int index] { get => items[index]; set => items[index] = value; }
18 public readonly Span<T> AsSpan() => items.AsSpan(0, count);
19 public readonly T[] AsArray() => items;
20
21 public void EnsureCapacity(int capacity)
22 {
23 if (items != null && items.Length >= capacity) return;
24 int length = items?.Length ?? 8;
25 while (length < capacity) length = checked(length * 2);
26 Array.Resize(ref items, length);
27 }
28
29 public void Add(T element)
30 {
31 if (items == null || count == items.Length) EnsureCapacity(checked(count + 1));
32 items[count++] = element;
33 }
34
35 public void RemoveAtSwapback(int index)
36 {
37 if ((uint)index >= (uint)count) throw new IndexOutOfRangeException();
38 items[index] = items[--count];
39 items[count] = default;
40 }
41
42 public void Clear(bool removeArray = false)
43 {
44 if (items != null) Array.Clear(items, 0, items.Length);
45 if (removeArray) items = null;
46 count = 0;
47 }
48 }
49
50 public interface ILinkedPoolNode<T> where T : class
51 {
52 ref T NextNode { get; }
53 }
54
55 [StructLayout(LayoutKind.Auto)]
56 public struct LinkedPool<T> where T : class, ILinkedPoolNode<T>
57 {
58 T first, last;
59 int gate, count;
60 public readonly int Size => count;
61
62 public bool TryPush(T item)
63 {
64 if (item == null || Interlocked.CompareExchange(ref gate, 1, 0) != 0) return false;
65 try
66 {
67 ref var link = ref item.NextNode;
68 if (link != null || ReferenceEquals(item, last) || count == int.MaxValue) return false;
69 if (first == null) last = item;
70 link = first;
71 first = item;
72 count++;
73 return true;
74 }
75 finally { Volatile.Write(ref gate, 0); }
76 }
77
78 public bool TryPop(out T result)
79 {
80 result = null;
81 if (Interlocked.CompareExchange(ref gate, 1, 0) != 0) return false;
82 try
83 {
84 if (first == null) return false;
85 ref var link = ref first.NextNode;
86 result = first;
87 first = link;
88 link = null;
89 if (first == null) last = null;
90 count--;
91 return true;
92 }
93 finally { Volatile.Write(ref gate, 0); }
94 }
95 }
96 }
97