暂无描述
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

NativeBitArray.cs 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. using System;
  2. using System.Diagnostics;
  3. using System.Runtime.InteropServices;
  4. using Unity.Burst;
  5. using Unity.Collections.LowLevel.Unsafe;
  6. using Unity.Jobs;
  7. namespace Unity.Collections
  8. {
  9. /// <summary>
  10. /// An arbitrarily-sized array of bits.
  11. /// </summary>
  12. /// <remarks>
  13. /// The number of allocated bytes is always a multiple of 8. For example, a 65-bit array could fit in 9 bytes, but its allocation is actually 16 bytes.
  14. /// </remarks>
  15. [StructLayout(LayoutKind.Sequential)]
  16. [NativeContainer]
  17. [DebuggerDisplay("Length = {Length}, IsCreated = {IsCreated}")]
  18. [BurstCompatible]
  19. public unsafe struct NativeBitArray
  20. : INativeDisposable
  21. {
  22. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  23. internal AtomicSafetyHandle m_Safety;
  24. static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeBitArray>();
  25. #if REMOVE_DISPOSE_SENTINEL
  26. #else
  27. [NativeSetClassTypeToNullOnSchedule]
  28. DisposeSentinel m_DisposeSentinel;
  29. #endif
  30. #endif
  31. [NativeDisableUnsafePtrRestriction]
  32. internal UnsafeBitArray m_BitArray;
  33. /// <summary>
  34. /// Initializes and returns an instance of NativeBitArray.
  35. /// </summary>
  36. /// <param name="numBits">The number of bits.</param>
  37. /// <param name="allocator">The allocator to use.</param>
  38. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  39. public NativeBitArray(int numBits, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
  40. : this(numBits, allocator, options, 2)
  41. {
  42. }
  43. NativeBitArray(int numBits, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options, int disposeSentinelStackDepth)
  44. {
  45. CollectionHelper.CheckAllocator(allocator);
  46. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  47. #if REMOVE_DISPOSE_SENTINEL
  48. m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
  49. #else
  50. if (allocator.IsCustomAllocator)
  51. {
  52. m_Safety = AtomicSafetyHandle.Create();
  53. m_DisposeSentinel = null;
  54. }
  55. else
  56. {
  57. DisposeSentinel.Create(out m_Safety, out m_DisposeSentinel, disposeSentinelStackDepth, allocator.ToAllocator);
  58. }
  59. #endif
  60. CollectionHelper.SetStaticSafetyId(ref m_Safety, ref s_staticSafetyId.Data, "Unity.Collections.NativeBitArray");
  61. #endif
  62. m_BitArray = new UnsafeBitArray(numBits, allocator, options);
  63. }
  64. /// <summary>
  65. /// Whether this array has been allocated (and not yet deallocated).
  66. /// </summary>
  67. /// <value>True if this array has been allocated (and not yet deallocated).</value>
  68. public bool IsCreated => m_BitArray.IsCreated;
  69. /// <summary>
  70. /// Releases all resources (memory and safety handles).
  71. /// </summary>
  72. public void Dispose()
  73. {
  74. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  75. #if REMOVE_DISPOSE_SENTINEL
  76. CollectionHelper.DisposeSafetyHandle(ref m_Safety);
  77. #else
  78. DisposeSentinel.Dispose(ref m_Safety, ref m_DisposeSentinel);
  79. #endif
  80. #endif
  81. m_BitArray.Dispose();
  82. }
  83. /// <summary>
  84. /// Creates and schedules a job that will dispose this array.
  85. /// </summary>
  86. /// <param name="inputDeps">The handle of a job which the new job will depend upon.</param>
  87. /// <returns>The handle of a new job that will dispose this array. The new job depends upon inputDeps.</returns>
  88. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  89. public JobHandle Dispose(JobHandle inputDeps)
  90. {
  91. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  92. #if REMOVE_DISPOSE_SENTINEL
  93. #else
  94. // [DeallocateOnJobCompletion] is not supported, but we want the deallocation
  95. // to happen in a thread. DisposeSentinel needs to be cleared on main thread.
  96. // AtomicSafetyHandle can be destroyed after the job was scheduled (Job scheduling
  97. // will check that no jobs are writing to the container).
  98. DisposeSentinel.Clear(ref m_DisposeSentinel);
  99. #endif
  100. #endif
  101. var jobHandle = m_BitArray.Dispose(inputDeps);
  102. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  103. AtomicSafetyHandle.Release(m_Safety);
  104. #endif
  105. return jobHandle;
  106. }
  107. /// <summary>
  108. /// Returns the number of bits.
  109. /// </summary>
  110. /// <value>The number of bits.</value>
  111. public int Length
  112. {
  113. get
  114. {
  115. CheckRead();
  116. return CollectionHelper.AssumePositive(m_BitArray.Length);
  117. }
  118. }
  119. /// <summary>
  120. /// Sets all the bits to 0.
  121. /// </summary>
  122. public void Clear()
  123. {
  124. CheckWrite();
  125. m_BitArray.Clear();
  126. }
  127. /// <summary>
  128. /// Returns a native array that aliases the content of this array.
  129. /// </summary>
  130. /// <typeparam name="T">The type of elements in the aliased array.</typeparam>
  131. /// <exception cref="InvalidOperationException">Thrown if the number of bits in this array
  132. /// is not evenly divisible by the size of T in bits (`sizeof(T) * 8`).</exception>
  133. /// <returns>A native array that aliases the content of this array.</returns>
  134. [BurstCompatible(GenericTypeArguments = new [] { typeof(int) })]
  135. public NativeArray<T> AsNativeArray<T>() where T : unmanaged
  136. {
  137. CheckReadBounds<T>();
  138. var bitsPerElement = UnsafeUtility.SizeOf<T>() * 8;
  139. var length = m_BitArray.Length / bitsPerElement;
  140. var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(m_BitArray.Ptr, length, Allocator.None);
  141. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  142. AtomicSafetyHandle.UseSecondaryVersion(ref m_Safety);
  143. NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, m_Safety);
  144. #endif
  145. return array;
  146. }
  147. /// <summary>
  148. /// Sets the bit at an index to 0 or 1.
  149. /// </summary>
  150. /// <param name="pos">Index of the bit to set.</param>
  151. /// <param name="value">True for 1, false for 0.</param>
  152. public void Set(int pos, bool value)
  153. {
  154. CheckWrite();
  155. m_BitArray.Set(pos, value);
  156. }
  157. /// <summary>
  158. /// Sets a range of bits to 0 or 1.
  159. /// </summary>
  160. /// <remarks>
  161. /// The range runs from index `pos` up to (but not including) `pos + numBits`.
  162. /// No exception is thrown if `pos + numBits` exceeds the length.
  163. /// </remarks>
  164. /// <param name="pos">Index of the first bit to set.</param>
  165. /// <param name="value">True for 1, false for 0.</param>
  166. /// <param name="numBits">Number of bits to set.</param>
  167. /// <exception cref="ArgumentException">Thrown if pos is out of bounds or if numBits is less than 1.</exception>
  168. public void SetBits(int pos, bool value, int numBits)
  169. {
  170. CheckWrite();
  171. m_BitArray.SetBits(pos, value, numBits);
  172. }
  173. /// <summary>
  174. /// Copies bits of a ulong to bits in this array.
  175. /// </summary>
  176. /// <remarks>
  177. /// The destination bits in this array run from index pos up to (but not including) `pos + numBits`.
  178. /// No exception is thrown if `pos + numBits` exceeds the length.
  179. ///
  180. /// The lowest bit of the ulong is copied to the first destination bit; the second-lowest bit of the ulong is
  181. /// copied to the second destination bit; and so forth.
  182. /// </remarks>
  183. /// <param name="pos">Index of the first bit to set.</param>
  184. /// <param name="value">Unsigned long from which to copy bits.</param>
  185. /// <param name="numBits">Number of bits to set (must be between 1 and 64).</param>
  186. /// <exception cref="ArgumentException">Thrown if pos is out of bounds or if numBits is not between 1 and 64.</exception>
  187. public void SetBits(int pos, ulong value, int numBits = 1)
  188. {
  189. CheckWrite();
  190. m_BitArray.SetBits(pos, value, numBits);
  191. }
  192. /// <summary>
  193. /// Returns a ulong which has bits copied from this array.
  194. /// </summary>
  195. /// <remarks>
  196. /// The source bits in this array run from index pos up to (but not including) `pos + numBits`.
  197. /// No exception is thrown if `pos + numBits` exceeds the length.
  198. ///
  199. /// The first source bit is copied to the lowest bit of the ulong; the second source bit is copied to the second-lowest bit of the ulong; and so forth. Any remaining bits in the ulong will be 0.
  200. /// </remarks>
  201. /// <param name="pos">Index of the first bit to get.</param>
  202. /// <param name="numBits">Number of bits to get (must be between 1 and 64).</param>
  203. /// <exception cref="ArgumentException">Thrown if pos is out of bounds or if numBits is not between 1 and 64.</exception>
  204. /// <returns>A ulong which has bits copied from this array.</returns>
  205. public ulong GetBits(int pos, int numBits = 1)
  206. {
  207. CheckRead();
  208. return m_BitArray.GetBits(pos, numBits);
  209. }
  210. /// <summary>
  211. /// Returns true if the bit at an index is 1.
  212. /// </summary>
  213. /// <param name="pos">Index of the bit to test.</param>
  214. /// <returns>True if the bit at the index is 1.</returns>
  215. /// <exception cref="ArgumentException">Thrown if `pos` is out of bounds.</exception>
  216. public bool IsSet(int pos)
  217. {
  218. CheckRead();
  219. return m_BitArray.IsSet(pos);
  220. }
  221. /// <summary>
  222. /// Copies a range of bits from this array to another range in this array.
  223. /// </summary>
  224. /// <remarks>
  225. /// The bits to copy run from index `srcPos` up to (but not including) `srcPos + numBits`.
  226. /// The bits to set run from index `dstPos` up to (but not including) `dstPos + numBits`.
  227. ///
  228. /// The ranges may overlap, but the result in the overlapping region is undefined.
  229. /// </remarks>
  230. /// <param name="dstPos">Index of the first bit to set.</param>
  231. /// <param name="srcPos">Index of the first bit to copy.</param>
  232. /// <param name="numBits">Number of bits to copy.</param>
  233. /// <exception cref="ArgumentException">Thrown if either `dstPos + numBits` or `srcPos + numBits` exceed the length of this array.</exception>
  234. public void Copy(int dstPos, int srcPos, int numBits)
  235. {
  236. CheckWrite();
  237. m_BitArray.Copy(dstPos, srcPos, numBits);
  238. }
  239. /// <summary>
  240. /// Copies a range of bits from an array to a range of bits in this array.
  241. /// </summary>
  242. /// <remarks>
  243. /// The bits to copy in the source array run from index srcPos up to (but not including) `srcPos + numBits`.
  244. /// The bits to set in the destination array run from index dstPos up to (but not including) `dstPos + numBits`.
  245. ///
  246. /// When the source and destination are the same array, the ranges may still overlap, but the result in the overlapping region is undefined.
  247. /// </remarks>
  248. /// <param name="dstPos">Index of the first bit to set.</param>
  249. /// <param name="srcBitArray">The source array.</param>
  250. /// <param name="srcPos">Index of the first bit to copy.</param>
  251. /// <param name="numBits">The number of bits to copy.</param>
  252. /// <exception cref="ArgumentException">Thrown if either `dstPos + numBits` or `srcBitArray + numBits` exceed the length of this array.</exception>
  253. public void Copy(int dstPos, ref NativeBitArray srcBitArray, int srcPos, int numBits)
  254. {
  255. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  256. AtomicSafetyHandle.CheckReadAndThrow(srcBitArray.m_Safety);
  257. #endif
  258. CheckWrite();
  259. m_BitArray.Copy(dstPos, ref srcBitArray.m_BitArray, srcPos, numBits);
  260. }
  261. /// <summary>
  262. /// Finds the first length-*N* contiguous sequence of 0 bits in this bit array.
  263. /// </summary>
  264. /// <param name="pos">Index at which to start searching.</param>
  265. /// <param name="numBits">Number of contiguous 0 bits to look for.</param>
  266. /// <returns>The index in this array where the sequence is found. The index will be greater than or equal to `pos`.
  267. /// Returns -1 if no occurrence is found.</returns>
  268. public int Find(int pos, int numBits)
  269. {
  270. CheckRead();
  271. return m_BitArray.Find(pos, numBits);
  272. }
  273. /// <summary>
  274. /// Finds the first length-*N* contiguous sequence of 0 bits in this bit array. Searches only a subsection.
  275. /// </summary>
  276. /// <param name="pos">Index at which to start searching.</param>
  277. /// <param name="numBits">Number of contiguous 0 bits to look for.</param>
  278. /// <param name="count">Number of bits to search.</param>
  279. /// <returns>The index in this array where the sequence is found. The index will be greater than or equal to `pos` but less than `pos + count`.
  280. /// Returns -1 if no occurrence is found.</returns>
  281. public int Find(int pos, int count, int numBits)
  282. {
  283. CheckRead();
  284. return m_BitArray.Find(pos, count, numBits);
  285. }
  286. /// <summary>
  287. /// Returns true if none of the bits in a range are 1 (*i.e.* all bits in the range are 0).
  288. /// </summary>
  289. /// <param name="pos">Index of the bit at which to start searching.</param>
  290. /// <param name="numBits">Number of bits to test. Defaults to 1.</param>
  291. /// <returns>Returns true if none of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
  292. /// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
  293. public bool TestNone(int pos, int numBits = 1)
  294. {
  295. CheckRead();
  296. return m_BitArray.TestNone(pos, numBits);
  297. }
  298. /// <summary>
  299. /// Returns true if at least one of the bits in a range is 1.
  300. /// </summary>
  301. /// <param name="pos">Index of the bit at which to start searching.</param>
  302. /// <param name="numBits">Number of bits to test. Defaults to 1.</param>
  303. /// <returns>True if one ore more of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
  304. /// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
  305. public bool TestAny(int pos, int numBits = 1)
  306. {
  307. CheckRead();
  308. return m_BitArray.TestAny(pos, numBits);
  309. }
  310. /// <summary>
  311. /// Returns true if all of the bits in a range are 1.
  312. /// </summary>
  313. /// <param name="pos">Index of the bit at which to start searching.</param>
  314. /// <param name="numBits">Number of bits to test. Defaults to 1.</param>
  315. /// <returns>True if all of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
  316. /// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
  317. public bool TestAll(int pos, int numBits = 1)
  318. {
  319. CheckRead();
  320. return m_BitArray.TestAll(pos, numBits);
  321. }
  322. /// <summary>
  323. /// Returns the number of bits in a range that are 1.
  324. /// </summary>
  325. /// <param name="pos">Index of the bit at which to start searching.</param>
  326. /// <param name="numBits">Number of bits to test. Defaults to 1.</param>
  327. /// <returns>The number of bits in a range of bits that are 1.</returns>
  328. /// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
  329. public int CountBits(int pos, int numBits = 1)
  330. {
  331. CheckRead();
  332. return m_BitArray.CountBits(pos, numBits);
  333. }
  334. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  335. void CheckRead()
  336. {
  337. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  338. AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
  339. #endif
  340. }
  341. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  342. void CheckReadBounds<T>() where T : unmanaged
  343. {
  344. CheckRead();
  345. var bitsPerElement = UnsafeUtility.SizeOf<T>() * 8;
  346. var length = m_BitArray.Length / bitsPerElement;
  347. if (length == 0)
  348. {
  349. throw new InvalidOperationException($"Number of bits in the NativeBitArray {m_BitArray.Length} is not sufficient to cast to NativeArray<T> {UnsafeUtility.SizeOf<T>() * 8}.");
  350. }
  351. else if (m_BitArray.Length != bitsPerElement* length)
  352. {
  353. throw new InvalidOperationException($"Number of bits in the NativeBitArray {m_BitArray.Length} couldn't hold multiple of T {UnsafeUtility.SizeOf<T>()}. Output array would be truncated.");
  354. }
  355. }
  356. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  357. void CheckWrite()
  358. {
  359. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  360. AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
  361. #endif
  362. }
  363. }
  364. }
  365. namespace Unity.Collections.LowLevel.Unsafe
  366. {
  367. /// <summary>
  368. /// Unsafe helper methods for NativeBitArray.
  369. /// </summary>
  370. [BurstCompatible]
  371. public static class NativeBitArrayUnsafeUtility
  372. {
  373. #if ENABLE_UNITY_COLLECTIONS_CHECKS
  374. /// <summary>
  375. /// Returns an array's atomic safety handle.
  376. /// </summary>
  377. /// <param name="container">Array from which to get an AtomicSafetyHandle.</param>
  378. /// <returns>This array's atomic safety handle.</returns>
  379. [BurstCompatible(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS", CompileTarget = BurstCompatibleAttribute.BurstCompatibleCompileTarget.Editor)]
  380. public static AtomicSafetyHandle GetAtomicSafetyHandle(in NativeBitArray container)
  381. {
  382. return container.m_Safety;
  383. }
  384. /// <summary>
  385. /// Sets an array's atomic safety handle.
  386. /// </summary>
  387. /// <param name="container">Array which the AtomicSafetyHandle is for.</param>
  388. /// <param name="safety">Atomic safety handle for this array.</param>
  389. [BurstCompatible(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS", CompileTarget = BurstCompatibleAttribute.BurstCompatibleCompileTarget.Editor)]
  390. public static void SetAtomicSafetyHandle(ref NativeBitArray container, AtomicSafetyHandle safety)
  391. {
  392. container.m_Safety = safety;
  393. }
  394. #endif
  395. /// <summary>
  396. /// Returns a bit array with content aliasing a buffer.
  397. /// </summary>
  398. /// <param name="ptr">A buffer.</param>
  399. /// <param name="sizeInBytes">Size of the buffer in bytes. Must be a multiple of 8.</param>
  400. /// <param name="allocator">The allocator that was used to create the buffer.</param>
  401. /// <returns>A bit array with content aliasing a buffer.</returns>
  402. public static unsafe NativeBitArray ConvertExistingDataToNativeBitArray(void* ptr, int sizeInBytes, AllocatorManager.AllocatorHandle allocator)
  403. {
  404. return new NativeBitArray
  405. {
  406. m_BitArray = new UnsafeBitArray(ptr, sizeInBytes, allocator),
  407. };
  408. }
  409. }
  410. }