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.

115 lines
2.8KB

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