NativeArrayHelper.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Unity.Collections;
  2. using Unity.Collections.LowLevel.Unsafe;
  3. namespace UnityEngine.U2D.Animation
  4. {
  5. internal static class NativeArrayHelpers
  6. {
  7. public static unsafe void ResizeIfNeeded<T>(ref NativeArray<T> nativeArray, int size, Allocator allocator = Allocator.Persistent) where T : struct
  8. {
  9. bool canDispose = nativeArray.IsCreated;
  10. if (canDispose && nativeArray.Length != size)
  11. {
  12. nativeArray.Dispose();
  13. canDispose = false;
  14. }
  15. if(!canDispose)
  16. nativeArray = new NativeArray<T>(size, allocator);
  17. }
  18. public static void ResizeAndCopyIfNeeded<T>(ref NativeArray<T> nativeArray, int size, Allocator allocator = Allocator.Persistent) where T : struct
  19. {
  20. bool canDispose = nativeArray.IsCreated;
  21. if (canDispose && nativeArray.Length == size)
  22. return;
  23. var newArray = new NativeArray<T>(size, allocator);
  24. if (canDispose)
  25. {
  26. NativeArray<T>.Copy(nativeArray, newArray, size < nativeArray.Length ? size : nativeArray.Length);
  27. nativeArray.Dispose();
  28. }
  29. nativeArray = newArray;
  30. }
  31. public static unsafe void DisposeIfCreated<T>(this NativeArray<T> nativeArray) where T : struct
  32. {
  33. if (nativeArray.IsCreated)
  34. nativeArray.Dispose();
  35. }
  36. [WriteAccessRequired]
  37. public static unsafe void CopyFromNativeSlice<T, S>(this NativeArray<T> nativeArray, int dstStartIndex, int dstEndIndex, NativeSlice<S> slice, int srcStartIndex, int srcEndIndex) where T : struct where S : struct
  38. {
  39. if ((dstEndIndex - dstStartIndex) != (srcEndIndex - srcStartIndex))
  40. throw new System.ArgumentException($"Destination and Source copy counts must match.", nameof(slice));
  41. var dstSizeOf = UnsafeUtility.SizeOf<T>();
  42. var srcSizeOf = UnsafeUtility.SizeOf<T>();
  43. byte* srcPtr = (byte*)slice.GetUnsafeReadOnlyPtr();
  44. srcPtr = srcPtr + (srcStartIndex * srcSizeOf);
  45. byte* dstPtr = (byte*)nativeArray.GetUnsafePtr();
  46. dstPtr = dstPtr + (dstStartIndex * dstSizeOf);
  47. UnsafeUtility.MemCpyStride(dstPtr, srcSizeOf, srcPtr, slice.Stride, dstSizeOf, srcEndIndex - srcStartIndex);
  48. }
  49. }
  50. }