No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CollectionHelper.cs 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. using Unity.Collections.LowLevel.Unsafe;
  5. using Unity.Burst;
  6. using Unity.Burst.CompilerServices;
  7. using Unity.Jobs;
  8. using Unity.Jobs.LowLevel.Unsafe;
  9. using Unity.Mathematics;
  10. #if !NET_DOTS
  11. using System.Reflection;
  12. #endif
  13. namespace Unity.Collections
  14. {
  15. /// <summary>
  16. /// For scheduling release of unmanaged resources.
  17. /// </summary>
  18. public interface INativeDisposable : IDisposable
  19. {
  20. /// <summary>
  21. /// Creates and schedules a job that will release all resources (memory and safety handles) of this collection.
  22. /// </summary>
  23. /// <param name="inputDeps">A job handle which the newly scheduled job will depend upon.</param>
  24. /// <returns>The handle of a new job that will release all resources (memory and safety handles) of this collection.</returns>
  25. JobHandle Dispose(JobHandle inputDeps);
  26. }
  27. /// <summary>
  28. /// Provides helper methods for collections.
  29. /// </summary>
  30. [BurstCompatible]
  31. public static class CollectionHelper
  32. {
  33. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  34. internal static void CheckAllocator(AllocatorManager.AllocatorHandle allocator)
  35. {
  36. if (!ShouldDeallocate(allocator))
  37. throw new ArgumentException($"Allocator {allocator} must not be None or Invalid");
  38. }
  39. /// <summary>
  40. /// The size in bytes of the current platform's L1 cache lines.
  41. /// </summary>
  42. /// <value>The size in bytes of the current platform's L1 cache lines.</value>
  43. public const int CacheLineSize = JobsUtility.CacheLineSize;
  44. [StructLayout(LayoutKind.Explicit)]
  45. internal struct LongDoubleUnion
  46. {
  47. [FieldOffset(0)]
  48. internal long longValue;
  49. [FieldOffset(0)]
  50. internal double doubleValue;
  51. }
  52. /// <summary>
  53. /// Returns the binary logarithm of the `value`, but the result is rounded down to the nearest integer.
  54. /// </summary>
  55. /// <param name="value">The value.</param>
  56. /// <returns>The binary logarithm of the `value`, but the result is rounded down to the nearest integer.</returns>
  57. public static int Log2Floor(int value)
  58. {
  59. return 31 - math.lzcnt((uint)value);
  60. }
  61. /// <summary>
  62. /// Returns the binary logarithm of the `value`, but the result is rounded up to the nearest integer.
  63. /// </summary>
  64. /// <param name="value">The value.</param>
  65. /// <returns>The binary logarithm of the `value`, but the result is rounded up to the nearest integer.</returns>
  66. public static int Log2Ceil(int value)
  67. {
  68. return 32 - math.lzcnt((uint)value - 1);
  69. }
  70. /// <summary>
  71. /// Returns an allocation size in bytes that factors in alignment.
  72. /// </summary>
  73. /// <example><code>
  74. /// // 55 aligned to 16 is 64.
  75. /// int size = CollectionHelper.Align(55, 16);
  76. /// </code></example>
  77. /// <param name="size">The size to align.</param>
  78. /// <param name="alignmentPowerOfTwo">A non-zero, positive power of two.</param>
  79. /// <returns>The smallest integer that is greater than or equal to `size` and is a multiple of `alignmentPowerOfTwo`.</returns>
  80. /// <exception cref="ArgumentException">Thrown if `alignmentPowerOfTwo` is not a non-zero, positive power of two.</exception>
  81. public static int Align(int size, int alignmentPowerOfTwo)
  82. {
  83. if (alignmentPowerOfTwo == 0)
  84. return size;
  85. CheckIntPositivePowerOfTwo(alignmentPowerOfTwo);
  86. return (size + alignmentPowerOfTwo - 1) & ~(alignmentPowerOfTwo - 1);
  87. }
  88. /// <summary>
  89. /// Returns an allocation size in bytes that factors in alignment.
  90. /// </summary>
  91. /// <example><code>
  92. /// // 55 aligned to 16 is 64.
  93. /// ulong size = CollectionHelper.Align(55, 16);
  94. /// </code></example>
  95. /// <param name="size">The size to align.</param>
  96. /// <param name="alignmentPowerOfTwo">A non-zero, positive power of two.</param>
  97. /// <returns>The smallest integer that is greater than or equal to `size` and is a multiple of `alignmentPowerOfTwo`.</returns>
  98. /// <exception cref="ArgumentException">Thrown if `alignmentPowerOfTwo` is not a non-zero, positive power of two.</exception>
  99. public static ulong Align(ulong size, ulong alignmentPowerOfTwo)
  100. {
  101. if (alignmentPowerOfTwo == 0)
  102. return size;
  103. CheckUlongPositivePowerOfTwo(alignmentPowerOfTwo);
  104. return (size + alignmentPowerOfTwo - 1) & ~(alignmentPowerOfTwo - 1);
  105. }
  106. /// <summary>
  107. /// Returns true if the address represented by the pointer has a given alignment.
  108. /// </summary>
  109. /// <param name="p">The pointer.</param>
  110. /// <param name="alignmentPowerOfTwo">A non-zero, positive power of two.</param>
  111. /// <returns>True if the address is a multiple of `alignmentPowerOfTwo`.</returns>
  112. /// <exception cref="ArgumentException">Thrown if `alignmentPowerOfTwo` is not a non-zero, positive power of two.</exception>
  113. public static unsafe bool IsAligned(void* p, int alignmentPowerOfTwo)
  114. {
  115. CheckIntPositivePowerOfTwo(alignmentPowerOfTwo);
  116. return ((ulong)p & ((ulong)alignmentPowerOfTwo - 1)) == 0;
  117. }
  118. /// <summary>
  119. /// Returns true if an offset has a given alignment.
  120. /// </summary>
  121. /// <param name="offset">An offset</param>
  122. /// <param name="alignmentPowerOfTwo">A non-zero, positive power of two.</param>
  123. /// <returns>True if the offset is a multiple of `alignmentPowerOfTwo`.</returns>
  124. /// <exception cref="ArgumentException">Thrown if `alignmentPowerOfTwo` is not a non-zero, positive power of two.</exception>
  125. public static bool IsAligned(ulong offset, int alignmentPowerOfTwo)
  126. {
  127. CheckIntPositivePowerOfTwo(alignmentPowerOfTwo);
  128. return (offset & ((ulong)alignmentPowerOfTwo - 1)) == 0;
  129. }
  130. /// <summary>
  131. /// Returns true if a positive value is a non-zero power of two.
  132. /// </summary>
  133. /// <remarks>Result is invalid if `value &lt; 0`.</remarks>
  134. /// <param name="value">A positive value.</param>
  135. /// <returns>True if the value is a non-zero, positive power of two.</returns>
  136. public static bool IsPowerOfTwo(int value)
  137. {
  138. return (value & (value - 1)) == 0;
  139. }
  140. /// <summary>
  141. /// Returns a (non-cryptographic) hash of a memory block.
  142. /// </summary>
  143. /// <remarks>The hash function used is [djb2](http://web.archive.org/web/20190508211657/http://www.cse.yorku.ca/~oz/hash.html).</remarks>
  144. /// <param name="ptr">A buffer.</param>
  145. /// <param name="bytes">The number of bytes to hash.</param>
  146. /// <returns>A hash of the bytes.</returns>
  147. public static unsafe uint Hash(void* ptr, int bytes)
  148. {
  149. // djb2 - Dan Bernstein hash function
  150. // http://web.archive.org/web/20190508211657/http://www.cse.yorku.ca/~oz/hash.html
  151. byte* str = (byte*)ptr;
  152. ulong hash = 5381;
  153. while (bytes > 0)
  154. {
  155. ulong c = str[--bytes];
  156. hash = ((hash << 5) + hash) + c;
  157. }
  158. return (uint)hash;
  159. }
  160. [NotBurstCompatible /* Used only for debugging. */]
  161. internal static void WriteLayout(Type type)
  162. {
  163. #if !NET_DOTS
  164. Console.WriteLine($" Offset | Bytes | Name Layout: {0}", type.Name);
  165. var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  166. foreach (var field in fields)
  167. {
  168. Console.WriteLine(" {0, 6} | {1, 6} | {2}"
  169. , Marshal.OffsetOf(type, field.Name)
  170. , Marshal.SizeOf(field.FieldType)
  171. , field.Name
  172. );
  173. }
  174. #else
  175. _ = type;
  176. #endif
  177. }
  178. internal static bool ShouldDeallocate(AllocatorManager.AllocatorHandle allocator)
  179. {
  180. // Allocator.Invalid == container is not initialized.
  181. // Allocator.None == container is initialized, but container doesn't own data.
  182. return allocator.ToAllocator > Allocator.None;
  183. }
  184. /// <summary>
  185. /// Tell Burst that an integer can be assumed to map to an always positive value.
  186. /// </summary>
  187. /// <param name="value">The integer that is always positive.</param>
  188. /// <returns>Returns `x`, but allows the compiler to assume it is always positive.</returns>
  189. [return: AssumeRange(0, int.MaxValue)]
  190. internal static int AssumePositive(int value)
  191. {
  192. return value;
  193. }
  194. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  195. [BurstDiscard] // Must use BurstDiscard because UnsafeUtility.IsUnmanaged is not burstable.
  196. [NotBurstCompatible /* Used only for debugging. */]
  197. internal static void CheckIsUnmanaged<T>()
  198. {
  199. if (!UnsafeUtility.IsValidNativeContainerElementType<T>())
  200. {
  201. throw new ArgumentException($"{typeof(T)} used in native collection is not blittable, not primitive, or contains a type tagged as NativeContainer");
  202. }
  203. }
  204. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  205. internal static void CheckIntPositivePowerOfTwo(int value)
  206. {
  207. var valid = (value > 0) && ((value & (value - 1)) == 0);
  208. if (!valid)
  209. {
  210. throw new ArgumentException($"Alignment requested: {value} is not a non-zero, positive power of two.");
  211. }
  212. }
  213. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  214. internal static void CheckUlongPositivePowerOfTwo(ulong value)
  215. {
  216. var valid = (value > 0) && ((value & (value - 1)) == 0);
  217. if (!valid)
  218. {
  219. throw new ArgumentException($"Alignment requested: {value} is not a non-zero, positive power of two.");
  220. }
  221. }
  222. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  223. internal static void CheckIndexInRange(int index, int length)
  224. {
  225. if (index < 0)
  226. throw new IndexOutOfRangeException($"Index {index} must be positive.");
  227. if (index >= length)
  228. throw new IndexOutOfRangeException($"Index {index} is out of range in container of '{length}' Length.");
  229. }
  230. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
  231. internal static void CheckCapacityInRange(int capacity, int length)
  232. {
  233. if (capacity < 0)
  234. throw new ArgumentOutOfRangeException($"Capacity {capacity} must be positive.");
  235. if (capacity < length)
  236. throw new ArgumentOutOfRangeException($"Capacity {capacity} is out of range in container of '{length}' Length.");
  237. }
  238. /// <summary>
  239. /// Create a NativeArray, using a provided allocator that implements IAllocator.
  240. /// </summary>
  241. /// <param name="length">The number of elements to allocate.</param>
  242. /// <param name="allocator">The allocator to use.</param>
  243. /// <param name="options">Options for allocation, such as whether to clear the memory.</param>
  244. /// <returns>Returns the NativeArray that was created.</returns>
  245. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(AllocatorManager.AllocatorHandle) })]
  246. public static NativeArray<T> CreateNativeArray<T, U>(int length, ref U allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
  247. where T : struct
  248. where U : unmanaged, AllocatorManager.IAllocator
  249. {
  250. NativeArray<T> nativeArray;
  251. if (!allocator.IsCustomAllocator)
  252. {
  253. nativeArray = new NativeArray<T>(length, allocator.ToAllocator, options);
  254. }
  255. else
  256. {
  257. nativeArray = new NativeArray<T>();
  258. nativeArray.Initialize(length, ref allocator, options);
  259. }
  260. return nativeArray;
  261. }
  262. /// <summary>
  263. /// Create a NativeArray, using a provided AllocatorHandle.
  264. /// </summary>
  265. /// <param name="length">The number of elements to allocate.</param>
  266. /// <param name="allocator">The AllocatorHandle to use.</param>
  267. /// <param name="options">Options for allocation, such as whether to clear the memory.</param>
  268. /// <returns>Returns the NativeArray that was created.</returns>
  269. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  270. public static NativeArray<T> CreateNativeArray<T>(int length, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
  271. where T : struct
  272. {
  273. NativeArray<T> nativeArray;
  274. if(!AllocatorManager.IsCustomAllocator(allocator))
  275. {
  276. nativeArray = new NativeArray<T>(length, allocator.ToAllocator, options);
  277. }
  278. else
  279. {
  280. nativeArray = new NativeArray<T>();
  281. nativeArray.Initialize(length, allocator, options);
  282. }
  283. return nativeArray;
  284. }
  285. /// <summary>
  286. /// Create a NativeArray from another NativeArray, using a provided AllocatorHandle.
  287. /// </summary>
  288. /// <param name="array">The NativeArray to make a copy of.</param>
  289. /// <param name="allocator">The AllocatorHandle to use.</param>
  290. /// <returns>Returns the NativeArray that was created.</returns>
  291. [BurstCompatible(GenericTypeArguments = new[] { typeof(int) })]
  292. public static NativeArray<T> CreateNativeArray<T>(NativeArray<T> array, AllocatorManager.AllocatorHandle allocator)
  293. where T : struct
  294. {
  295. NativeArray<T> nativeArray;
  296. if (!AllocatorManager.IsCustomAllocator(allocator))
  297. {
  298. nativeArray = new NativeArray<T>(array, allocator.ToAllocator);
  299. }
  300. else
  301. {
  302. nativeArray = new NativeArray<T>();
  303. nativeArray.Initialize(array.Length, allocator);
  304. nativeArray.CopyFrom(array);
  305. }
  306. return nativeArray;
  307. }
  308. /// <summary>
  309. /// Create a NativeArray from a managed array, using a provided AllocatorHandle.
  310. /// </summary>
  311. /// <param name="array">The managed array to make a copy of.</param>
  312. /// <param name="allocator">The AllocatorHandle to use.</param>
  313. /// <returns>Returns the NativeArray that was created.</returns>
  314. [NotBurstCompatible]
  315. public static NativeArray<T> CreateNativeArray<T>(T[] array, AllocatorManager.AllocatorHandle allocator)
  316. where T : struct
  317. {
  318. NativeArray<T> nativeArray;
  319. if (!AllocatorManager.IsCustomAllocator(allocator))
  320. {
  321. nativeArray = new NativeArray<T>(array, allocator.ToAllocator);
  322. }
  323. else
  324. {
  325. nativeArray = new NativeArray<T>();
  326. nativeArray.Initialize(array.Length, allocator);
  327. nativeArray.CopyFrom(array);
  328. }
  329. return nativeArray;
  330. }
  331. /// <summary>
  332. /// Create a NativeArray from a managed array, using a provided Allocator.
  333. /// </summary>
  334. /// <param name="array">The managed array to make a copy of.</param>
  335. /// <param name="allocator">The Allocator to use.</param>
  336. /// <returns>Returns the NativeArray that was created.</returns>
  337. [NotBurstCompatible]
  338. public static NativeArray<T> CreateNativeArray<T, U>(T[] array, ref U allocator)
  339. where T : struct
  340. where U : unmanaged, AllocatorManager.IAllocator
  341. {
  342. NativeArray<T> nativeArray;
  343. if (!allocator.IsCustomAllocator)
  344. {
  345. nativeArray = new NativeArray<T>(array, allocator.ToAllocator);
  346. }
  347. else
  348. {
  349. nativeArray = new NativeArray<T>();
  350. nativeArray.Initialize(array.Length, ref allocator);
  351. nativeArray.CopyFrom(array);
  352. }
  353. return nativeArray;
  354. }
  355. /// <summary>
  356. /// Create a NativeMultiHashMap from a managed array, using a provided Allocator.
  357. /// </summary>
  358. /// <param name="length">The desired capacity of the NativeMultiHashMap.</param>
  359. /// <param name="allocator">The Allocator to use.</param>
  360. /// <returns>Returns the NativeMultiHashMap that was created.</returns>
  361. [BurstCompatible(GenericTypeArguments = new[] { typeof(int), typeof(int), typeof(AllocatorManager.AllocatorHandle) })]
  362. public static NativeMultiHashMap<TKey, TValue> CreateNativeMultiHashMap<TKey, TValue, U>(int length, ref U allocator)
  363. where TKey : struct, IEquatable<TKey>
  364. where TValue : struct
  365. where U : unmanaged, AllocatorManager.IAllocator
  366. {
  367. var nativeMultiHashMap = new NativeMultiHashMap<TKey, TValue>();
  368. nativeMultiHashMap.Initialize(length, ref allocator);
  369. return nativeMultiHashMap;
  370. }
  371. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  372. [BurstCompatible(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS")]
  373. internal static AtomicSafetyHandle CreateSafetyHandle(AllocatorManager.AllocatorHandle allocator)
  374. {
  375. if (allocator.IsCustomAllocator)
  376. {
  377. return AtomicSafetyHandle.Create();
  378. }
  379. return (allocator.ToAllocator == Allocator.Temp) ? AtomicSafetyHandle.GetTempMemoryHandle() : AtomicSafetyHandle.Create();
  380. }
  381. [BurstCompatible(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS")]
  382. internal static void DisposeSafetyHandle(ref AtomicSafetyHandle safety)
  383. {
  384. AtomicSafetyHandle.CheckDeallocateAndThrow(safety);
  385. // If the safety handle is for a temp allocation, create a new safety handle for this instance which can be marked as invalid
  386. // Setting it to new AtomicSafetyHandle is not enough since the handle needs a valid node pointer in order to give the correct errors
  387. if (AtomicSafetyHandle.IsTempMemoryHandle(safety))
  388. {
  389. int staticSafetyId = safety.staticSafetyId;
  390. safety = AtomicSafetyHandle.Create();
  391. safety.staticSafetyId = staticSafetyId;
  392. }
  393. AtomicSafetyHandle.Release(safety);
  394. }
  395. static unsafe void CreateStaticSafetyIdInternal(ref int id, in FixedString512Bytes name)
  396. {
  397. id = AtomicSafetyHandle.NewStaticSafetyId(name.GetUnsafePtr(), name.Length);
  398. }
  399. [BurstDiscard]
  400. static void CreateStaticSafetyIdInternal<T>(ref int id)
  401. {
  402. CreateStaticSafetyIdInternal(ref id, typeof(T).ToString());
  403. }
  404. /// <summary>
  405. /// Returns a static safety id which better identifies resources in safety system messages.
  406. /// </summary>
  407. /// <remarks>This is preferable to AtomicSafetyHandle.NewStaticSafetyId as it is compatible with burst.</remarks>
  408. /// <param name="name">The name of the resource type.</param>
  409. /// <returns>An int representing the static safety id for this resource.</returns>
  410. [BurstCompatible(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS", GenericTypeArguments = new[] { typeof(NativeArray<int>) })]
  411. public static void SetStaticSafetyId<T>(ref AtomicSafetyHandle handle, ref int sharedStaticId)
  412. {
  413. if (sharedStaticId == 0)
  414. {
  415. // This will eventually either work with burst supporting a subset of typeof()
  416. // or something similar to Burst.BurstRuntime.GetTypeName() will be implemented
  417. // JIRA issue https://jira.unity3d.com/browse/DOTS-5685
  418. CreateStaticSafetyIdInternal<T>(ref sharedStaticId);
  419. }
  420. AtomicSafetyHandle.SetStaticSafetyId(ref handle, sharedStaticId);
  421. }
  422. /// <summary>
  423. /// Returns a static safety id which better identifies resources in safety system messages.
  424. /// </summary>
  425. /// <remarks>This is preferable to AtomicSafetyHandle.NewStaticSafetyId as it is compatible with burst.</remarks>
  426. /// <param name="name">The name of the resource type.</param>
  427. /// <returns>An int representing the static safety id for this resource.</returns>
  428. [BurstCompatible(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS")]
  429. public static unsafe void SetStaticSafetyId(ref AtomicSafetyHandle handle, ref int sharedStaticId, FixedString512Bytes name)
  430. {
  431. if (sharedStaticId == 0)
  432. {
  433. CreateStaticSafetyIdInternal(ref sharedStaticId, name);
  434. }
  435. AtomicSafetyHandle.SetStaticSafetyId(ref handle, sharedStaticId);
  436. }
  437. #endif
  438. }
  439. }