DynamicBitfield.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using UnityEngine.InputSystem.Utilities;
  2. namespace UnityEngine.InputSystem
  3. {
  4. /// <summary>
  5. /// Struct replacement for System.Collections.Bitfield.
  6. /// </summary>
  7. /// <remarks>
  8. /// We don't want the extra heap object just for keeping the header
  9. /// state of the bitfield. This struct directly embeds the header
  10. /// into the owner. Also doesn't allocate any array while length is
  11. /// less than or equal to 64 bits.
  12. /// </remarks>
  13. internal struct DynamicBitfield
  14. {
  15. public InlinedArray<ulong> array;
  16. public int length;
  17. public void SetLength(int newLength)
  18. {
  19. // Don't touch array size if we don't have to. We're fine having a
  20. // larger array to work with if it's already in place.
  21. var ulongCount = BitCountToULongCount(newLength);
  22. if (array.length < ulongCount)
  23. array.SetLength(ulongCount);
  24. length = newLength;
  25. }
  26. public void SetBit(int bitIndex)
  27. {
  28. Debug.Assert(bitIndex >= 0);
  29. Debug.Assert(bitIndex < length);
  30. array[bitIndex / 64] |= (ulong)1 << (bitIndex % 64);
  31. }
  32. public bool TestBit(int bitIndex)
  33. {
  34. Debug.Assert(bitIndex >= 0);
  35. Debug.Assert(bitIndex < length);
  36. return (array[bitIndex / 64] & ((ulong)1 << (bitIndex % 64))) != 0;
  37. }
  38. public void ClearBit(int bitIndex)
  39. {
  40. Debug.Assert(bitIndex >= 0);
  41. Debug.Assert(bitIndex < length);
  42. array[bitIndex / 64] &= ~((ulong)1 << (bitIndex % 64));
  43. }
  44. private static int BitCountToULongCount(int bitCount)
  45. {
  46. return (bitCount + 63) / 64;
  47. }
  48. }
  49. }