Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1.    internal static class CacheComponents<T> where T : struct, IComponent {
  2.         private static int        capacity;
  3.         private static int        length;
  4.         private static T[]        components;
  5.         private static Queue<int> freeIndexes;
  6.  
  7.         static CacheComponents() {
  8.             capacity = 16;
  9.             length   = 0;
  10.  
  11.             components  = new T[capacity];
  12.             freeIndexes = new Queue<int>();
  13.            
  14.             ComponentsCleaner.Register(CacheTypeIdentifier<T>.typeID, Remove);
  15.         }
  16.  
  17.         public static int Add(T component) {
  18.             if (freeIndexes.Count > 0) {
  19.                 var id = freeIndexes.Dequeue();
  20.                 components[id] = component;
  21.                 return id;
  22.             }
  23.  
  24.             if (capacity < length) {
  25.                 var newCapacity = capacity * 2;
  26.                 Array.Resize(ref components, newCapacity);
  27.                 capacity = newCapacity;
  28.             }
  29.  
  30.             var newID = length;
  31.             components[newID] = component;
  32.             length++;
  33.             return newID;
  34.         }
  35.  
  36.         public static ref T Get(int id) => ref components[id];
  37.  
  38.         public static bool Remove(int id) {
  39.             if (length >= id && !freeIndexes.Contains(id)) {
  40.                 freeIndexes.Enqueue(id);
  41.                 return true;
  42.             }
  43.  
  44.             return false;
  45.         }
  46.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement