Bez popisu
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.

UnsafeBitArray.cs 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. using System;
  2. using System.Diagnostics;
  3. using Unity.Jobs;
  4. using Unity.Mathematics;
  5. namespace Unity.Collections.LowLevel.Unsafe
  6. {
  7. /// <summary>
  8. /// An arbitrarily-sized array of bits.
  9. /// </summary>
  10. /// <remarks>
  11. /// 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.
  12. /// </remarks>
  13. [DebuggerDisplay("Length = {Length}, IsCreated = {IsCreated}")]
  14. [DebuggerTypeProxy(typeof(UnsafeBitArrayDebugView))]
  15. [BurstCompatible]
  16. public unsafe struct UnsafeBitArray
  17. : INativeDisposable
  18. {
  19. /// <summary>
  20. /// Pointer to the data.
  21. /// </summary>
  22. /// <value>Pointer to the data.</value>
  23. [NativeDisableUnsafePtrRestriction]
  24. public ulong* Ptr;
  25. /// <summary>
  26. /// The number of bits.
  27. /// </summary>
  28. /// <value>The number of bits.</value>
  29. public int Length;
  30. /// <summary>
  31. /// The allocator to use.
  32. /// </summary>
  33. /// <value>The allocator to use.</value>
  34. public AllocatorManager.AllocatorHandle Allocator;
  35. /// <summary>
  36. /// Initializes and returns an instance of UnsafeBitArray which aliases an existing buffer.
  37. /// </summary>
  38. /// <param name="ptr">An existing buffer.</param>
  39. /// <param name="allocator">The allocator that was used to allocate the bytes. Needed to dispose this array.</param>
  40. /// <param name="sizeInBytes">The number of bytes. The length will be `sizeInBytes * 8`.</param>
  41. public unsafe UnsafeBitArray(void* ptr, int sizeInBytes, AllocatorManager.AllocatorHandle allocator = new AllocatorManager.AllocatorHandle())
  42. {
  43. CheckSizeMultipleOf8(sizeInBytes);
  44. Ptr = (ulong*)ptr;
  45. Length = sizeInBytes * 8;
  46. Allocator = allocator;
  47. }
  48. /// <summary>
  49. /// Initializes and returns an instance of UnsafeBitArray.
  50. /// </summary>
  51. /// <param name="numBits">Number of bits.</param>
  52. /// <param name="allocator">The allocator to use.</param>
  53. /// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
  54. public UnsafeBitArray(int numBits, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
  55. {
  56. CollectionHelper.CheckAllocator(allocator);
  57. Allocator = allocator;
  58. var sizeInBytes = Bitwise.AlignUp(numBits, 64) / 8;
  59. Ptr = (ulong*)Memory.Unmanaged.Allocate(sizeInBytes, 16, allocator);
  60. Length = numBits;
  61. if (options == NativeArrayOptions.ClearMemory)
  62. {
  63. UnsafeUtility.MemClear(Ptr, sizeInBytes);
  64. }
  65. }
  66. /// <summary>
  67. /// Whether this array has been allocated (and not yet deallocated).
  68. /// </summary>
  69. /// <value>True if this array has been allocated (and not yet deallocated).</value>
  70. public bool IsCreated => Ptr != null;
  71. /// <summary>
  72. /// Releases all resources (memory and safety handles).
  73. /// </summary>
  74. public void Dispose()
  75. {
  76. if (CollectionHelper.ShouldDeallocate(Allocator))
  77. {
  78. Memory.Unmanaged.Free(Ptr, Allocator);
  79. Allocator = AllocatorManager.Invalid;
  80. }
  81. Ptr = null;
  82. Length = 0;
  83. }
  84. /// <summary>
  85. /// Creates and schedules a job that will dispose this array.
  86. /// </summary>
  87. /// <param name="inputDeps">The handle of a job which the new job will depend upon.</param>
  88. /// <returns>The handle of a new job that will dispose this array. The new job depends upon inputDeps.</returns>
  89. [NotBurstCompatible /* This is not burst compatible because of IJob's use of a static IntPtr. Should switch to IJobBurstSchedulable in the future */]
  90. public JobHandle Dispose(JobHandle inputDeps)
  91. {
  92. if (CollectionHelper.ShouldDeallocate(Allocator))
  93. {
  94. var jobHandle = new UnsafeDisposeJob { Ptr = Ptr, Allocator = Allocator }.Schedule(inputDeps);
  95. Ptr = null;
  96. Allocator = AllocatorManager.Invalid;
  97. return jobHandle;
  98. }
  99. Ptr = null;
  100. return inputDeps;
  101. }
  102. /// <summary>
  103. /// Sets all the bits to 0.
  104. /// </summary>
  105. public void Clear()
  106. {
  107. var sizeInBytes = Bitwise.AlignUp(Length, 64) / 8;
  108. UnsafeUtility.MemClear(Ptr, sizeInBytes);
  109. }
  110. /// <summary>
  111. /// Sets the bit at an index to 0 or 1.
  112. /// </summary>
  113. /// <param name="pos">Index of the bit to set.</param>
  114. /// <param name="value">True for 1, false for 0.</param>
  115. public void Set(int pos, bool value)
  116. {
  117. CheckArgs(pos, 1);
  118. var idx = pos >> 6;
  119. var shift = pos & 0x3f;
  120. var mask = 1ul << shift;
  121. var bits = (Ptr[idx] & ~mask) | ((ulong)-Bitwise.FromBool(value) & mask);
  122. Ptr[idx] = bits;
  123. }
  124. /// <summary>
  125. /// Sets a range of bits to 0 or 1.
  126. /// </summary>
  127. /// <remarks>
  128. /// The range runs from index `pos` up to (but not including) `pos + numBits`.
  129. /// No exception is thrown if `pos + numBits` exceeds the length.
  130. /// </remarks>
  131. /// <param name="pos">Index of the first bit to set.</param>
  132. /// <param name="value">True for 1, false for 0.</param>
  133. /// <param name="numBits">Number of bits to set.</param>
  134. /// <exception cref="ArgumentException">Thrown if pos is out of bounds or if numBits is less than 1.</exception>
  135. public void SetBits(int pos, bool value, int numBits)
  136. {
  137. CheckArgs(pos, numBits);
  138. var end = math.min(pos + numBits, Length);
  139. var idxB = pos >> 6;
  140. var shiftB = pos & 0x3f;
  141. var idxE = (end - 1) >> 6;
  142. var shiftE = end & 0x3f;
  143. var maskB = 0xfffffffffffffffful << shiftB;
  144. var maskE = 0xfffffffffffffffful >> (64 - shiftE);
  145. var orBits = (ulong)-Bitwise.FromBool(value);
  146. var orBitsB = maskB & orBits;
  147. var orBitsE = maskE & orBits;
  148. var cmaskB = ~maskB;
  149. var cmaskE = ~maskE;
  150. if (idxB == idxE)
  151. {
  152. var maskBE = maskB & maskE;
  153. var cmaskBE = ~maskBE;
  154. var orBitsBE = orBitsB & orBitsE;
  155. Ptr[idxB] = (Ptr[idxB] & cmaskBE) | orBitsBE;
  156. return;
  157. }
  158. Ptr[idxB] = (Ptr[idxB] & cmaskB) | orBitsB;
  159. for (var idx = idxB + 1; idx < idxE; ++idx)
  160. {
  161. Ptr[idx] = orBits;
  162. }
  163. Ptr[idxE] = (Ptr[idxE] & cmaskE) | orBitsE;
  164. }
  165. /// <summary>
  166. /// Copies bits of a ulong to bits in this array.
  167. /// </summary>
  168. /// <remarks>
  169. /// The destination bits in this array run from index `pos` up to (but not including) `pos + numBits`.
  170. /// No exception is thrown if `pos + numBits` exceeds the length.
  171. ///
  172. /// The lowest bit of the ulong is copied to the first destination bit; the second-lowest bit of the ulong is
  173. /// copied to the second destination bit; and so forth.
  174. /// </remarks>
  175. /// <param name="pos">Index of the first bit to set.</param>
  176. /// <param name="value">Unsigned long from which to copy bits.</param>
  177. /// <param name="numBits">Number of bits to set (must be between 1 and 64).</param>
  178. /// <exception cref="ArgumentException">Thrown if pos is out of bounds or if numBits is not between 1 and 64.</exception>
  179. public void SetBits(int pos, ulong value, int numBits = 1)
  180. {
  181. CheckArgsUlong(pos, numBits);
  182. var idxB = pos >> 6;
  183. var shiftB = pos & 0x3f;
  184. if (shiftB + numBits <= 64)
  185. {
  186. var mask = 0xfffffffffffffffful >> (64 - numBits);
  187. Ptr[idxB] = Bitwise.ReplaceBits(Ptr[idxB], shiftB, mask, value);
  188. return;
  189. }
  190. var end = math.min(pos + numBits, Length);
  191. var idxE = (end - 1) >> 6;
  192. var shiftE = end & 0x3f;
  193. var maskB = 0xfffffffffffffffful >> shiftB;
  194. Ptr[idxB] = Bitwise.ReplaceBits(Ptr[idxB], shiftB, maskB, value);
  195. var valueE = value >> (64 - shiftB);
  196. var maskE = 0xfffffffffffffffful >> (64 - shiftE);
  197. Ptr[idxE] = Bitwise.ReplaceBits(Ptr[idxE], 0, maskE, valueE);
  198. }
  199. /// <summary>
  200. /// Returns a ulong which has bits copied from this array.
  201. /// </summary>
  202. /// <remarks>
  203. /// The source bits in this array run from index `pos` up to (but not including) `pos + numBits`.
  204. /// No exception is thrown if `pos + numBits` exceeds the length.
  205. ///
  206. /// 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.
  207. /// </remarks>
  208. /// <param name="pos">Index of the first bit to get.</param>
  209. /// <param name="numBits">Number of bits to get (must be between 1 and 64).</param>
  210. /// <exception cref="ArgumentException">Thrown if pos is out of bounds or if numBits is not between 1 and 64.</exception>
  211. /// <returns>A ulong which has bits copied from this array.</returns>
  212. public ulong GetBits(int pos, int numBits = 1)
  213. {
  214. CheckArgsUlong(pos, numBits);
  215. var idxB = pos >> 6;
  216. var shiftB = pos & 0x3f;
  217. if (shiftB + numBits <= 64)
  218. {
  219. var mask = 0xfffffffffffffffful >> (64 - numBits);
  220. return Bitwise.ExtractBits(Ptr[idxB], shiftB, mask);
  221. }
  222. var end = math.min(pos + numBits, Length);
  223. var idxE = (end - 1) >> 6;
  224. var shiftE = end & 0x3f;
  225. var maskB = 0xfffffffffffffffful >> shiftB;
  226. ulong valueB = Bitwise.ExtractBits(Ptr[idxB], shiftB, maskB);
  227. var maskE = 0xfffffffffffffffful >> (64 - shiftE);
  228. ulong valueE = Bitwise.ExtractBits(Ptr[idxE], 0, maskE);
  229. return (valueE << (64 - shiftB)) | valueB;
  230. }
  231. /// <summary>
  232. /// Returns true if the bit at an index is 1.
  233. /// </summary>
  234. /// <param name="pos">Index of the bit to test.</param>
  235. /// <returns>True if the bit at the index is 1.</returns>
  236. /// <exception cref="ArgumentException">Thrown if `pos` is out of bounds.</exception>
  237. public bool IsSet(int pos)
  238. {
  239. CheckArgs(pos, 1);
  240. var idx = pos >> 6;
  241. var shift = pos & 0x3f;
  242. var mask = 1ul << shift;
  243. return 0ul != (Ptr[idx] & mask);
  244. }
  245. internal void CopyUlong(int dstPos, ref UnsafeBitArray srcBitArray, int srcPos, int numBits) => SetBits(dstPos, srcBitArray.GetBits(srcPos, numBits), numBits);
  246. /// <summary>
  247. /// Copies a range of bits from this array to another range in this array.
  248. /// </summary>
  249. /// <remarks>
  250. /// The bits to copy run from index `srcPos` up to (but not including) `srcPos + numBits`.
  251. /// The bits to set run from index `dstPos` up to (but not including) `dstPos + numBits`.
  252. ///
  253. /// The ranges may overlap, but the result in the overlapping region is undefined.
  254. /// </remarks>
  255. /// <param name="dstPos">Index of the first bit to set.</param>
  256. /// <param name="srcPos">Index of the first bit to copy.</param>
  257. /// <param name="numBits">Number of bits to copy.</param>
  258. /// <exception cref="ArgumentException">Thrown if either `dstPos + numBits` or `srcPos + numBits` exceed the length of this array.</exception>
  259. public void Copy(int dstPos, int srcPos, int numBits)
  260. {
  261. if (dstPos == srcPos)
  262. {
  263. return;
  264. }
  265. Copy(dstPos, ref this, srcPos, numBits);
  266. }
  267. /// <summary>
  268. /// Copies a range of bits from an array to a range of bits in this array.
  269. /// </summary>
  270. /// <remarks>
  271. /// The bits to copy in the source array run from index srcPos up to (but not including) `srcPos + numBits`.
  272. /// The bits to set in the destination array run from index dstPos up to (but not including) `dstPos + numBits`.
  273. ///
  274. /// It's fine if source and destination array are one and the same, even if the ranges overlap, but the result in the overlapping region is undefined.
  275. /// </remarks>
  276. /// <param name="dstPos">Index of the first bit to set.</param>
  277. /// <param name="srcBitArray">The source array.</param>
  278. /// <param name="srcPos">Index of the first bit to copy.</param>
  279. /// <param name="numBits">The number of bits to copy.</param>
  280. /// <exception cref="ArgumentException">Thrown if either `dstPos + numBits` or `srcBitArray + numBits` exceed the length of this array.</exception>
  281. public void Copy(int dstPos, ref UnsafeBitArray srcBitArray, int srcPos, int numBits)
  282. {
  283. if (numBits == 0)
  284. {
  285. return;
  286. }
  287. CheckArgsCopy(ref this, dstPos, ref srcBitArray, srcPos, numBits);
  288. if (numBits <= 64) // 1x CopyUlong
  289. {
  290. CopyUlong(dstPos, ref srcBitArray, srcPos, numBits);
  291. }
  292. else if (numBits <= 128) // 2x CopyUlong
  293. {
  294. CopyUlong(dstPos, ref srcBitArray, srcPos, 64);
  295. numBits -= 64;
  296. if (numBits > 0)
  297. {
  298. CopyUlong(dstPos + 64, ref srcBitArray, srcPos + 64, numBits);
  299. }
  300. }
  301. else if ((dstPos & 7) == (srcPos & 7)) // aligned copy
  302. {
  303. var dstPosInBytes = CollectionHelper.Align(dstPos, 8) >> 3;
  304. var srcPosInBytes = CollectionHelper.Align(srcPos, 8) >> 3;
  305. var numPreBits = dstPosInBytes * 8 - dstPos;
  306. if (numPreBits > 0)
  307. {
  308. CopyUlong(dstPos, ref srcBitArray, srcPos, numPreBits);
  309. }
  310. var numBitsLeft = numBits - numPreBits;
  311. var numBytes = numBitsLeft / 8;
  312. if (numBytes > 0)
  313. {
  314. unsafe
  315. {
  316. UnsafeUtility.MemMove((byte*)Ptr + dstPosInBytes, (byte*)srcBitArray.Ptr + srcPosInBytes, numBytes);
  317. }
  318. }
  319. var numPostBits = numBitsLeft & 7;
  320. if (numPostBits > 0)
  321. {
  322. CopyUlong((dstPosInBytes + numBytes) * 8, ref srcBitArray, (srcPosInBytes + numBytes) * 8, numPostBits);
  323. }
  324. }
  325. else // unaligned copy
  326. {
  327. var dstPosAligned = CollectionHelper.Align(dstPos, 64);
  328. var numPreBits = dstPosAligned - dstPos;
  329. if (numPreBits > 0)
  330. {
  331. CopyUlong(dstPos, ref srcBitArray, srcPos, numPreBits);
  332. numBits -= numPreBits;
  333. dstPos += numPreBits;
  334. srcPos += numPreBits;
  335. }
  336. for (; numBits >= 64; numBits -= 64, dstPos += 64, srcPos += 64)
  337. {
  338. Ptr[dstPos >> 6] = srcBitArray.GetBits(srcPos, 64);
  339. }
  340. if (numBits > 0)
  341. {
  342. CopyUlong(dstPos, ref srcBitArray, srcPos, numBits);
  343. }
  344. }
  345. }
  346. /// <summary>
  347. /// Returns the index of the first occurrence in this array of *N* contiguous 0 bits.
  348. /// </summary>
  349. /// <remarks>The search is linear.</remarks>
  350. /// <param name="pos">Index of the bit at which to start searching.</param>
  351. /// <param name="numBits">Number of contiguous 0 bits to look for.</param>
  352. /// <returns>The index of the first occurrence in this array of `numBits` contiguous 0 bits. Range is pos up to (but not including) the length of this array. Returns -1 if no occurrence is found.</returns>
  353. public int Find(int pos, int numBits)
  354. {
  355. var count = Length - pos;
  356. CheckArgsPosCount(pos, count, numBits);
  357. return Bitwise.Find(Ptr, pos, count, numBits);
  358. }
  359. /// <summary>
  360. /// Returns the index of the first occurrence in this array of a given number of contiguous 0 bits.
  361. /// </summary>
  362. /// <remarks>The search is linear.</remarks>
  363. /// <param name="pos">Index of the bit at which to start searching.</param>
  364. /// <param name="numBits">Number of contiguous 0 bits to look for.</param>
  365. /// <param name="count">Number of indexes to consider as the return value.</param>
  366. /// <returns>The index of the first occurrence in this array of `numBits` contiguous 0 bits. Range is pos up to (but not including) `pos + count`. Returns -1 if no occurrence is found.</returns>
  367. public int Find(int pos, int count, int numBits)
  368. {
  369. CheckArgsPosCount(pos, count, numBits);
  370. return Bitwise.Find(Ptr, pos, count, numBits);
  371. }
  372. /// <summary>
  373. /// Returns true if none of the bits in a range are 1 (*i.e.* all bits in the range are 0).
  374. /// </summary>
  375. /// <param name="pos">Index of the bit at which to start searching.</param>
  376. /// <param name="numBits">Number of bits to test. Defaults to 1.</param>
  377. /// <returns>Returns true if none of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
  378. /// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
  379. public bool TestNone(int pos, int numBits = 1)
  380. {
  381. CheckArgs(pos, numBits);
  382. var end = math.min(pos + numBits, Length);
  383. var idxB = pos >> 6;
  384. var shiftB = pos & 0x3f;
  385. var idxE = (end - 1) >> 6;
  386. var shiftE = end & 0x3f;
  387. var maskB = 0xfffffffffffffffful << shiftB;
  388. var maskE = 0xfffffffffffffffful >> (64 - shiftE);
  389. if (idxB == idxE)
  390. {
  391. var mask = maskB & maskE;
  392. return 0ul == (Ptr[idxB] & mask);
  393. }
  394. if (0ul != (Ptr[idxB] & maskB))
  395. {
  396. return false;
  397. }
  398. for (var idx = idxB + 1; idx < idxE; ++idx)
  399. {
  400. if (0ul != Ptr[idx])
  401. {
  402. return false;
  403. }
  404. }
  405. return 0ul == (Ptr[idxE] & maskE);
  406. }
  407. /// <summary>
  408. /// Returns true if at least one of the bits in a range is 1.
  409. /// </summary>
  410. /// <param name="pos">Index of the bit at which to start searching.</param>
  411. /// <param name="numBits">Number of bits to test. Defaults to 1.</param>
  412. /// <returns>True if one or more of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
  413. /// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
  414. public bool TestAny(int pos, int numBits = 1)
  415. {
  416. CheckArgs(pos, numBits);
  417. var end = math.min(pos + numBits, Length);
  418. var idxB = pos >> 6;
  419. var shiftB = pos & 0x3f;
  420. var idxE = (end - 1) >> 6;
  421. var shiftE = end & 0x3f;
  422. var maskB = 0xfffffffffffffffful << shiftB;
  423. var maskE = 0xfffffffffffffffful >> (64 - shiftE);
  424. if (idxB == idxE)
  425. {
  426. var mask = maskB & maskE;
  427. return 0ul != (Ptr[idxB] & mask);
  428. }
  429. if (0ul != (Ptr[idxB] & maskB))
  430. {
  431. return true;
  432. }
  433. for (var idx = idxB + 1; idx < idxE; ++idx)
  434. {
  435. if (0ul != Ptr[idx])
  436. {
  437. return true;
  438. }
  439. }
  440. return 0ul != (Ptr[idxE] & maskE);
  441. }
  442. /// <summary>
  443. /// Returns true if all of the bits in a range are 1.
  444. /// </summary>
  445. /// <param name="pos">Index of the bit at which to start searching.</param>
  446. /// <param name="numBits">Number of bits to test. Defaults to 1.</param>
  447. /// <returns>True if all of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
  448. /// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
  449. public bool TestAll(int pos, int numBits = 1)
  450. {
  451. CheckArgs(pos, numBits);
  452. var end = math.min(pos + numBits, Length);
  453. var idxB = pos >> 6;
  454. var shiftB = pos & 0x3f;
  455. var idxE = (end - 1) >> 6;
  456. var shiftE = end & 0x3f;
  457. var maskB = 0xfffffffffffffffful << shiftB;
  458. var maskE = 0xfffffffffffffffful >> (64 - shiftE);
  459. if (idxB == idxE)
  460. {
  461. var mask = maskB & maskE;
  462. return mask == (Ptr[idxB] & mask);
  463. }
  464. if (maskB != (Ptr[idxB] & maskB))
  465. {
  466. return false;
  467. }
  468. for (var idx = idxB + 1; idx < idxE; ++idx)
  469. {
  470. if (0xfffffffffffffffful != Ptr[idx])
  471. {
  472. return false;
  473. }
  474. }
  475. return maskE == (Ptr[idxE] & maskE);
  476. }
  477. /// <summary>
  478. /// Returns the number of bits in a range that are 1.
  479. /// </summary>
  480. /// <param name="pos">Index of the bit at which to start searching.</param>
  481. /// <param name="numBits">Number of bits to test. Defaults to 1.</param>
  482. /// <returns>The number of bits in a range of bits that are 1.</returns>
  483. /// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
  484. public int CountBits(int pos, int numBits = 1)
  485. {
  486. CheckArgs(pos, numBits);
  487. var end = math.min(pos + numBits, Length);
  488. var idxB = pos >> 6;
  489. var shiftB = pos & 0x3f;
  490. var idxE = (end - 1) >> 6;
  491. var shiftE = end & 0x3f;
  492. var maskB = 0xfffffffffffffffful << shiftB;
  493. var maskE = 0xfffffffffffffffful >> (64 - shiftE);
  494. if (idxB == idxE)
  495. {
  496. var mask = maskB & maskE;
  497. return math.countbits(Ptr[idxB] & mask);
  498. }
  499. var count = math.countbits(Ptr[idxB] & maskB);
  500. for (var idx = idxB + 1; idx < idxE; ++idx)
  501. {
  502. count += math.countbits(Ptr[idx]);
  503. }
  504. count += math.countbits(Ptr[idxE] & maskE);
  505. return count;
  506. }
  507. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  508. static void CheckSizeMultipleOf8(int sizeInBytes)
  509. {
  510. if ((sizeInBytes & 7) != 0)
  511. throw new ArgumentException($"BitArray invalid arguments: sizeInBytes {sizeInBytes} (must be multiple of 8-bytes, sizeInBytes: {sizeInBytes}).");
  512. }
  513. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  514. void CheckArgs(int pos, int numBits)
  515. {
  516. if (pos < 0
  517. || pos >= Length
  518. || numBits < 1)
  519. {
  520. throw new ArgumentException($"BitArray invalid arguments: pos {pos} (must be 0-{Length - 1}), numBits {numBits} (must be greater than 0).");
  521. }
  522. }
  523. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  524. void CheckArgsPosCount(int begin, int count, int numBits)
  525. {
  526. if (begin < 0 || begin >= Length)
  527. {
  528. throw new ArgumentException($"BitArray invalid argument: begin {begin} (must be 0-{Length - 1}).");
  529. }
  530. if (count < 0 || count > Length)
  531. {
  532. throw new ArgumentException($"BitArray invalid argument: count {count} (must be 0-{Length}).");
  533. }
  534. if (numBits < 1 || count < numBits)
  535. {
  536. throw new ArgumentException($"BitArray invalid argument: numBits {numBits} (must be greater than 0).");
  537. }
  538. }
  539. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  540. void CheckArgsUlong(int pos, int numBits)
  541. {
  542. CheckArgs(pos, numBits);
  543. if (numBits < 1 || numBits > 64)
  544. {
  545. throw new ArgumentException($"BitArray invalid arguments: numBits {numBits} (must be 1-64).");
  546. }
  547. if (pos + numBits > Length)
  548. {
  549. throw new ArgumentException($"BitArray invalid arguments: Out of bounds pos {pos}, numBits {numBits}, Length {Length}.");
  550. }
  551. }
  552. [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
  553. static void CheckArgsCopy(ref UnsafeBitArray dstBitArray, int dstPos, ref UnsafeBitArray srcBitArray, int srcPos, int numBits)
  554. {
  555. if (srcPos + numBits > srcBitArray.Length)
  556. {
  557. throw new ArgumentException($"BitArray invalid arguments: Out of bounds - source position {srcPos}, numBits {numBits}, source bit array Length {srcBitArray.Length}.");
  558. }
  559. if (dstPos + numBits > dstBitArray.Length)
  560. {
  561. throw new ArgumentException($"BitArray invalid arguments: Out of bounds - destination position {dstPos}, numBits {numBits}, destination bit array Length {dstBitArray.Length}.");
  562. }
  563. }
  564. }
  565. sealed class UnsafeBitArrayDebugView
  566. {
  567. UnsafeBitArray Data;
  568. public UnsafeBitArrayDebugView(UnsafeBitArray data)
  569. {
  570. Data = data;
  571. }
  572. public bool[] Bits
  573. {
  574. get
  575. {
  576. var array = new bool[Data.Length];
  577. for (int i = 0; i < Data.Length; ++i)
  578. {
  579. array[i] = Data.IsSet(i);
  580. }
  581. return array;
  582. }
  583. }
  584. }
  585. }