Make `AddNoResize` and `AddRangeNoResize` of `ParallelWriter` of `NativeList<T>` and `UnsafeList<T>` return the index of added element

It would be beneficial for jobs if in the type NativeList<T>.ParallelWriter and UnsafeList<T>.ParallelWriter, the methods:

  • void AddNoResize(T).
  • void AddRangeNoResize(void* ptr, int count).
  • void AddRangeNoResize(UnsafeList<T>).
  • void AddRangeNoResize(NativeList<T>).

Rather than returning void they returned int, being that the index at which the element (or first element for AddRangeNoResize([...]) was added.

Implementing it is extremely easy (the code already knows the index to add the element, we can just return it) and would allow more functionality in this type.

I got this idea by trying to emulate NativeArray<NativeList<T>> which is unsupported. Instead, I wanted to have something along the lines of:

NativeArray<int> indexes; // In my case I already know the length of this array before running.
NativeList<Element>.ParallelWriter elements; // But not the length of this one.
struct Element { public int prev; public T value; }

void Add(int index, T element) 
{
    int prevIndex = indexes[index];
    Element e = new() { prev = prevIndex, value = element }; // Order gets reversed, but I don't care.
    int newIndex = elements.AddNoResize(e);
    indexes[index] = newIndex;
}

At the moment, to do that I’m forced to use NativeParallelMultiHashMap<int, T>, which is less performant as it computes hashes (where I only require indexes) and can resize the key numbers (which in my case it not needed).

These improvements in the API could probably be useful for many other cases.

2 Likes