using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Unity.Burst; using Unity.Jobs; using Unity.Jobs.LowLevel.Unsafe; using Unity.Mathematics; namespace Unity.Collections.LowLevel.Unsafe { [BurstCompile] internal unsafe struct UnsafeDisposeJob : IJob { [NativeDisableUnsafePtrRestriction] public void* Ptr; public AllocatorManager.AllocatorHandle Allocator; public void Execute() { AllocatorManager.Free(Allocator, Ptr); } } [StructLayout(LayoutKind.Sequential)] internal unsafe struct UntypedUnsafeList { #pragma warning disable 169 // // 'Header' of this struct must binary match `UntypedUnsafeList`, `UnsafeList`, `UnsafePtrList`, and `NativeArray` struct. [NativeDisableUnsafePtrRestriction] internal readonly void* Ptr; internal readonly int m_length; internal readonly int m_capacity; internal readonly AllocatorManager.AllocatorHandle Allocator; internal readonly int padding; #pragma warning restore 169 } /// /// An unmanaged, resizable list. /// /// The type of the elements. [DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}, IsEmpty = {IsEmpty}")] [DebuggerTypeProxy(typeof(UnsafeListTDebugView<>))] [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] [StructLayout(LayoutKind.Sequential)] public unsafe struct UnsafeList : INativeDisposable , INativeList , IEnumerable // Used by collection initializers. where T : unmanaged { // // 'Header' of this struct must binary match `UntypedUnsafeList`, `UnsafeList`, `UnsafePtrList`, and `NativeArray` struct. // Fields must match UntypedUnsafeList structure, please don't reorder and don't insert anything in between first 4 fields /// /// The internal buffer of this list. /// [NativeDisableUnsafePtrRestriction] public T* Ptr; /// /// The number of elements. /// public int m_length; /// /// The number of elements that can fit in the internal buffer. /// public int m_capacity; /// /// The allocator used to create the internal buffer. /// public AllocatorManager.AllocatorHandle Allocator; readonly int padding; /// /// The number of elements. /// /// The number of elements. public int Length { [MethodImpl(MethodImplOptions.AggressiveInlining)] readonly get => CollectionHelper.AssumePositive(m_length); set { if (value > Capacity) { Resize(value); } else { m_length = value; } } } /// /// The number of elements that can fit in the internal buffer. /// /// The number of elements that can fit in the internal buffer. public int Capacity { [MethodImpl(MethodImplOptions.AggressiveInlining)] readonly get => CollectionHelper.AssumePositive(m_capacity); set => SetCapacity(value); } /// /// The element at an index. /// /// An index. /// The element at the index. public T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { CollectionHelper.CheckIndexInRange(index, m_length); return Ptr[CollectionHelper.AssumePositive(index)]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { CollectionHelper.CheckIndexInRange(index, m_length); Ptr[CollectionHelper.AssumePositive(index)] = value; } } /// /// Returns a reference to the element at a given index. /// /// The index to access. Must be in the range of [0..Length). /// A reference to the element at the index. [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T ElementAt(int index) { CollectionHelper.CheckIndexInRange(index, m_length); return ref Ptr[CollectionHelper.AssumePositive(index)]; } /// /// Initializes and returns an instance of UnsafeList. /// /// An existing byte array to set as the internal buffer. /// The length. public UnsafeList(T* ptr, int length) : this() { Ptr = ptr; m_length = length; m_capacity = length; Allocator = AllocatorManager.None; } /// /// Initializes and returns an instance of UnsafeList. /// /// The initial capacity of the list. /// The allocator to use. /// Whether newly allocated bytes should be zeroed out. public UnsafeList(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) { Ptr = null; m_length = 0; m_capacity = 0; Allocator = allocator; padding = 0; SetCapacity(math.max(initialCapacity, 1)); if (options == NativeArrayOptions.ClearMemory && Ptr != null) { var sizeOf = sizeof(T); UnsafeUtility.MemClear(Ptr, Capacity * sizeOf); } } [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(AllocatorManager.AllocatorHandle) })] internal static UnsafeList* Create(int initialCapacity, ref U allocator, NativeArrayOptions options) where U : unmanaged, AllocatorManager.IAllocator { UnsafeList* listData = allocator.Allocate(default(UnsafeList), 1); *listData = new UnsafeList(initialCapacity, allocator.Handle, options); return listData; } [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(AllocatorManager.AllocatorHandle) })] internal static void Destroy(UnsafeList* listData, ref U allocator) where U : unmanaged, AllocatorManager.IAllocator { CheckNull(listData); listData->Dispose(ref allocator); allocator.Free(listData, sizeof(UnsafeList), UnsafeUtility.AlignOf>(), 1); } /// /// Returns a new list. /// /// The initial capacity of the list. /// The allocator to use. /// Whether newly allocated bytes should be zeroed out. /// A pointer to the new list. public static UnsafeList* Create(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) { UnsafeList* listData = AllocatorManager.Allocate>(allocator); *listData = new UnsafeList(initialCapacity, allocator, options); return listData; } /// /// Destroys the list. /// /// The list to destroy. public static void Destroy(UnsafeList* listData) { CheckNull(listData); var allocator = listData->Allocator; listData->Dispose(); AllocatorManager.Free(allocator, listData); } /// /// Whether the list is empty. /// /// True if the list is empty or the list has not been constructed. public readonly bool IsEmpty { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => !IsCreated || m_length == 0; } /// /// Whether this list has been allocated (and not yet deallocated). /// /// True if this list has been allocated (and not yet deallocated). public readonly bool IsCreated { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => Ptr != null; } [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(AllocatorManager.AllocatorHandle) })] internal void Dispose(ref U allocator) where U : unmanaged, AllocatorManager.IAllocator { allocator.Free(Ptr, m_capacity); Ptr = null; m_length = 0; m_capacity = 0; } /// /// Releases all resources (memory). /// public void Dispose() { if (!IsCreated) { return; } if (CollectionHelper.ShouldDeallocate(Allocator)) { AllocatorManager.Free(Allocator, Ptr, m_capacity); Allocator = AllocatorManager.Invalid; } Ptr = null; m_length = 0; m_capacity = 0; } /// /// Creates and schedules a job that frees the memory of this list. /// /// The dependency for the new job. /// The handle of the new job. The job depends upon `inputDeps` and frees the memory of this list. public JobHandle Dispose(JobHandle inputDeps) { if (!IsCreated) { return inputDeps; } if (CollectionHelper.ShouldDeallocate(Allocator)) { var jobHandle = new UnsafeDisposeJob { Ptr = Ptr, Allocator = Allocator }.Schedule(inputDeps); Ptr = null; Allocator = AllocatorManager.Invalid; return jobHandle; } Ptr = null; return inputDeps; } /// /// Sets the length to 0. /// /// Does not change the capacity. public void Clear() { m_length = 0; } /// /// Sets the length, expanding the capacity if necessary. /// /// The new length. /// Whether newly allocated bytes should be zeroed out. public void Resize(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) { var oldLength = m_length; if (length > Capacity) { SetCapacity(length); } m_length = length; if (options == NativeArrayOptions.ClearMemory && oldLength < length) { var num = length - oldLength; byte* ptr = (byte*)Ptr; var sizeOf = sizeof(T); UnsafeUtility.MemClear(ptr + oldLength * sizeOf, num * sizeOf); } } void ResizeExact(ref U allocator, int newCapacity) where U : unmanaged, AllocatorManager.IAllocator { newCapacity = math.max(0, newCapacity); CollectionHelper.CheckAllocator(Allocator); T* newPointer = null; var alignOf = UnsafeUtility.AlignOf(); var sizeOf = sizeof(T); if (newCapacity > 0) { newPointer = (T*)allocator.Allocate(sizeOf, alignOf, newCapacity); if (Ptr != null && m_capacity > 0) { var itemsToCopy = math.min(newCapacity, Capacity); var bytesToCopy = itemsToCopy * sizeOf; UnsafeUtility.MemCpy(newPointer, Ptr, bytesToCopy); } } allocator.Free(Ptr, Capacity); Ptr = newPointer; m_capacity = newCapacity; m_length = math.min(m_length, newCapacity); } void ResizeExact(int capacity) { ResizeExact(ref Allocator, capacity); } void SetCapacity(ref U allocator, int capacity) where U : unmanaged, AllocatorManager.IAllocator { CollectionHelper.CheckCapacityInRange(capacity, Length); var sizeOf = sizeof(T); var newCapacity = math.max(capacity, CollectionHelper.CacheLineSize / sizeOf); newCapacity = math.ceilpow2(newCapacity); if (newCapacity == Capacity) { return; } ResizeExact(ref allocator, newCapacity); } /// /// Sets the capacity. /// /// The new capacity. public void SetCapacity(int capacity) { SetCapacity(ref Allocator, capacity); } /// /// Sets the capacity to match the length. /// public void TrimExcess() { if (Capacity != m_length) { ResizeExact(m_length); } } /// /// Adds an element to the end of this list. /// /// /// Increments the length by 1. Never increases the capacity. /// /// The value to add to the end of the list. /// Thrown if incrementing the length would exceed the capacity. [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AddNoResize(T value) { CheckNoResizeHasEnoughCapacity(1); UnsafeUtility.WriteArrayElement(Ptr, m_length, value); m_length += 1; } /// /// Copies elements from a buffer to the end of this list. /// /// /// Increments the length by `count`. Never increases the capacity. /// /// The buffer to copy from. /// The number of elements to copy from the buffer. /// Thrown if the increased length would exceed the capacity. public void AddRangeNoResize(void* ptr, int count) { CheckNoResizeHasEnoughCapacity(count); var sizeOf = sizeof(T); void* dst = (byte*)Ptr + m_length * sizeOf; UnsafeUtility.MemCpy(dst, ptr, count * sizeOf); m_length += count; } /// /// Copies the elements of another list to the end of this list. /// /// The other list to copy from. /// /// Increments the length by the length of the other list. Never increases the capacity. /// /// Thrown if the increased length would exceed the capacity. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] public void AddRangeNoResize(UnsafeList list) { AddRangeNoResize(list.Ptr, CollectionHelper.AssumePositive(list.Length)); } /// /// Adds an element to the end of the list. /// /// The value to add to the end of this list. /// /// Increments the length by 1. Increases the capacity if necessary. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(in T value) { var idx = m_length; if (m_length < m_capacity) { Ptr[idx] = value; m_length++; return; } Resize(idx + 1); Ptr[idx] = value; } /// /// Copies the elements of a buffer to the end of this list. /// /// The buffer to copy from. /// The number of elements to copy from the buffer. /// /// Increments the length by `count`. Increases the capacity if necessary. /// public void AddRange(void* ptr, int count) { var idx = m_length; if (m_length + count > Capacity) { Resize(m_length + count); } else { m_length += count; } var sizeOf = sizeof(T); void* dst = (byte*)Ptr + idx * sizeOf; UnsafeUtility.MemCpy(dst, ptr, count * sizeOf); } /// /// Copies the elements of another list to the end of the list. /// /// The list to copy from. /// /// The length is increased by the length of the other list. Increases the capacity if necessary. /// [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] public void AddRange(UnsafeList list) { AddRange(list.Ptr, list.Length); } /// /// Appends value count times to the end of this list. /// /// The value to add to the end of this list. /// The number of times to replicate the value. /// /// Length is incremented by count. If necessary, the capacity is increased. /// public void AddReplicate(in T value, int count) { var idx = m_length; if (m_length + count > Capacity) { Resize(m_length + count); } else { m_length += count; } fixed (void* ptr = &value) { UnsafeUtility.MemCpyReplicate(Ptr + idx, ptr, UnsafeUtility.SizeOf(), count); } } /// /// Shifts elements toward the end of this list, increasing its length. /// /// /// Right-shifts elements in the list so as to create 'free' slots at the beginning or in the middle. /// /// The length is increased by `end - begin`. If necessary, the capacity will be increased accordingly. /// /// If `end` equals `begin`, the method does nothing. /// /// The element at index `begin` will be copied to index `end`, the element at index `begin + 1` will be copied to `end + 1`, and so forth. /// /// The indexes `begin` up to `end` are not cleared: they will contain whatever values they held prior. /// /// The index of the first element that will be shifted up. /// The index where the first shifted element will end up. /// Thrown if `end < begin`. /// Thrown if `begin` or `end` are out of bounds. public void InsertRangeWithBeginEnd(int begin, int end) { CheckBeginEndNoLength(begin, end); // Because we've checked begin and end in `CheckBeginEnd` above, we can now // assume they are positive. begin = CollectionHelper.AssumePositive(begin); end = CollectionHelper.AssumePositive(end); int items = end - begin; if (items < 1) { return; } var oldLength = m_length; if (m_length + items > Capacity) { Resize(m_length + items); } else { m_length += items; } var itemsToCopy = oldLength - begin; if (itemsToCopy < 1) { return; } var sizeOf = sizeof(T); var bytesToCopy = itemsToCopy * sizeOf; unsafe { byte* ptr = (byte*)Ptr; byte* dest = ptr + end * sizeOf; byte* src = ptr + begin * sizeOf; UnsafeUtility.MemMove(dest, src, bytesToCopy); } } /// /// Shifts elements toward the end of this list, increasing its length. /// /// /// Right-shifts elements in the list so as to create 'free' slots at the beginning or in the middle. /// /// The length is increased by `count`. If necessary, the capacity will be increased accordingly. /// /// If `count` equals `0`, the method does nothing. /// /// The element at index `index` will be copied to index `index + count`, the element at index `index + 1` will be copied to `index + count + 1`, and so forth. /// /// The indexes `index` up to `index + count` are not cleared: they will contain whatever values they held prior. /// /// The index of the first element that will be shifted up. /// The number of elements to insert. /// Thrown if `count` is negative. /// Thrown if `index` is out of bounds. public void InsertRange(int index, int count) => InsertRangeWithBeginEnd(index, index + count); /// /// Copies the last element of this list to the specified index. Decrements the length by 1. /// /// Useful as a cheap way to remove an element from this list when you don't care about preserving order. /// The index to overwrite with the last element. /// Thrown if `index` is out of bounds. public void RemoveAtSwapBack(int index) { CollectionHelper.CheckIndexInRange(index, m_length); index = CollectionHelper.AssumePositive(index); int copyFrom = m_length - 1; T* dst = (T*)Ptr + index; T* src = (T*)Ptr + copyFrom; (*dst) = (*src); m_length -= 1; } /// /// Copies the last *N* elements of this list to a range in this list. Decrements the length by *N*. /// /// /// Copies the last `count` elements to the indexes `index` up to `index + count`. /// /// Useful as a cheap way to remove elements from a list when you don't care about preserving order. /// /// The index of the first element to overwrite. /// The number of elements to copy and remove. /// Thrown if `index` is out of bounds /// Thrown if `count` is negative, /// or `index + count` exceeds the length. public void RemoveRangeSwapBack(int index, int count) { CheckIndexCount(index, count); index = CollectionHelper.AssumePositive(index); count = CollectionHelper.AssumePositive(count); if (count > 0) { int copyFrom = math.max(m_length - count, index + count); var sizeOf = sizeof(T); void* dst = (byte*)Ptr + index * sizeOf; void* src = (byte*)Ptr + copyFrom * sizeOf; UnsafeUtility.MemCpy(dst, src, (m_length - copyFrom) * sizeOf); m_length -= count; } } /// /// Removes the element at an index, shifting everything above it down by one. Decrements the length by 1. /// /// The index of the element to remove. /// /// If you don't care about preserving the order of the elements, is a more efficient way to remove elements. /// /// Thrown if `index` is out of bounds. public void RemoveAt(int index) { CollectionHelper.CheckIndexInRange(index, m_length); index = CollectionHelper.AssumePositive(index); T* dst = Ptr + index; T* src = dst + 1; m_length--; // Because these tend to be smaller (< 1MB), and the cost of jumping context to native and back is // so high, this consistently optimizes to better code than UnsafeUtility.MemCpy for (int i = index; i < m_length; i++) { *dst++ = *src++; } } /// /// Removes *N* elements in a range, shifting everything above the range down by *N*. Decrements the length by *N*. /// /// The index of the first element to remove. /// The number of elements to remove. /// /// If you don't care about preserving the order of the elements, `RemoveRangeSwapBackWithBeginEnd` /// is a more efficient way to remove elements. /// /// Thrown if `index` is out of bounds /// Thrown if `count` is negative, /// or `index + count` exceeds the length. public void RemoveRange(int index, int count) { CheckIndexCount(index, count); index = CollectionHelper.AssumePositive(index); count = CollectionHelper.AssumePositive(count); if (count > 0) { int copyFrom = math.min(index + count, m_length); var sizeOf = sizeof(T); void* dst = (byte*)Ptr + index * sizeOf; void* src = (byte*)Ptr + copyFrom * sizeOf; UnsafeUtility.MemCpy(dst, src, (m_length - copyFrom) * sizeOf); m_length -= count; } } /// /// Returns a read only of this list. /// /// A read only of this list. public ReadOnly AsReadOnly() { return new ReadOnly(Ptr, Length); } /// /// A read only for an UnsafeList<T>. /// /// /// Use to create a read only for a list. /// [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] public unsafe struct ReadOnly : IEnumerable { /// /// The internal buffer of the list. /// [NativeDisableUnsafePtrRestriction] public readonly T* Ptr; /// /// The number of elements. /// public readonly int Length; /// /// Whether this list has been allocated (and not yet deallocated). /// /// True if this list has been allocated (and not yet deallocated). public readonly bool IsCreated { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => Ptr != null; } /// /// Whether the list is empty. /// /// True if the list is empty or the list has not been constructed. public readonly bool IsEmpty { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => !IsCreated || Length == 0; } internal ReadOnly(T* ptr, int length) { Ptr = ptr; Length = length; } /// /// Returns an enumerator over the elements of the list. /// /// An enumerator over the elements of the list. public Enumerator GetEnumerator() { return new Enumerator { m_Ptr = Ptr, m_Length = Length, m_Index = -1 }; } /// /// This method is not implemented. Use instead. /// /// Throws NotImplementedException. /// Method is not implemented. IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } /// /// This method is not implemented. Use instead. /// /// Throws NotImplementedException. /// Method is not implemented. IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } /// /// **Obsolete.** Use instead. /// /// A parallel reader of this list. // [Obsolete("'AsParallelReader' has been deprecated; use 'AsReadOnly' instead. (UnityUpgradable) -> AsReadOnly")] public ParallelReader AsParallelReader() { return new ParallelReader(Ptr, Length); } /// /// **Obsolete.** Use instead. /// /// /// Use to create a parallel reader for a list. /// [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })] // [Obsolete("'ParallelReader' has been deprecated; use 'ReadOnly' instead. (UnityUpgradable) -> ReadOnly")] public unsafe struct ParallelReader { /// /// The internal buffer of the list. /// [NativeDisableUnsafePtrRestriction] public readonly T* Ptr; /// /// The number of elements. /// public readonly int Length; internal ParallelReader(T* ptr, int length) { Ptr = ptr; Length = length; } } /// /// Returns a parallel writer of this list. /// /// A parallel writer of this list. public ParallelWriter AsParallelWriter() { return new ParallelWriter((UnsafeList*)UnsafeUtility.AddressOf(ref this)); } /// /// A parallel writer for an UnsafeList<T>. /// /// /// Use to create a parallel writer for a list. /// [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })] public unsafe struct ParallelWriter { /// /// The data of the list. /// public readonly void* Ptr { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ListData->Ptr; } } /// /// The UnsafeList to write to. /// [NativeDisableUnsafePtrRestriction] public UnsafeList* ListData; internal unsafe ParallelWriter(UnsafeList* listData) { ListData = listData; } /// /// Adds an element to the end of the list. /// /// The value to add to the end of the list. /// /// Increments the length by 1. Never increases the capacity. /// /// Thrown if incrementing the length would exceed the capacity. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] public void AddNoResize(T value) { var idx = Interlocked.Increment(ref ListData->m_length) - 1; ListData->CheckNoResizeHasEnoughCapacity(idx, 1); UnsafeUtility.WriteArrayElement(ListData->Ptr, idx, value); } /// /// Copies elements from a buffer to the end of the list. /// /// The buffer to copy from. /// The number of elements to copy from the buffer. /// /// Increments the length by `count`. Never increases the capacity. /// /// Thrown if the increased length would exceed the capacity. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] public void AddRangeNoResize(void* ptr, int count) { var idx = Interlocked.Add(ref ListData->m_length, count) - count; ListData->CheckNoResizeHasEnoughCapacity(idx, count); void* dst = (byte*)ListData->Ptr + idx * sizeof(T); UnsafeUtility.MemCpy(dst, ptr, count * sizeof(T)); } /// /// Copies the elements of another list to the end of this list. /// /// The other list to copy from. /// /// Increments the length by the length of the other list. Never increases the capacity. /// /// Thrown if the increased length would exceed the capacity. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] public void AddRangeNoResize(UnsafeList list) { AddRangeNoResize(list.Ptr, list.Length); } } /// /// Copies all elements of specified container to this container. /// /// An container to copy into this container. public void CopyFrom(in NativeArray other) { Resize(other.Length); UnsafeUtility.MemCpy(Ptr, other.GetUnsafeReadOnlyPtr(), UnsafeUtility.SizeOf() * other.Length); } /// /// Copies all elements of specified container to this container. /// /// An container to copy into this container. public void CopyFrom(in UnsafeList other) { Resize(other.Length); UnsafeUtility.MemCpy(Ptr, other.Ptr, UnsafeUtility.SizeOf() * other.Length); } /// /// Returns an enumerator over the elements of the list. /// /// An enumerator over the elements of the list. public Enumerator GetEnumerator() { return new Enumerator { m_Ptr = Ptr, m_Length = Length, m_Index = -1 }; } /// /// This method is not implemented. Use instead. /// /// Throws NotImplementedException. /// Method is not implemented. IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } /// /// This method is not implemented. Use instead. /// /// Throws NotImplementedException. /// Method is not implemented. IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } /// /// An enumerator over the elements of a list. /// /// /// In an enumerator's initial state, is invalid. /// The first call advances the enumerator to the first element of the list. /// public struct Enumerator : IEnumerator { internal T* m_Ptr; internal int m_Length; internal int m_Index; /// /// Does nothing. /// public void Dispose() { } /// /// Advances the enumerator to the next element of the list. /// /// /// The first `MoveNext` call advances the enumerator to the first element of the list. Before this call, `Current` is not valid to read. /// /// True if `Current` is valid to read after the call. [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() => ++m_Index < m_Length; /// /// Resets the enumerator to its initial state. /// public void Reset() => m_Index = -1; /// /// The current element. /// /// The current element. public T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => m_Ptr[m_Index]; } object IEnumerator.Current => Current; } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")] internal static void CheckNull(void* listData) { if (listData == null) { throw new InvalidOperationException("UnsafeList has yet to be created or has been destroyed!"); } } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")] void CheckIndexCount(int index, int count) { if (count < 0) { throw new ArgumentOutOfRangeException($"Value for count {count} must be positive."); } if (index < 0) { throw new IndexOutOfRangeException($"Value for index {index} must be positive."); } if (index > Length) { throw new IndexOutOfRangeException($"Value for index {index} is out of bounds."); } if (index + count > Length) { throw new ArgumentOutOfRangeException($"Value for count {count} is out of bounds."); } } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")] void CheckBeginEndNoLength(int begin, int end) { if (begin > end) { throw new ArgumentException($"Value for begin {begin} index must less or equal to end {end}."); } if (begin < 0) { throw new ArgumentOutOfRangeException($"Value for begin {begin} must be positive."); } } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")] void CheckBeginEnd(int begin, int end) { CheckBeginEndNoLength(begin, end); if (begin > Length) { throw new ArgumentOutOfRangeException($"Value for begin {begin} is out of bounds."); } if (end > Length) { throw new ArgumentOutOfRangeException($"Value for end {end} is out of bounds."); } } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")] [MethodImpl(MethodImplOptions.AggressiveInlining)] void CheckNoResizeHasEnoughCapacity(int length) { CheckNoResizeHasEnoughCapacity(length, Length); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")] [MethodImpl(MethodImplOptions.AggressiveInlining)] void CheckNoResizeHasEnoughCapacity(int length, int index) { if (Capacity < index + length) { throw new InvalidOperationException($"AddNoResize assumes that list capacity is sufficient (Capacity {Capacity}, Length {Length}), requested length {length}!"); } } } /// /// Provides extension methods for UnsafeList. /// [GenerateTestsForBurstCompatibility] public unsafe static class UnsafeListExtensions { /// /// Finds the index of the first occurrence of a particular value in this list. /// /// The type of elements in this list. /// The type of value to locate. /// This list. /// A value to locate. /// The zero-based index of the first occurrence of the value if it is found. Returns -1 if no occurrence is found. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })] public static int IndexOf(this UnsafeList list, U value) where T : unmanaged, IEquatable { return NativeArrayExtensions.IndexOf(list.Ptr, list.Length, value); } /// /// Returns true if a particular value is present in this list. /// /// The type of elements in the list. /// The type of value to locate. /// This list. /// The value to locate. /// True if the value is present in this list. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })] public static bool Contains(this UnsafeList list, U value) where T : unmanaged, IEquatable { return list.IndexOf(value) != -1; } /// /// Finds the index of the first occurrence of a particular value in the list. /// /// The type of elements in the list. /// The type of value to locate. /// This reader of the list. /// A value to locate. /// The zero-based index of the first occurrence of the value if it is found. Returns -1 if no occurrence is found. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })] public static int IndexOf(this UnsafeList.ReadOnly list, U value) where T : unmanaged, IEquatable { return NativeArrayExtensions.IndexOf(list.Ptr, list.Length, value); } /// /// Returns true if a particular value is present in the list. /// /// The type of elements in the list. /// The type of value to locate. /// This reader of the list. /// The value to locate. /// True if the value is present in the list. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })] public static bool Contains(this UnsafeList.ReadOnly list, U value) where T : unmanaged, IEquatable { return list.IndexOf(value) != -1; } /// /// **Obsolete.** Use instead. /// /// The type of elements in the list. /// The type of value to locate. /// This reader of the list. /// A value to locate. /// The zero-based index of the first occurrence of the value if it is found. Returns -1 if no occurrence is found. // [Obsolete("'UnsafeList.ParallelReader' has been deprecated; use 'UnsafeList.ReadOnly' instead.")] [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })] public static int IndexOf(this UnsafeList.ParallelReader list, U value) where T : unmanaged, IEquatable { return NativeArrayExtensions.IndexOf(list.Ptr, list.Length, value); } /// /// **Obsolete.** Use instead. /// /// The type of elements in the list. /// The type of value to locate. /// This reader of the list. /// The value to locate. /// True if the value is present in the list. // [Obsolete("'UnsafeList.ParallelReader' has been deprecated; use 'UnsafeList.ReadOnly' instead.")] [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })] public static bool Contains(this UnsafeList.ParallelReader list, U value) where T : unmanaged, IEquatable { return list.IndexOf(value) != -1; } /// /// Returns true if this container and another have equal length and content. /// /// The type of the source container's elements. /// The container to compare for equality. /// The other container to compare for equality. /// True if the containers have equal length and content. [GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })] public static bool ArraysEqual(this UnsafeList container, in UnsafeList other) where T : unmanaged, IEquatable { if (container.Length != other.Length) return false; for (int i = 0; i != container.Length; i++) { if (!container[i].Equals(other[i])) return false; } return true; } } internal sealed class UnsafeListTDebugView where T : unmanaged { UnsafeList Data; public UnsafeListTDebugView(UnsafeList data) { Data = data; } public unsafe T[] Items { get { T[] result = new T[Data.Length]; for (var i = 0; i < result.Length; ++i) { result[i] = Data.Ptr[i]; } return result; } } } /// /// An unmanaged, resizable list of pointers. /// /// The type of pointer element. [DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}, IsEmpty = {IsEmpty}")] [DebuggerTypeProxy(typeof(UnsafePtrListDebugView<>))] [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] [StructLayout(LayoutKind.Sequential)] public unsafe struct UnsafePtrList : INativeDisposable // IIndexable and INativeList can't be implemented because this[index] and ElementAt return T* instead of T. , IEnumerable // Used by collection initializers. where T : unmanaged { // // 'Header' of this struct must binary match `UntypedUnsafeList`, `UnsafeList`, `UnsafePtrList`, and `NativeArray` struct. // Fields must match UntypedUnsafeList structure, please don't reorder and don't insert anything in between first 4 fields /// /// The internal buffer of this list. /// [NativeDisableUnsafePtrRestriction] public readonly T** Ptr; /// /// The number of elements. /// public readonly int m_length; /// /// The number of elements that can fit in the internal buffer. /// public readonly int m_capacity; /// /// The allocator used to create the internal buffer. /// public readonly AllocatorManager.AllocatorHandle Allocator; readonly int padding; /// /// The number of elements. /// /// The number of elements. public int Length { [MethodImpl(MethodImplOptions.AggressiveInlining)] readonly get => this.ListDataRO().Length; set => this.ListData().Length = value; } /// /// The number of elements that can fit in the internal buffer. /// /// The number of elements that can fit in the internal buffer. public int Capacity { [MethodImpl(MethodImplOptions.AggressiveInlining)] readonly get => this.ListDataRO().Capacity; set => this.ListData().Capacity = value; } /// /// The element at an index. /// /// An index. /// The element at the index. public T* this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { CollectionHelper.CheckIndexInRange(index, Length); return Ptr[CollectionHelper.AssumePositive(index)]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { CollectionHelper.CheckIndexInRange(index, Length); Ptr[CollectionHelper.AssumePositive(index)] = value; } } /// /// Returns a reference to the element at a given index. /// /// The index to access. Must be in the range of [0..Length). /// A reference to the element at the index. [MethodImpl(MethodImplOptions.AggressiveInlining)] public ref T* ElementAt(int index) { CollectionHelper.CheckIndexInRange(index, Length); return ref Ptr[CollectionHelper.AssumePositive(index)]; } /// /// Initializes and returns an instance of UnsafePtrList. /// /// An existing pointer array to set as the internal buffer. /// The length. public unsafe UnsafePtrList(T** ptr, int length) : this() { Ptr = ptr; m_length = length; m_capacity = length; Allocator = AllocatorManager.None; } /// /// Initializes and returns an instance of UnsafePtrList. /// /// The initial capacity of the list. /// The allocator to use. /// Whether newly allocated bytes should be zeroed out. public unsafe UnsafePtrList(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) { Ptr = null; m_length = 0; m_capacity = 0; padding = 0; Allocator = AllocatorManager.None; this.ListData() = new UnsafeList(initialCapacity, allocator, options); } /// /// Returns a new list of pointers. /// /// An existing pointer array to set as the internal buffer. /// The length. /// A pointer to the new list. public static UnsafePtrList* Create(T** ptr, int length) { UnsafePtrList* listData = AllocatorManager.Allocate>(AllocatorManager.Persistent); *listData = new UnsafePtrList(ptr, length); return listData; } /// /// Returns a new list of pointers. /// /// The initial capacity of the list. /// The allocator to use. /// Whether newly allocated bytes should be zeroed out. /// A pointer to the new list. public static UnsafePtrList* Create(int initialCapacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) { UnsafePtrList* listData = AllocatorManager.Allocate>(allocator); *listData = new UnsafePtrList(initialCapacity, allocator, options); return listData; } /// /// Destroys the list. /// /// The list to destroy. public static void Destroy(UnsafePtrList* listData) { UnsafeList.CheckNull(listData); var allocator = listData->ListData().Allocator.Value == AllocatorManager.Invalid.Value ? AllocatorManager.Persistent : listData->ListData().Allocator ; listData->Dispose(); AllocatorManager.Free(allocator, listData); } /// /// Whether the list is empty. /// /// True if the list is empty or the list has not been constructed. public readonly bool IsEmpty { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => !IsCreated || Length == 0; } /// /// Whether this list has been allocated (and not yet deallocated). /// /// True if this list has been allocated (and not yet deallocated). public readonly bool IsCreated { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => Ptr != null; } /// /// Releases all resources (memory). /// public void Dispose() { this.ListData().Dispose(); } /// /// Creates and schedules a job that frees the memory of this list. /// /// The dependency for the new job. /// The handle of the new job. The job depends upon `inputDeps` and frees the memory of this list. public JobHandle Dispose(JobHandle inputDeps) => this.ListData().Dispose(inputDeps); /// /// Sets the length to 0. /// /// Does not change the capacity. public void Clear() => this.ListData().Clear(); /// /// Sets the length, expanding the capacity if necessary. /// /// The new length. /// Whether newly allocated bytes should be zeroed out. public void Resize(int length, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory) => this.ListData().Resize(length, options); /// /// Sets the capacity. /// /// The new capacity. public void SetCapacity(int capacity) => this.ListData().SetCapacity(capacity); /// /// Sets the capacity to match the length. /// public void TrimExcess() => this.ListData().TrimExcess(); /// /// Returns the index of the first occurrence of a specific pointer in the list. /// /// The pointer to search for in the list. /// The index of the first occurrence of the pointer. Returns -1 if it is not found in the list. public int IndexOf(void* ptr) { for (int i = 0; i < Length; ++i) { if (Ptr[i] == ptr) return i; } return -1; } /// /// Returns true if the list contains at least one occurrence of a specific pointer. /// /// The pointer to search for in the list. /// True if the list contains at least one occurrence of the pointer. public bool Contains(void* ptr) { return IndexOf(ptr) != -1; } /// /// Adds a pointer to the end of this list. /// /// /// Increments the length by 1. Never increases the capacity. /// /// The pointer to add to the end of the list. /// Thrown if incrementing the length would exceed the capacity. public void AddNoResize(void* value) { this.ListData().AddNoResize((IntPtr)value); } /// /// Copies pointers from a buffer to the end of this list. /// /// /// Increments the length by `count`. Never increases the capacity. /// /// The buffer to copy from. /// The number of pointers to copy from the buffer. /// Thrown if the increased length would exceed the capacity. public void AddRangeNoResize(void** ptr, int count) => this.ListData().AddRangeNoResize(ptr, count); /// /// Copies the pointers of another list to the end of this list. /// /// The other list to copy from. /// /// Increments the length by the length of the other list. Never increases the capacity. /// /// Thrown if the increased length would exceed the capacity. public void AddRangeNoResize(UnsafePtrList list) => this.ListData().AddRangeNoResize(list.Ptr, list.Length); /// /// Adds a pointer to the end of the list. /// /// The pointer to add to the end of this list. /// /// Increments the length by 1. Increases the capacity if necessary. /// public void Add(in IntPtr value) { this.ListData().Add(value); } /// /// Adds a pointer to the end of the list. /// /// The pointer to add to the end of this list. /// /// Increments the length by 1. Increases the capacity if necessary. /// public void Add(void* value) { this.ListData().Add((IntPtr)value); } /// /// Adds elements from a buffer to this list. /// /// A pointer to the buffer. /// The number of elements to add to the list. public void AddRange(void* ptr, int length) => this.ListData().AddRange(ptr, length); /// /// Copies the elements of another list to the end of this list. /// /// The other list to copy from. /// /// Increments the length by the length of the other list. Increases the capacity if necessary. /// public void AddRange(UnsafePtrList list) => this.ListData().AddRange(list.ListData()); /// /// Shifts pointers toward the end of this list, increasing its length. /// /// /// Right-shifts pointers in the list so as to create 'free' slots at the beginning or in the middle. /// /// The length is increased by `end - begin`. If necessary, the capacity will be increased accordingly. /// /// If `end` equals `begin`, the method does nothing. /// /// The pointer at index `begin` will be copied to index `end`, the pointer at index `begin + 1` will be copied to `end + 1`, and so forth. /// /// The indexes `begin` up to `end` are not cleared: they will contain whatever pointers they held prior. /// /// The index of the first pointer that will be shifted up. /// The index where the first shifted pointer will end up. /// Thrown if `end < begin`. /// Thrown if `begin` or `end` are out of bounds. public void InsertRangeWithBeginEnd(int begin, int end) => this.ListData().InsertRangeWithBeginEnd(begin, end); /// /// Copies the last pointer of this list to the specified index. Decrements the length by 1. /// /// Useful as a cheap way to remove a pointer from this list when you don't care about preserving order. /// The index to overwrite with the last pointer. /// Thrown if `index` is out of bounds. public void RemoveAtSwapBack(int index) => this.ListData().RemoveAtSwapBack(index); /// /// Copies the last *N* pointer of this list to a range in this list. Decrements the length by *N*. /// /// /// Copies the last `count` pointers to the indexes `index` up to `index + count`. /// /// Useful as a cheap way to remove pointers from a list when you don't care about preserving order. /// /// The index of the first pointer to overwrite. /// The number of pointers to copy and remove. /// Thrown if `index` is out of bounds /// Thrown if `count` is negative, /// or `index + count` exceeds the length. public void RemoveRangeSwapBack(int index, int count) => this.ListData().RemoveRangeSwapBack(index, count); /// /// Removes the pointer at an index, shifting everything above it down by one. Decrements the length by 1. /// /// The index of the pointer to remove. /// /// If you don't care about preserving the order of the pointers, is a more efficient way to remove pointers. /// /// Thrown if `index` is out of bounds. public void RemoveAt(int index) => this.ListData().RemoveAt(index); /// /// Removes *N* pointers in a range, shifting everything above the range down by *N*. Decrements the length by *N*. /// /// The index of the first pointer to remove. /// The number of pointers to remove. /// /// If you don't care about preserving the order of the pointers, `RemoveRangeSwapBackWithBeginEnd` /// is a more efficient way to remove pointers. /// /// Thrown if `index` is out of bounds /// Thrown if `count` is negative, /// or `index + count` exceeds the length. public void RemoveRange(int index, int count) => this.ListData().RemoveRange(index, count); /// /// This method is not implemented. It will throw NotImplementedException if it is used. /// /// Use Enumerator GetEnumerator() instead. /// Throws NotImplementedException. /// Method is not implemented. IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } /// /// This method is not implemented. It will throw NotImplementedException if it is used. /// /// Use Enumerator GetEnumerator() instead. /// Throws NotImplementedException. /// Method is not implemented. IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } /// /// Returns a read only of this list. /// /// A read only of this list. public ReadOnly AsReadOnly() { return new ReadOnly(Ptr, Length); } /// /// A read only for an UnsafePtrList<T>. /// /// /// Use to create a read only for a list. /// [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] public unsafe struct ReadOnly { /// /// The internal buffer of the list. /// [NativeDisableUnsafePtrRestriction] public readonly T** Ptr; /// /// The number of elements. /// public readonly int Length; /// /// Whether this list has been allocated (and not yet deallocated). /// /// True if this list has been allocated (and not yet deallocated). public readonly bool IsCreated { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => Ptr != null; } /// /// Whether the list is empty. /// /// True if the list is empty or the list has not been constructed. public readonly bool IsEmpty { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => !IsCreated || Length == 0; } internal ReadOnly(T** ptr, int length) { Ptr = ptr; Length = length; } /// /// Returns the index of the first occurrence of a specific pointer in the list. /// /// The pointer to search for in the list. /// The index of the first occurrence of the pointer. Returns -1 if it is not found in the list. public int IndexOf(void* ptr) { for (int i = 0; i < Length; ++i) { if (Ptr[i] == ptr) return i; } return -1; } /// /// Returns true if the list contains at least one occurrence of a specific pointer. /// /// The pointer to search for in the list. /// True if the list contains at least one occurrence of the pointer. public bool Contains(void* ptr) { return IndexOf(ptr) != -1; } } /// /// **Obsolete**. Use instead. /// /// A parallel reader of this list. // [Obsolete("'AsParallelReader' has been deprecated; use 'AsReadOnly' instead. (UnityUpgradable) -> AsReadOnly")] public ParallelReader AsParallelReader() { return new ParallelReader(Ptr, Length); } /// /// **Obsolete.** Use instead. /// /// /// Use to create a parallel reader for a list. /// // [Obsolete("'ParallelReader' has been deprecated; use 'ReadOnly' instead. (UnityUpgradable) -> ReadOnly")] [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] public unsafe struct ParallelReader { /// /// The internal buffer of the list. /// [NativeDisableUnsafePtrRestriction] public readonly T** Ptr; /// /// The number of elements. /// public readonly int Length; internal ParallelReader(T** ptr, int length) { Ptr = ptr; Length = length; } /// /// Returns the index of the first occurrence of a specific pointer in the list. /// /// The pointer to search for in the list. /// The index of the first occurrence of the pointer. Returns -1 if it is not found in the list. public int IndexOf(void* ptr) { for (int i = 0; i < Length; ++i) { if (Ptr[i] == ptr) return i; } return -1; } /// /// Returns true if the list contains at least one occurrence of a specific pointer. /// /// The pointer to search for in the list. /// True if the list contains at least one occurrence of the pointer. public bool Contains(void* ptr) { return IndexOf(ptr) != -1; } } /// /// Returns a parallel writer of this list. /// /// A parallel writer of this list. public ParallelWriter AsParallelWriter() { return new ParallelWriter(Ptr, (UnsafeList*)UnsafeUtility.AddressOf(ref this)); } /// /// A parallel writer for an UnsafePtrList<T>. /// /// /// Use to create a parallel writer for a list. /// [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] public unsafe struct ParallelWriter { /// /// The data of the list. /// [NativeDisableUnsafePtrRestriction] public readonly T** Ptr; /// /// The UnsafeList to write to. /// [NativeDisableUnsafePtrRestriction] public UnsafeList* ListData; internal unsafe ParallelWriter(T** ptr, UnsafeList* listData) { Ptr = ptr; ListData = listData; } /// /// Adds a pointer to the end of the list. /// /// The pointer to add to the end of the list. /// /// Increments the length by 1. Never increases the capacity. /// /// Thrown if incrementing the length would exceed the capacity. public void AddNoResize(T* value) => ListData->AddNoResize((IntPtr)value); /// /// Copies pointers from a buffer to the end of the list. /// /// The buffer to copy from. /// The number of pointers to copy from the buffer. /// /// Increments the length by `count`. Never increases the capacity. /// /// Thrown if the increased length would exceed the capacity. public void AddRangeNoResize(T** ptr, int count) => ListData->AddRangeNoResize(ptr, count); /// /// Copies the pointers of another list to the end of this list. /// /// The other list to copy from. /// /// Increments the length by the length of the other list. Never increases the capacity. /// /// Thrown if the increased length would exceed the capacity. public void AddRangeNoResize(UnsafePtrList list) => ListData->AddRangeNoResize(list.Ptr, list.Length); } } [GenerateTestsForBurstCompatibility] internal static class UnsafePtrListExtensions { [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref UnsafeList ListData(ref this UnsafePtrList from) where T : unmanaged => ref UnsafeUtility.As, UnsafeList>(ref from); [GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static UnsafeList ListDataRO(this UnsafePtrList from) where T : unmanaged => UnsafeUtility.As, UnsafeList>(ref from); } internal sealed class UnsafePtrListDebugView where T : unmanaged { UnsafePtrList Data; public UnsafePtrListDebugView(UnsafePtrList data) { Data = data; } public unsafe T*[] Items { get { T*[] result = new T*[Data.Length]; for (var i = 0; i < result.Length; ++i) { result[i] = Data.Ptr[i]; } return result; } } } }