Mirror of Svelto.ECS because we're a fan of it
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.

127 lines
3.0KB

  1. using System;
  2. using System.Threading;
  3. using Svelto.Common;
  4. namespace Svelto.ECS.DataStructures
  5. {
  6. public struct SharedNativeInt: IDisposable
  7. {
  8. #if UNITY_COLLECTIONS || UNITY_JOBS || UNITY_BURST
  9. [global::Unity.Collections.LowLevel.Unsafe.NativeDisableUnsafePtrRestriction]
  10. #endif
  11. unsafe int* data;
  12. Allocator _allocator;
  13. public SharedNativeInt(Allocator allocator)
  14. {
  15. unsafe
  16. {
  17. _allocator = allocator;
  18. data = (int*) MemoryUtilities.Alloc(sizeof(int), allocator);
  19. }
  20. }
  21. public static SharedNativeInt Create(int t, Allocator allocator)
  22. {
  23. unsafe
  24. {
  25. var current = new SharedNativeInt();
  26. current._allocator = allocator;
  27. current.data = (int*) MemoryUtilities.Alloc(sizeof(int), allocator);
  28. *current.data = t;
  29. return current;
  30. }
  31. }
  32. public static implicit operator int(SharedNativeInt t)
  33. {
  34. unsafe
  35. {
  36. #if DEBUG && !PROFILE_SVELTO
  37. if (t.data == null)
  38. throw new Exception("using disposed SharedInt");
  39. #endif
  40. return *t.data;
  41. }
  42. }
  43. public void Dispose()
  44. {
  45. unsafe
  46. {
  47. if (data != null)
  48. {
  49. MemoryUtilities.Free((IntPtr) data, _allocator);
  50. data = null;
  51. }
  52. }
  53. }
  54. public int Decrement()
  55. {
  56. unsafe
  57. {
  58. #if DEBUG && !PROFILE_SVELTO
  59. if (data == null)
  60. throw new Exception("null-access");
  61. #endif
  62. return Interlocked.Decrement(ref *data);
  63. }
  64. }
  65. public int Increment()
  66. {
  67. unsafe
  68. {
  69. #if DEBUG && !PROFILE_SVELTO
  70. if (data == null)
  71. throw new Exception("null-access");
  72. #endif
  73. return Interlocked.Increment(ref *data);
  74. }
  75. }
  76. public int Add(int val)
  77. {
  78. unsafe
  79. {
  80. #if DEBUG && !PROFILE_SVELTO
  81. if (data == null)
  82. throw new Exception("null-access");
  83. #endif
  84. return Interlocked.Add(ref *data, val);
  85. }
  86. }
  87. public int CompareExchange(int value, int compare)
  88. {
  89. unsafe
  90. {
  91. #if DEBUG && !PROFILE_SVELTO
  92. if (data == null)
  93. throw new Exception("null-access");
  94. #endif
  95. return Interlocked.CompareExchange(ref *data, value, compare);
  96. }
  97. }
  98. public void Set(int val)
  99. {
  100. unsafe
  101. {
  102. #if DEBUG && !PROFILE_SVELTO
  103. if (data == null)
  104. throw new Exception("null-access");
  105. #endif
  106. Volatile.Write(ref *data, val);
  107. }
  108. }
  109. }
  110. }