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