This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b49443f1e93e4dec9a7a68741679aa52
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,24 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Unity.Burst.Tests")]
[assembly: InternalsVisibleTo("Unity.Collections.BurstCompatibilityTestCodeGen")]
[assembly: InternalsVisibleTo("Unity.Collections.Tests")]
[assembly: InternalsVisibleTo("Unity.Collections.CodeGen")]
[assembly: InternalsVisibleTo("Unity.Collections.Editor")]
[assembly: InternalsVisibleTo("Unity.Collections.PerformanceTests")]
[assembly: InternalsVisibleTo("Unity.Entities")]
[assembly: InternalsVisibleTo("Unity.Entities.CodeGen")]
[assembly: InternalsVisibleTo("Unity.Entities.Tests")]
[assembly: InternalsVisibleTo("Unity.Entities.Editor")]
[assembly: InternalsVisibleTo("Unity.Entities.Editor.Tests")]
[assembly: InternalsVisibleTo("Unity.Entities.Graphics")]
[assembly: InternalsVisibleTo("Unity.Entities.Hybrid")]
[assembly: InternalsVisibleTo("Unity.Runtime")]
[assembly: InternalsVisibleTo("Unity.Runtime.Tests")]
[assembly: InternalsVisibleTo("Unity.Runtime.IO.Tests")]
[assembly: InternalsVisibleTo("Unity.Runtime.UnityInstance")]
[assembly: InternalsVisibleTo("Unity.Scenes")]
[assembly: InternalsVisibleTo("Unity.Scenes.Editor")]
[assembly: InternalsVisibleTo("Samples.GridPath.Tests")]
[assembly: InternalsVisibleTo("Unity.Entities.PerformanceTests")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.GPUDriven.Runtime")]
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 63bc65d8d2fe144e1b071aeb3b624536
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,264 @@
using System;
using System.Diagnostics;
using System.Threading;
using AOT;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
namespace Unity.Collections
{
unsafe internal struct ArrayOfArrays<T> : IDisposable where T : unmanaged
{
AllocatorManager.AllocatorHandle m_backingAllocatorHandle;
int m_lengthInElements;
int m_capacityInElements;
int m_log2BlockSizeInElements;
int m_blocks;
IntPtr* m_block;
int BlockSizeInElements => 1 << m_log2BlockSizeInElements;
int BlockSizeInBytes => BlockSizeInElements * sizeof(T);
int BlockMask => BlockSizeInElements - 1;
public int Length => m_lengthInElements;
public int Capacity => m_capacityInElements;
public ArrayOfArrays(int capacityInElements, AllocatorManager.AllocatorHandle backingAllocatorHandle, int log2BlockSizeInElements = 12)
{
this = default;
m_backingAllocatorHandle = backingAllocatorHandle;
m_lengthInElements = 0;
m_capacityInElements = capacityInElements;
m_log2BlockSizeInElements = log2BlockSizeInElements;
m_blocks = (capacityInElements + BlockMask) >> m_log2BlockSizeInElements;
m_block = (IntPtr*)Memory.Unmanaged.Allocate(sizeof(IntPtr) * m_blocks, 16, m_backingAllocatorHandle);
UnsafeUtility.MemSet(m_block, 0, sizeof(IntPtr) * m_blocks);
}
public void LockfreeAdd(T t)
{
var elementIndex = Interlocked.Increment(ref m_lengthInElements) - 1;
var blockIndex = BlockIndexOfElement(elementIndex);
CheckBlockIndex(blockIndex);
if(m_block[blockIndex] == IntPtr.Zero)
{
void* pointer = Memory.Unmanaged.Allocate(BlockSizeInBytes, 16, m_backingAllocatorHandle); // $$$!
var lastBlock = math.min(m_blocks, blockIndex + 4); // don't overgrow too fast, simply to avoid a $$$ free
for(; blockIndex < lastBlock; ++blockIndex)
if(IntPtr.Zero == Interlocked.CompareExchange(ref m_block[blockIndex], (IntPtr)pointer, IntPtr.Zero))
break; // install the new block, into *any* empty slot available, to avoid wasting the time we spent on malloc
if(blockIndex == lastBlock)
Memory.Unmanaged.Free(pointer, m_backingAllocatorHandle); // $$$, only if absolutely necessary
}
this[elementIndex] = t;
}
public ref T this[int elementIndex]
{
get
{
CheckElementIndex(elementIndex);
var blockIndex = BlockIndexOfElement(elementIndex);
CheckBlockIndex(blockIndex);
CheckBlockIsNotNull(blockIndex);
IntPtr blockIntPtr = m_block[blockIndex];
var elementIndexInBlock = elementIndex & BlockMask;
T* blockPointer = (T*)blockIntPtr;
return ref blockPointer[elementIndexInBlock];
}
}
public void Rewind()
{
m_lengthInElements = 0;
}
public void Clear()
{
Rewind();
for(var i = 0; i < m_blocks; ++i)
if(m_block[i] != IntPtr.Zero)
{
Memory.Unmanaged.Free((void*)m_block[i], m_backingAllocatorHandle);
m_block[i] = IntPtr.Zero;
}
}
public void Dispose()
{
Clear();
Memory.Unmanaged.Free(m_block, m_backingAllocatorHandle);
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckElementIndex(int elementIndex)
{
if (elementIndex >= m_lengthInElements)
throw new ArgumentException($"Element index {elementIndex} must be less than length in elements {m_lengthInElements}.");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckBlockIndex(int blockIndex)
{
if (blockIndex >= m_blocks)
throw new ArgumentException($"Block index {blockIndex} must be less than number of blocks {m_blocks}.");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckBlockIsNotNull(int blockIndex)
{
if(m_block[blockIndex] == IntPtr.Zero)
throw new ArgumentException($"Block index {blockIndex} is a null pointer.");
}
public void RemoveAtSwapBack(int elementIndex)
{
this[elementIndex] = this[Length-1];
--m_lengthInElements;
}
int BlockIndexOfElement(int elementIndex)
{
return elementIndex >> m_log2BlockSizeInElements;
}
public void TrimExcess()
{
for(var blockIndex = BlockIndexOfElement(m_lengthInElements + BlockMask); blockIndex < m_blocks; ++blockIndex)
{
CheckBlockIndex(blockIndex);
if(m_block[blockIndex] != IntPtr.Zero)
{
var blockIntPtr = m_block[blockIndex];
void* blockPointer = (void*)blockIntPtr;
Memory.Unmanaged.Free(blockPointer, m_backingAllocatorHandle);
m_block[blockIndex] = IntPtr.Zero;
}
}
}
}
[BurstCompile]
internal struct AutoFreeAllocator : AllocatorManager.IAllocator
{
ArrayOfArrays<IntPtr> m_allocated;
ArrayOfArrays<IntPtr> m_tofree;
AllocatorManager.AllocatorHandle m_handle;
AllocatorManager.AllocatorHandle m_backingAllocatorHandle;
unsafe public void Update()
{
for(var i = m_tofree.Length; i --> 0;)
for(var j = m_allocated.Length; j --> 0;)
if(m_allocated[j] == m_tofree[i])
{
Memory.Unmanaged.Free((void*)m_tofree[i], m_backingAllocatorHandle);
m_allocated.RemoveAtSwapBack(j);
break;
}
m_tofree.Rewind();
m_allocated.TrimExcess();
}
unsafe public void Initialize(AllocatorManager.AllocatorHandle backingAllocatorHandle)
{
m_allocated = new ArrayOfArrays<IntPtr>(1024 * 1024, backingAllocatorHandle);
m_tofree = new ArrayOfArrays<IntPtr>(128 * 1024, backingAllocatorHandle);
m_backingAllocatorHandle = backingAllocatorHandle;
}
unsafe public void FreeAll()
{
Update();
m_handle.Rewind();
for(var i = 0; i < m_allocated.Length; ++i)
Memory.Unmanaged.Free((void*) m_allocated[i], m_backingAllocatorHandle);
m_allocated.Rewind();
}
/// <summary>
/// Dispose the allocator. This must be called to free the memory blocks that were allocated from the system.
/// </summary>
public void Dispose()
{
FreeAll();
m_tofree.Dispose();
m_allocated.Dispose();
}
/// <summary>
/// The allocator function. It can allocate, deallocate, or reallocate.
/// </summary>
public AllocatorManager.TryFunction Function => Try;
/// <summary>
/// Invoke the allocator function.
/// </summary>
/// <param name="block">The block to allocate, deallocate, or reallocate. See <see cref="AllocatorManager.Try"/></param>
/// <returns>0 if successful. Otherwise, returns the error code from the allocator function.</returns>
public int Try(ref AllocatorManager.Block block)
{
unsafe
{
if (block.Range.Pointer == IntPtr.Zero)
{
if (block.Bytes == 0)
{
return 0;
}
var ptr = (byte*)Memory.Unmanaged.Allocate(block.Bytes, block.Alignment, m_backingAllocatorHandle);
block.Range.Pointer = (IntPtr)ptr;
block.AllocatedItems = block.Range.Items;
m_allocated.LockfreeAdd(block.Range.Pointer);
return 0;
}
if (block.Range.Items == 0)
{
m_tofree.LockfreeAdd(block.Range.Pointer);
block.Range.Pointer = IntPtr.Zero;
block.AllocatedItems = 0;
return 0;
}
return -1;
}
}
[BurstCompile]
[MonoPInvokeCallback(typeof(AllocatorManager.TryFunction))]
internal static int Try(IntPtr state, ref AllocatorManager.Block block)
{
unsafe { return ((AutoFreeAllocator*)state)->Try(ref block); }
}
/// <summary>
/// This allocator.
/// </summary>
/// <value>This allocator.</value>
public AllocatorManager.AllocatorHandle Handle { get { return m_handle; } set { m_handle = value; } }
/// <summary>
/// Cast the Allocator index into Allocator
/// </summary>
public Allocator ToAllocator { get { return m_handle.ToAllocator; } }
/// <summary>
/// Check whether an allocator is a custom allocator
/// </summary>
public bool IsCustomAllocator { get { return m_handle.IsCustomAllocator; } }
/// <summary>
/// Check whether this allocator will automatically dispose allocations.
/// </summary>
/// <remarks>Allocations made by Auto free allocator are automatically disposed.</remarks>
/// <value>Always true</value>
public bool IsAutoDispose { get { return true; } }
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a2aa8b5b9af347fdbe909f0811e6ac90
timeCreated: 1651524384
@@ -0,0 +1,994 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Unity.Mathematics;
namespace Unity.Collections
{
[GenerateTestsForBurstCompatibility]
internal unsafe struct Bitwise
{
internal static int AlignDown(int value, int alignPow2)
{
return value & ~(alignPow2 - 1);
}
internal static long AlignDown(long value, int alignPow2)
{
return value & ~(alignPow2 - 1);
}
internal static int AlignUp(int value, int alignPow2)
{
return AlignDown(value + alignPow2 - 1, alignPow2);
}
internal static long AlignUp(long value, int alignPow2)
{
return AlignDown(value + alignPow2 - 1, alignPow2);
}
internal static int FromBool(bool value)
{
return value ? 1 : 0;
}
// 32-bit uint
internal static uint ExtractBits(uint input, int pos, uint mask)
{
var tmp0 = input >> pos;
return tmp0 & mask;
}
internal static uint ReplaceBits(uint input, int pos, uint mask, uint value)
{
var tmp0 = (value & mask) << pos;
var tmp1 = input & ~(mask << pos);
return tmp0 | tmp1;
}
internal static uint SetBits(uint input, int pos, uint mask, bool value)
{
return ReplaceBits(input, pos, mask, (uint)-FromBool(value));
}
// 64-bit ulong
internal static ulong ExtractBits(ulong input, int pos, ulong mask)
{
var tmp0 = input >> pos;
return tmp0 & mask;
}
internal static ulong ReplaceBits(ulong input, int pos, ulong mask, ulong value)
{
var tmp0 = (value & mask) << pos;
var tmp1 = input & ~(mask << pos);
return tmp0 | tmp1;
}
internal static ulong SetBits(ulong input, int pos, ulong mask, bool value)
{
return ReplaceBits(input, pos, mask, (ulong)-(long)FromBool(value));
}
internal static int lzcnt(byte value)
{
return math.lzcnt((uint)value) - 24;
}
internal static int tzcnt(byte value)
{
return math.min(8, math.tzcnt((uint)value));
}
internal static int lzcnt(ushort value)
{
return math.lzcnt((uint)value) - 16;
}
internal static int tzcnt(ushort value)
{
return math.min(16, math.tzcnt((uint)value));
}
static int FindUlong(ulong* ptr, int beginBit, int endBit, int numBits)
{
var bits = ptr;
var numSteps = (numBits + 63) >> 6;
var numBitsPerStep = 64;
var maxBits = numSteps * numBitsPerStep;
for (int i = beginBit / numBitsPerStep, end = AlignUp(endBit, numBitsPerStep) / numBitsPerStep; i < end; ++i)
{
if (bits[i] != 0)
{
continue;
}
var idx = i * numBitsPerStep;
var num = math.min(idx + numBitsPerStep, endBit) - idx;
if (idx != beginBit)
{
var test = bits[idx / numBitsPerStep - 1];
var newIdx = math.max(idx - math.lzcnt(test), beginBit);
num += idx - newIdx;
idx = newIdx;
}
for (++i; i < end; ++i)
{
if (num >= numBits)
{
return idx;
}
var test = bits[i];
var pos = i * numBitsPerStep;
num += math.min(pos + math.tzcnt(test), endBit) - pos;
if (test != 0)
{
break;
}
}
if (num >= numBits)
{
return idx;
}
}
return endBit;
}
static int FindUint(ulong* ptr, int beginBit, int endBit, int numBits)
{
var bits = (uint*)ptr;
var numSteps = (numBits + 31) >> 5;
var numBitsPerStep = 32;
var maxBits = numSteps * numBitsPerStep;
for (int i = beginBit / numBitsPerStep, end = AlignUp(endBit, numBitsPerStep) / numBitsPerStep; i < end; ++i)
{
if (bits[i] != 0)
{
continue;
}
var idx = i * numBitsPerStep;
var num = math.min(idx + numBitsPerStep, endBit) - idx;
if (idx != beginBit)
{
var test = bits[idx / numBitsPerStep - 1];
var newIdx = math.max(idx - math.lzcnt(test), beginBit);
num += idx - newIdx;
idx = newIdx;
}
for (++i; i < end; ++i)
{
if (num >= numBits)
{
return idx;
}
var test = bits[i];
var pos = i * numBitsPerStep;
num += math.min(pos + math.tzcnt(test), endBit) - pos;
if (test != 0)
{
break;
}
}
if (num >= numBits)
{
return idx;
}
}
return endBit;
}
static int FindUshort(ulong* ptr, int beginBit, int endBit, int numBits)
{
var bits = (ushort*)ptr;
var numSteps = (numBits + 15) >> 4;
var numBitsPerStep = 16;
var maxBits = numSteps * numBitsPerStep;
for (int i = beginBit / numBitsPerStep, end = AlignUp(endBit, numBitsPerStep) / numBitsPerStep; i < end; ++i)
{
if (bits[i] != 0)
{
continue;
}
var idx = i * numBitsPerStep;
var num = math.min(idx + numBitsPerStep, endBit) - idx;
if (idx != beginBit)
{
var test = bits[idx / numBitsPerStep - 1];
var newIdx = math.max(idx - lzcnt(test), beginBit);
num += idx - newIdx;
idx = newIdx;
}
for (++i; i < end; ++i)
{
if (num >= numBits)
{
return idx;
}
var test = bits[i];
var pos = i * numBitsPerStep;
num += math.min(pos + tzcnt(test), endBit) - pos;
if (test != 0)
{
break;
}
}
if (num >= numBits)
{
return idx;
}
}
return endBit;
}
static int FindByte(ulong* ptr, int beginBit, int endBit, int numBits)
{
var bits = (byte*)ptr;
var numSteps = (numBits + 7) >> 3;
var numBitsPerStep = 8;
var maxBits = numSteps * numBitsPerStep;
for (int i = beginBit / numBitsPerStep, end = AlignUp(endBit, numBitsPerStep) / numBitsPerStep; i < end; ++i)
{
if (bits[i] != 0)
{
continue;
}
var idx = i * numBitsPerStep;
var num = math.min(idx + numBitsPerStep, endBit) - idx;
if (idx != beginBit)
{
var test = bits[idx / numBitsPerStep - 1];
var newIdx = math.max(idx - lzcnt(test), beginBit);
num += idx - newIdx;
idx = newIdx;
}
for (++i; i < end; ++i)
{
if (num >= numBits)
{
return idx;
}
var test = bits[i];
var pos = i * numBitsPerStep;
num += math.min(pos + tzcnt(test), endBit) - pos;
if (test != 0)
{
break;
}
}
if (num >= numBits)
{
return idx;
}
}
return endBit;
}
static int FindUpto14bits(ulong* ptr, int beginBit, int endBit, int numBits)
{
var bits = (byte*)ptr;
var bit = (byte)(beginBit & 7);
byte beginMask = (byte)~(0xff << bit);
var lz = 0;
for (int begin = beginBit / 8, end = AlignUp(endBit, 8) / 8, i = begin; i < end; ++i)
{
var test = bits[i];
test |= i == begin ? beginMask : (byte)0;
if (test == 0xff)
{
continue;
}
var pos = i * 8;
var tz = math.min(pos + tzcnt(test), endBit) - pos;
if (lz + tz >= numBits)
{
return pos - lz;
}
lz = lzcnt(test);
var idx = pos + 8;
var newIdx = math.max(idx - lz, beginBit);
lz = math.min(idx, endBit) - newIdx;
if (lz >= numBits)
{
return newIdx;
}
}
return endBit;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static ushort sar(ushort val, int shift)
{
short tmp = (short)val;
tmp >>= shift;
return (ushort)tmp;
}
static int FindUpto6bits(ulong* ptr, int beginBit, int endBit, int numBits)
{
var bits = (byte*)ptr;
byte beginMask = (byte)~(0xff << (beginBit & 7));
byte endMask = (byte)~(0xff >> ((8 - (endBit & 7) & 7)));
var mask = (1 << numBits) - 1;
for (int begin = beginBit / 8, end = AlignUp(endBit, 8) / 8, i = begin; i < end; ++i)
{
ushort test = bits[i];
test |= i == begin ? beginMask : (ushort)0;
test |= i == end - 1 ? endMask : (ushort)0;
test |= 0xff00;
if (test == 0xffff)
{
continue;
}
for (int pos = i * 8, posEnd = pos + 7; pos < posEnd; ++pos)
{
var tz = tzcnt((byte)(test ^ 0xff));
test = sar(test, tz);
pos += tz;
if ((test & mask) == 0)
{
return pos;
}
test = sar(test, 1);
}
}
return endBit;
}
internal static int FindWithBeginEnd(ulong* ptr, int beginBit, int endBit, int numBits)
{
int idx;
if (numBits >= 127)
{
idx = FindUlong(ptr, beginBit, endBit, numBits);
if (idx != endBit)
{
return idx;
}
}
if (numBits >= 63)
{
idx = FindUint(ptr, beginBit, endBit, numBits);
if (idx != endBit)
{
return idx;
}
}
if (numBits >= 128)
{
// early out - no smaller step will find this gap
return int.MaxValue;
}
if (numBits >= 31)
{
idx = FindUshort(ptr, beginBit, endBit, numBits);
if (idx != endBit)
{
return idx;
}
}
if (numBits >= 64)
{
// early out - no smaller step will find this gap
return int.MaxValue;
}
idx = FindByte(ptr, beginBit, endBit, numBits);
if (idx != endBit)
{
return idx;
}
if (numBits < 15)
{
idx = FindUpto14bits(ptr, beginBit, endBit, numBits);
if (idx != endBit)
{
return idx;
}
if (numBits < 7)
{
// The worst case scenario when every byte boundary bit is set (pattern 0x81),
// and we're looking for 6 or less bits. It will rescan byte-by-byte to find
// any inner byte gap.
idx = FindUpto6bits(ptr, beginBit, endBit, numBits);
if (idx != endBit)
{
return idx;
}
}
}
return int.MaxValue;
}
internal static int Find(ulong* ptr, int pos, int count, int numBits) => FindWithBeginEnd(ptr, pos, pos + count, numBits);
internal static bool TestNone(ulong* ptr, int length, int pos, int numBits = 1)
{
var end = math.min(pos + numBits, length);
var idxB = pos >> 6;
var shiftB = pos & 0x3f;
var idxE = (end - 1) >> 6;
var shiftE = end & 0x3f;
var maskB = 0xfffffffffffffffful << shiftB;
var maskE = 0xfffffffffffffffful >> (64 - shiftE);
if (idxB == idxE)
{
var mask = maskB & maskE;
return 0ul == (ptr[idxB] & mask);
}
if (0ul != (ptr[idxB] & maskB))
{
return false;
}
for (var idx = idxB + 1; idx < idxE; ++idx)
{
if (0ul != ptr[idx])
{
return false;
}
}
return 0ul == (ptr[idxE] & maskE);
}
internal static bool TestAny(ulong* ptr, int length, int pos, int numBits = 1)
{
var end = math.min(pos + numBits, length);
var idxB = pos >> 6;
var shiftB = pos & 0x3f;
var idxE = (end - 1) >> 6;
var shiftE = end & 0x3f;
var maskB = 0xfffffffffffffffful << shiftB;
var maskE = 0xfffffffffffffffful >> (64 - shiftE);
if (idxB == idxE)
{
var mask = maskB & maskE;
return 0ul != (ptr[idxB] & mask);
}
if (0ul != (ptr[idxB] & maskB))
{
return true;
}
for (var idx = idxB + 1; idx < idxE; ++idx)
{
if (0ul != ptr[idx])
{
return true;
}
}
return 0ul != (ptr[idxE] & maskE);
}
internal static bool TestAll(ulong* ptr, int length, int pos, int numBits = 1)
{
var end = math.min(pos + numBits, length);
var idxB = pos >> 6;
var shiftB = pos & 0x3f;
var idxE = (end - 1) >> 6;
var shiftE = end & 0x3f;
var maskB = 0xfffffffffffffffful << shiftB;
var maskE = 0xfffffffffffffffful >> (64 - shiftE);
if (idxB == idxE)
{
var mask = maskB & maskE;
return mask == (ptr[idxB] & mask);
}
if (maskB != (ptr[idxB] & maskB))
{
return false;
}
for (var idx = idxB + 1; idx < idxE; ++idx)
{
if (0xfffffffffffffffful != ptr[idx])
{
return false;
}
}
return maskE == (ptr[idxE] & maskE);
}
internal static int CountBits(ulong* ptr, int length, int pos, int numBits = 1)
{
var end = math.min(pos + numBits, length);
var idxB = pos >> 6;
var shiftB = pos & 0x3f;
var idxE = (end - 1) >> 6;
var shiftE = end & 0x3f;
var maskB = 0xfffffffffffffffful << shiftB;
var maskE = 0xfffffffffffffffful >> (64 - shiftE);
if (idxB == idxE)
{
var mask = maskB & maskE;
return math.countbits(ptr[idxB] & mask);
}
var count = math.countbits(ptr[idxB] & maskB);
for (var idx = idxB + 1; idx < idxE; ++idx)
{
count += math.countbits(ptr[idx]);
}
count += math.countbits(ptr[idxE] & maskE);
return count;
}
internal static bool IsSet(ulong* ptr, int pos)
{
var idx = pos >> 6;
var shift = pos & 0x3f;
var mask = 1ul << shift;
return 0ul != (ptr[idx] & mask);
}
internal static ulong GetBits(ulong* ptr, int length, int pos, int numBits = 1)
{
var idxB = pos >> 6;
var shiftB = pos & 0x3f;
if (shiftB + numBits <= 64)
{
var mask = 0xfffffffffffffffful >> (64 - numBits);
return Bitwise.ExtractBits(ptr[idxB], shiftB, mask);
}
var end = math.min(pos + numBits, length);
var idxE = (end - 1) >> 6;
var shiftE = end & 0x3f;
var maskB = 0xfffffffffffffffful >> shiftB;
ulong valueB = Bitwise.ExtractBits(ptr[idxB], shiftB, maskB);
var maskE = 0xfffffffffffffffful >> (64 - shiftE);
ulong valueE = Bitwise.ExtractBits(ptr[idxE], 0, maskE);
return (valueE << (64 - shiftB)) | valueB;
}
}
/// <summary>
/// A 32-bit array of bits.
/// </summary>
/// <remarks>
/// Stack allocated, so it does not require thread safety checks or disposal.
/// </remarks>
[DebuggerTypeProxy(typeof(BitField32DebugView))]
[GenerateTestsForBurstCompatibility]
public struct BitField32
{
/// <summary>
/// The 32 bits, stored as a uint.
/// </summary>
/// <value>The 32 bits, stored as a uint.</value>
public uint Value;
/// <summary>
/// Initializes and returns an instance of BitField32.
/// </summary>
/// <param name="initialValue">Initial value of the bit field. Default is 0.</param>
public BitField32(uint initialValue = 0u)
{
Value = initialValue;
}
/// <summary>
/// Clears all the bits to 0.
/// </summary>
public void Clear()
{
Value = 0u;
}
/// <summary>
/// Sets a single bit to 1 or 0.
/// </summary>
/// <param name="pos">Position in this bit field to set (must be 0-31).</param>
/// <param name="value">If true, sets the bit to 1. If false, sets the bit to 0.</param>
/// <exception cref="ArgumentException">Thrown if `pos`is out of range.</exception>
public void SetBits(int pos, bool value)
{
CheckArgs(pos, 1);
Value = Bitwise.SetBits(Value, pos, 1, value);
}
/// <summary>
/// Sets one or more contiguous bits to 1 or 0.
/// </summary>
/// <param name="pos">Position in the bit field of the first bit to set (must be 0-31).</param>
/// <param name="value">If true, sets the bits to 1. If false, sets the bits to 0.</param>
/// <param name="numBits">Number of bits to set (must be 1-32).</param>
/// <exception cref="ArgumentException">Thrown if `pos` or `numBits` are out of bounds or if `pos + numBits` exceeds 32.</exception>
public void SetBits(int pos, bool value, int numBits)
{
CheckArgs(pos, numBits);
var mask = 0xffffffffu >> (32 - numBits);
Value = Bitwise.SetBits(Value, pos, mask, value);
}
/// <summary>
/// Returns one or more contiguous bits from the bit field as the lower bits of a uint.
/// </summary>
/// <param name="pos">Position in the bit field of the first bit to get (must be 0-31).</param>
/// <param name="numBits">Number of bits to get (must be 1-32).</param>
/// <exception cref="ArgumentException">Thrown if `pos` or `numBits` are out of bounds or if `pos + numBits` exceeds 32.</exception>
/// <returns>The requested range of bits from the bit field stored in the least-significant bits of a uint. All other bits of the uint will be 0.</returns>
public uint GetBits(int pos, int numBits = 1)
{
CheckArgs(pos, numBits);
var mask = 0xffffffffu >> (32 - numBits);
return Bitwise.ExtractBits(Value, pos, mask);
}
/// <summary>
/// Returns true if the bit at a position is 1.
/// </summary>
/// <param name="pos">Position in the bit field (must be 0-31).</param>
/// <returns>True if the bit at the position is 1.</returns>
public bool IsSet(int pos)
{
return 0 != GetBits(pos);
}
/// <summary>
/// Returns true if none of the bits in a contiguous range are 1.
/// </summary>
/// <param name="pos">Position in the bit field (must be 0-31).</param>
/// <param name="numBits">Number of bits to test (must be 1-32).</param>
/// <exception cref="ArgumentException">Thrown if `pos` or `numBits` are out of bounds or if `pos + numBits` exceeds 32.</exception>
/// <returns>True if none of the bits in the contiguous range are 1.</returns>
public bool TestNone(int pos, int numBits = 1)
{
return 0u == GetBits(pos, numBits);
}
/// <summary>
/// Returns true if any of the bits in a contiguous range are 1.
/// </summary>
/// <param name="pos">Position in the bit field (must be 0-31).</param>
/// <param name="numBits">Number of bits to test (must be 1-32).</param>
/// <exception cref="ArgumentException">Thrown if `pos` or `numBits` are out of bounds or if `pos + numBits` exceeds 32.</exception>
/// <returns>True if at least one bit in the contiguous range is 1.</returns>
public bool TestAny(int pos, int numBits = 1)
{
return 0u != GetBits(pos, numBits);
}
/// <summary>
/// Returns true if all of the bits in a contiguous range are 1.
/// </summary>
/// <param name="pos">Position in the bit field (must be 0-31).</param>
/// <param name="numBits">Number of bits to test (must be 1-32).</param>
/// <exception cref="ArgumentException">Thrown if `pos` or `numBits` are out of bounds or if `pos + numBits` exceeds 32.</exception>
/// <returns>True if all bits in the contiguous range are 1.</returns>
public bool TestAll(int pos, int numBits = 1)
{
CheckArgs(pos, numBits);
var mask = 0xffffffffu >> (32 - numBits);
return mask == Bitwise.ExtractBits(Value, pos, mask);
}
/// <summary>
/// Returns the number of bits that are 1.
/// </summary>
/// <returns>The number of bits that are 1.</returns>
public int CountBits()
{
return math.countbits(Value);
}
/// <summary>
/// Returns the number of leading zeroes.
/// </summary>
/// <returns>The number of leading zeros.</returns>
public int CountLeadingZeros()
{
return math.lzcnt(Value);
}
/// <summary>
/// Returns the number of trailing zeros.
/// </summary>
/// <returns>The number of trailing zeros.</returns>
public int CountTrailingZeros()
{
return math.tzcnt(Value);
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void CheckArgs(int pos, int numBits)
{
if (pos > 31
|| numBits == 0
|| numBits > 32
|| pos + numBits > 32)
{
throw new ArgumentException($"BitField32 invalid arguments: pos {pos} (must be 0-31), numBits {numBits} (must be 1-32).");
}
}
}
sealed class BitField32DebugView
{
BitField32 BitField;
public BitField32DebugView(BitField32 bitfield)
{
BitField = bitfield;
}
public bool[] Bits
{
get
{
var array = new bool[32];
for (int i = 0; i < 32; ++i)
{
array[i] = BitField.IsSet(i);
}
return array;
}
}
}
/// <summary>
/// A 64-bit array of bits.
/// </summary>
/// <remarks>
/// Stack allocated, so it does not require thread safety checks or disposal.
/// </remarks>
[DebuggerTypeProxy(typeof(BitField64DebugView))]
[GenerateTestsForBurstCompatibility]
public struct BitField64
{
/// <summary>
/// The 64 bits, stored as a ulong.
/// </summary>
/// <value>The 64 bits, stored as a uint.</value>
public ulong Value;
/// <summary>
/// Initializes and returns an instance of BitField64.
/// </summary>
/// <param name="initialValue">Initial value of the bit field. Default is 0.</param>
public BitField64(ulong initialValue = 0ul)
{
Value = initialValue;
}
/// <summary>
/// Clears all bits to 0.
/// </summary>
public void Clear()
{
Value = 0ul;
}
/// <summary>
/// Sets a single bit to 1 or 0.
/// </summary>
/// <param name="pos">Position in this bit field to set (must be 0-63).</param>
/// <param name="value">If true, sets the bit to 1. If false, sets the bit to 0.</param>
/// <exception cref="ArgumentException">Thrown if `pos`is out of range.</exception>
public void SetBits(int pos, bool value)
{
CheckArgs(pos, 1);
Value = Bitwise.SetBits(Value, pos, 1, value);
}
/// <summary>
/// Sets one or more contiguous bits to 1 or 0.
/// </summary>
/// <param name="pos">Position in the bit field of the first bit to set (must be 0-63).</param>
/// <param name="value">If true, sets the bits to 1. If false, sets the bits to 0.</param>
/// <param name="numBits">Number of bits to set (must be 1-64).</param>
/// <exception cref="ArgumentException">Thrown if `pos` or `numBits` are out of bounds or if `pos + numBits` exceeds 64.</exception>
public void SetBits(int pos, bool value, int numBits = 1)
{
CheckArgs(pos, numBits);
var mask = 0xfffffffffffffffful >> (64 - numBits);
Value = Bitwise.SetBits(Value, pos, mask, value);
}
/// <summary>
/// Returns one or more contiguous bits from the bit field as the lower bits of a ulong.
/// </summary>
/// <param name="pos">Position in the bit field of the first bit to get (must be 0-63).</param>
/// <param name="numBits">Number of bits to get (must be 1-64).</param>
/// <exception cref="ArgumentException">Thrown if `pos` or `numBits` are out of bounds or if `pos + numBits` exceeds 64.</exception>
/// <returns>The requested range of bits from the bit field stored in the least-significant bits of a ulong. All other bits of the ulong will be 0.</returns>
public ulong GetBits(int pos, int numBits = 1)
{
CheckArgs(pos, numBits);
var mask = 0xfffffffffffffffful >> (64 - numBits);
return Bitwise.ExtractBits(Value, pos, mask);
}
/// <summary>
/// Returns true if the bit at a position is 1.
/// </summary>
/// <param name="pos">Position in the bit field (must be 0-63).</param>
/// <returns>True if the bit at the position is 1.</returns>
public bool IsSet(int pos)
{
return 0ul != GetBits(pos);
}
/// <summary>
/// Returns true if none of the bits in a contiguous range are 1.
/// </summary>
/// <param name="pos">Position in the bit field (must be 0-63).</param>
/// <param name="numBits">Number of bits to test (must be 1-64).</param>
/// <exception cref="ArgumentException">Thrown if `pos` or `numBits` are out of bounds or if `pos + numBits` exceeds 64.</exception>
/// <returns>True if none of the bits in the contiguous range are 1.</returns>
public bool TestNone(int pos, int numBits = 1)
{
return 0ul == GetBits(pos, numBits);
}
/// <summary>
/// Returns true if any of the bits in a contiguous range are 1.
/// </summary>
/// <param name="pos">Position in the bit field (must be 0-63).</param>
/// <param name="numBits">Number of bits to test (must be 1-64).</param>
/// <exception cref="ArgumentException">Thrown if `pos` or `numBits` are out of bounds or if `pos + numBits` exceeds 64.</exception>
/// <returns>True if at least one bit in the contiguous range is 1.</returns>
public bool TestAny(int pos, int numBits = 1)
{
return 0ul != GetBits(pos, numBits);
}
/// <summary>
/// Returns true if all of the bits in a contiguous range are 1.
/// </summary>
/// <param name="pos">Position in the bit field (must be 0-63).</param>
/// <param name="numBits">Number of bits to test (must be 1-64).</param>
/// <exception cref="ArgumentException">Thrown if `pos` or `numBits` are out of bounds or if `pos + numBits` exceeds 64.</exception>
/// <returns>True if all bits in the contiguous range are 1.</returns>
public bool TestAll(int pos, int numBits = 1)
{
CheckArgs(pos, numBits);
var mask = 0xfffffffffffffffful >> (64 - numBits);
return mask == Bitwise.ExtractBits(Value, pos, mask);
}
/// <summary>
/// Returns the number of bits that are 1.
/// </summary>
/// <returns>The number of bits that are 1.</returns>
public int CountBits()
{
return math.countbits(Value);
}
/// <summary>
/// Returns the number of leading zeroes.
/// </summary>
/// <returns>The number of leading zeros.</returns>
public int CountLeadingZeros()
{
return math.lzcnt(Value);
}
/// <summary>
/// Returns the number of trailing zeros.
/// </summary>
/// <returns>The number of trailing zeros.</returns>
public int CountTrailingZeros()
{
return math.tzcnt(Value);
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void CheckArgs(int pos, int numBits)
{
if (pos > 63
|| numBits == 0
|| numBits > 64
|| pos + numBits > 64)
{
throw new ArgumentException($"BitField32 invalid arguments: pos {pos} (must be 0-63), numBits {numBits} (must be 1-64).");
}
}
}
sealed class BitField64DebugView
{
BitField64 Data;
public BitField64DebugView(BitField64 data)
{
Data = data;
}
public bool[] Bits
{
get
{
var array = new bool[64];
for (int i = 0; i < 64; ++i)
{
array[i] = Data.IsSet(i);
}
return array;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ec1f6f558fc0b9a4fac43b21ec79cd5a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,727 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Burst;
using Unity.Burst.CompilerServices;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
using Unity.Mathematics;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Unity.Collections
{
/// <summary>
/// For scheduling release of unmanaged resources.
/// </summary>
public interface INativeDisposable : IDisposable
{
/// <summary>
/// Creates and schedules a job that will release all resources (memory and safety handles) of this collection.
/// </summary>
/// <param name="inputDeps">A job handle which the newly scheduled job will depend upon.</param>
/// <returns>The handle of a new job that will release all resources (memory and safety handles) of this collection.</returns>
JobHandle Dispose(JobHandle inputDeps);
}
/// <summary>
/// Provides helper methods for collections.
/// </summary>
[GenerateTestsForBurstCompatibility]
public static class CollectionHelper
{
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
internal static void CheckAllocator(AllocatorManager.AllocatorHandle allocator)
{
if (!ShouldDeallocate(allocator))
throw new ArgumentException($"Allocator {allocator} must not be None or Invalid");
}
/// <summary>
/// The size in bytes of the current platform's L1 cache lines.
/// </summary>
/// <value>The size in bytes of the current platform's L1 cache lines.</value>
public const int CacheLineSize = JobsUtility.CacheLineSize;
[StructLayout(LayoutKind.Explicit)]
internal struct LongDoubleUnion
{
[FieldOffset(0)]
internal long longValue;
[FieldOffset(0)]
internal double doubleValue;
}
/// <summary>
/// Returns the binary logarithm of the `value`, but the result is rounded down to the nearest integer.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The binary logarithm of the `value`, but the result is rounded down to the nearest integer.</returns>
public static int Log2Floor(int value)
{
return 31 - math.lzcnt((uint)value);
}
/// <summary>
/// Returns the binary logarithm of the `value`, but the result is rounded up to the nearest integer.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The binary logarithm of the `value`, but the result is rounded up to the nearest integer.</returns>
public static int Log2Ceil(int value)
{
return 32 - math.lzcnt((uint)value - 1);
}
/// <summary>
/// Returns an allocation size in bytes that factors in alignment.
/// </summary>
/// <example><code>
/// // 55 aligned to 16 is 64.
/// int size = CollectionHelper.Align(55, 16);
/// </code></example>
/// <param name="size">The size to align.</param>
/// <param name="alignmentPowerOfTwo">A non-zero, positive power of two.</param>
/// <returns>The smallest integer that is greater than or equal to<paramref name="size"/> and is a multiple of <paramref name="alignmentPowerOfTwo"/>.</returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="alignmentPowerOfTwo"/> is not a non-zero, positive power of two.</exception>
public static int Align(int size, int alignmentPowerOfTwo)
{
if (alignmentPowerOfTwo == 0)
return size;
CheckIntPositivePowerOfTwo(alignmentPowerOfTwo);
return (size + alignmentPowerOfTwo - 1) & ~(alignmentPowerOfTwo - 1);
}
/// <summary>
/// Returns an allocation size in bytes that factors in alignment.
/// </summary>
/// <example><code>
/// // 55 aligned to 16 is 64.
/// long size = CollectionHelper.Align(55, 16);
/// </code></example>
/// <param name="size">The size to align.</param>
/// <param name="alignmentPowerOfTwo">A non-zero, positive power of two.</param>
/// <returns>The smallest integer that is greater than or equal to<paramref name="size"/> and is a multiple of <paramref name="alignmentPowerOfTwo"/>.</returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="alignmentPowerOfTwo"/> is not a non-zero, positive power of two.</exception>
public static long Align(long size, int alignmentPowerOfTwo)
{
if (alignmentPowerOfTwo == 0)
return size;
CheckIntPositivePowerOfTwo(alignmentPowerOfTwo);
return (size + alignmentPowerOfTwo - 1) & ~(alignmentPowerOfTwo - 1);
}
/// <summary>
/// Returns an allocation size in bytes that factors in alignment.
/// </summary>
/// <example><code>
/// // 55 aligned to 16 is 64.
/// ulong size = CollectionHelper.Align(55, 16);
/// </code></example>
/// <param name="size">The size to align.</param>
/// <param name="alignmentPowerOfTwo">A non-zero, positive power of two.</param>
/// <returns>The smallest integer that is greater than or equal to <paramref name="size"/> and is a multiple of <paramref name="alignmentPowerOfTwo"/>.</returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="alignmentPowerOfTwo"/> is not a non-zero, positive power of two.</exception>
public static ulong Align(ulong size, ulong alignmentPowerOfTwo)
{
if (alignmentPowerOfTwo == 0)
return size;
CheckUlongPositivePowerOfTwo(alignmentPowerOfTwo);
return (size + alignmentPowerOfTwo - 1) & ~(alignmentPowerOfTwo - 1);
}
/// <summary>
/// Returns a pointer whose value is rounded up to an address aligned to the provided alignment.
/// </summary>
/// <example><code>
/// // 0x80BD5162 aligned to 8 is 0x80BD5168
/// void* alignedPtr = CollectionHelper.Align(55, 16);
/// </code></example>
/// <param name="ptr">The pointer to align.</param>
/// <param name="alignmentPowerOfTwo">A non-zero, positive power of two.</param>
/// <returns>The smallest address that is greater than or equal to <paramref name="ptr"/> and is a multiple of <paramref name="alignmentPowerOfTwo"/>.</returns>
/// <exception cref="ArgumentException">Thrown if <paramref name="alignmentPowerOfTwo"/> is not a non-zero, positive power of two.</exception>
internal static unsafe void* AlignPointer(void* ptr, int alignmentPowerOfTwo)
{
if (alignmentPowerOfTwo == 0)
return ptr;
CheckIntPositivePowerOfTwo(alignmentPowerOfTwo);
var ptrAsNuint = (nuint)ptr;
var alignmentAsNuint = (nuint)alignmentPowerOfTwo;
return (void*)( (ptrAsNuint + alignmentAsNuint - 1) & ~(alignmentAsNuint - 1) );
}
/// <summary>
/// Returns true if the address represented by the pointer has a given alignment.
/// </summary>
/// <param name="p">The pointer.</param>
/// <param name="alignmentPowerOfTwo">A non-zero, positive power of two.</param>
/// <returns>True if the address is a multiple of `alignmentPowerOfTwo`.</returns>
/// <exception cref="ArgumentException">Thrown if `alignmentPowerOfTwo` is not a non-zero, positive power of two.</exception>
public static unsafe bool IsAligned(void* p, int alignmentPowerOfTwo)
{
CheckIntPositivePowerOfTwo(alignmentPowerOfTwo);
return ((ulong)p & ((ulong)alignmentPowerOfTwo - 1)) == 0;
}
/// <summary>
/// Returns true if an offset has a given alignment.
/// </summary>
/// <param name="offset">An offset</param>
/// <param name="alignmentPowerOfTwo">A non-zero, positive power of two.</param>
/// <returns>True if the offset is a multiple of `alignmentPowerOfTwo`.</returns>
/// <exception cref="ArgumentException">Thrown if `alignmentPowerOfTwo` is not a non-zero, positive power of two.</exception>
public static bool IsAligned(ulong offset, int alignmentPowerOfTwo)
{
CheckIntPositivePowerOfTwo(alignmentPowerOfTwo);
return (offset & ((ulong)alignmentPowerOfTwo - 1)) == 0;
}
/// <summary>
/// Returns true if a positive value is a non-zero power of two.
/// </summary>
/// <remarks>Result is invalid if `value &lt; 0`.</remarks>
/// <param name="value">A positive value.</param>
/// <returns>True if the value is a non-zero, positive power of two.</returns>
public static bool IsPowerOfTwo(int value)
{
return (value & (value - 1)) == 0;
}
/// <summary>
/// Returns a (non-cryptographic) hash of a memory block.
/// </summary>
/// <remarks>The hash function used is [djb2](http://web.archive.org/web/20190508211657/http://www.cse.yorku.ca/~oz/hash.html).</remarks>
/// <param name="ptr">A buffer.</param>
/// <param name="bytes">The number of bytes to hash.</param>
/// <returns>A hash of the bytes.</returns>
public static unsafe uint Hash(void* ptr, int bytes)
{
// djb2 - Dan Bernstein hash function
// http://web.archive.org/web/20190508211657/http://www.cse.yorku.ca/~oz/hash.html
byte* str = (byte*)ptr;
ulong hash = 5381;
while (bytes > 0)
{
ulong c = str[--bytes];
hash = ((hash << 5) + hash) + c;
}
return (uint)hash;
}
[ExcludeFromBurstCompatTesting("Used only for debugging, and uses managed strings")]
internal static void WriteLayout(Type type)
{
Console.WriteLine($" Offset | Bytes | Name Layout: {0}", type.Name);
var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var field in fields)
{
Console.WriteLine(" {0, 6} | {1, 6} | {2}"
, Marshal.OffsetOf(type, field.Name)
, Marshal.SizeOf(field.FieldType)
, field.Name
);
}
}
internal static bool ShouldDeallocate(AllocatorManager.AllocatorHandle allocator)
{
// Allocator.Invalid == container is not initialized.
// Allocator.None == container is initialized, but container doesn't own data.
return allocator.ToAllocator > Allocator.None;
}
/// <summary>
/// Tell Burst that an integer can be assumed to map to an always positive value.
/// </summary>
/// <param name="value">The integer that is always positive.</param>
/// <returns>Returns `x`, but allows the compiler to assume it is always positive.</returns>
[return: AssumeRange(0, int.MaxValue)]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int AssumePositive(int value)
{
return value;
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
[GenerateTestsForBurstCompatibility(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS", GenericTypeArguments = new[] { typeof(NativeArray<int>) })]
internal static void CheckIsUnmanaged<T>()
{
if (!UnsafeUtility.IsUnmanaged<T>())
{
throw new ArgumentException($"{typeof(T)} used in native collection is not blittable or not primitive");
}
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
[GenerateTestsForBurstCompatibility(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS", GenericTypeArguments = new[] { typeof(NativeArray<int>) })]
internal static void InitNativeContainer<T>(AtomicSafetyHandle handle)
{
if (UnsafeUtility.IsNativeContainerType<T>())
AtomicSafetyHandle.SetNestedContainer(handle, true);
}
#endif
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
internal static void CheckIntPositivePowerOfTwo(int value)
{
var valid = (value > 0) && ((value & (value - 1)) == 0);
if (!valid)
{
throw new ArgumentException($"Alignment requested: {value} is not a non-zero, positive power of two.");
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
internal static void CheckUlongPositivePowerOfTwo(ulong value)
{
var valid = (value > 0) && ((value & (value - 1)) == 0);
if (!valid)
{
throw new ArgumentException($"Alignment requested: {value} is not a non-zero, positive power of two.");
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void CheckIndexInRange(int index, int length)
{
// This checks both < 0 and >= Length with one comparison
if ((uint)index >= (uint)length)
throw new IndexOutOfRangeException($"Index {index} is out of range in container of '{length}' Length.");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
internal static void CheckCapacityInRange(int capacity, int maxCapacity, int length)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException($"Capacity {capacity} must be positive.");
if (capacity > maxCapacity)
throw new ArgumentException($"Capacity {capacity} value too large. Maximum capacity is {maxCapacity}.");
if (capacity < length)
throw new ArgumentOutOfRangeException($"Capacity {capacity} is out of range in container of '{length}' Length.");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
internal static void CheckCapacityInRange(int capacity, int length)
{
CheckCapacityInRange(capacity, int.MaxValue, length);
}
/// <summary>
/// Create a NativeArray, using a provided allocator that implements IAllocator.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <typeparam name="U">The type of allocator.</typeparam>
/// <param name="length">The number of elements to allocate.</param>
/// <param name="allocator">The allocator to use.</param>
/// <param name="options">Options for allocation, such as whether to clear the memory.</param>
/// <returns>Returns the NativeArray that was created.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(AllocatorManager.AllocatorHandle) })]
public static NativeArray<T> CreateNativeArray<T, U>(int length, ref U allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
where T : unmanaged
where U : unmanaged, AllocatorManager.IAllocator
{
NativeArray<T> nativeArray;
if (!allocator.IsCustomAllocator)
{
nativeArray = new NativeArray<T>(length, allocator.ToAllocator, options);
}
else
{
nativeArray = new NativeArray<T>();
nativeArray.Initialize(length, ref allocator, options);
}
return nativeArray;
}
/// <summary>
/// Create a NativeArray, using a provided AllocatorHandle.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="length">The number of elements to allocate.</param>
/// <param name="allocator">The AllocatorHandle to use.</param>
/// <param name="options">Options for allocation, such as whether to clear the memory.</param>
/// <returns>Returns the NativeArray that was created.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public static NativeArray<T> CreateNativeArray<T>(int length, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
where T : unmanaged
{
NativeArray<T> nativeArray;
if(!AllocatorManager.IsCustomAllocator(allocator))
{
nativeArray = new NativeArray<T>(length, allocator.ToAllocator, options);
}
else
{
nativeArray = new NativeArray<T>();
nativeArray.Initialize(length, allocator, options);
}
return nativeArray;
}
/// <summary>
/// Create a NativeArray from another NativeArray, using a provided AllocatorHandle.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="array">The NativeArray to make a copy of.</param>
/// <param name="allocator">The AllocatorHandle to use.</param>
/// <returns>Returns the NativeArray that was created.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public static NativeArray<T> CreateNativeArray<T>(NativeArray<T> array, AllocatorManager.AllocatorHandle allocator)
where T : unmanaged
{
NativeArray<T> nativeArray;
if (!AllocatorManager.IsCustomAllocator(allocator))
{
nativeArray = new NativeArray<T>(array, allocator.ToAllocator);
}
else
{
nativeArray = new NativeArray<T>();
nativeArray.Initialize(array.Length, allocator);
nativeArray.CopyFrom(array);
}
return nativeArray;
}
/// <summary>
/// Create a NativeArray from a managed array, using a provided AllocatorHandle.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="array">The managed array to make a copy of.</param>
/// <param name="allocator">The AllocatorHandle to use.</param>
/// <returns>Returns the NativeArray that was created.</returns>
[ExcludeFromBurstCompatTesting("Managed array")]
public static NativeArray<T> CreateNativeArray<T>(T[] array, AllocatorManager.AllocatorHandle allocator)
where T : unmanaged
{
NativeArray<T> nativeArray;
if (!AllocatorManager.IsCustomAllocator(allocator))
{
nativeArray = new NativeArray<T>(array, allocator.ToAllocator);
}
else
{
nativeArray = new NativeArray<T>();
nativeArray.Initialize(array.Length, allocator);
nativeArray.CopyFrom(array);
}
return nativeArray;
}
/// <summary>
/// Create a NativeArray from a managed array, using a provided Allocator.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <typeparam name="U">The type of allocator.</typeparam>
/// <param name="array">The managed array to make a copy of.</param>
/// <param name="allocator">The Allocator to use.</param>
/// <returns>Returns the NativeArray that was created.</returns>
[ExcludeFromBurstCompatTesting("Managed array")]
public static NativeArray<T> CreateNativeArray<T, U>(T[] array, ref U allocator)
where T : unmanaged
where U : unmanaged, AllocatorManager.IAllocator
{
NativeArray<T> nativeArray;
if (!allocator.IsCustomAllocator)
{
nativeArray = new NativeArray<T>(array, allocator.ToAllocator);
}
else
{
nativeArray = new NativeArray<T>();
nativeArray.Initialize(array.Length, ref allocator);
nativeArray.CopyFrom(array);
}
return nativeArray;
}
/// <summary>
/// Dispose a NativeArray from an AllocatorHandle where it is allocated.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="nativeArray">The NativeArray to make a copy of.</param>
/// <param name="allocator">The AllocatorHandle used to allocate the NativeArray.</param>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public static void DisposeNativeArray<T>(NativeArray<T> nativeArray, AllocatorManager.AllocatorHandle allocator)
where T : unmanaged
{
nativeArray.DisposeCheckAllocator();
}
/// <summary>
/// Dispose a NativeArray from an AllocatorHandle where it is allocated.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="nativeArray">The NativeArray to be disposed.</param>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public static void Dispose<T>(NativeArray<T> nativeArray)
where T : unmanaged
{
nativeArray.DisposeCheckAllocator();
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void CheckConvertArguments<T>(int length) where T : unmanaged
{
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), "Length must be >= 0");
if (!UnsafeUtility.IsUnmanaged<T>())
{
throw new InvalidOperationException(
$"{typeof(T)} used in NativeArray<{typeof(T)}> must be unmanaged (contain no managed types).");
}
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
static void InitNestedNativeContainer<T>(AtomicSafetyHandle handle)
where T : unmanaged
{
if (UnsafeUtility.IsNativeContainerType<T>())
{
AtomicSafetyHandle.SetNestedContainer(handle, true);
}
}
#endif
/// <summary>
/// Convert existing data into a NativeArray.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="dataPointer">Pointer to the data to be converted.</param>
/// <param name="length">The count of elements.</param>
/// <param name="allocator">The Allocator to use.</param>
/// <param name="setTempMemoryHandle">Use temporary memory atomic safety handle.</param>
/// <returns>Returns the NativeArray that was created.</returns>
/// <remarks>The caller is still the owner of the data.</remarks>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public static unsafe NativeArray<T> ConvertExistingDataToNativeArray<T>(void* dataPointer, int length, AllocatorManager.AllocatorHandle allocator, bool setTempMemoryHandle = false)
where T : unmanaged
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
CheckConvertArguments<T>(length);
#endif
NativeArray<T> nativeArray = default;
nativeArray.m_Buffer = dataPointer;
nativeArray.m_Length = length;
if (!allocator.IsCustomAllocator)
{
nativeArray.m_AllocatorLabel = allocator.ToAllocator;
}
else
{
nativeArray.m_AllocatorLabel = Allocator.None;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
nativeArray.m_MinIndex = 0;
nativeArray.m_MaxIndex = length - 1;
if (setTempMemoryHandle)
{
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nativeArray, AtomicSafetyHandle.GetTempMemoryHandle());
}
#endif
return nativeArray;
}
/// <summary>
/// Convert NativeList into a NativeArray.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="nativeList">NativeList to be converted.</param>
/// <param name="length">The count of elements.</param>
/// <param name="allocator">The Allocator to use.</param>
/// <returns>Returns the NativeArray that was created.</returns>
/// <remarks>There is a caveat if users would like to transfer memory ownership from the NativeList to the converted NativeArray.
/// NativeList implementation includes two memory allocations, one holds its header, another holds the list data.
/// After convertion, the converted NativeArray holds the list data and dispose the array only free the list data.
/// Users need to manually free the list header to avoid memory leaks, for example after convertion call,
/// AllocatorManager.Free(allocator, nativeList.m_ListData); </remarks>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public static unsafe NativeArray<T> ConvertExistingNativeListToNativeArray<T>(ref NativeList<T> nativeList, int length, AllocatorManager.AllocatorHandle allocator)
where T : unmanaged
{
NativeArray<T> nativeArray = ConvertExistingDataToNativeArray<T>(nativeList.GetUnsafePtr(), length, allocator);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var safetyHandle = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref nativeList);
NativeArrayUnsafeUtility.SetAtomicSafetyHandle<T>(ref nativeArray, safetyHandle);
InitNestedNativeContainer<T>(nativeArray.m_Safety);
#endif
return nativeArray;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) }, RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS", CompileTarget = GenerateTestsForBurstCompatibilityAttribute.BurstCompatibleCompileTarget.Editor)]
internal static AtomicSafetyHandle GetNativeArraySafetyHandle<T>(ref NativeArray<T> nativeArray)
where T : unmanaged
{
return nativeArray.m_Safety;
}
#endif
/// <summary>
/// Create a NativeParallelMultiHashMap from a managed array, using a provided Allocator.
/// </summary>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <typeparam name="U">The type of allocator.</typeparam>
/// <param name="length">The desired capacity of the NativeParallelMultiHashMap.</param>
/// <param name="allocator">The Allocator to use.</param>
/// <returns>Returns the NativeParallelMultiHashMap that was created.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int), typeof(AllocatorManager.AllocatorHandle) })]
public static NativeParallelMultiHashMap<TKey, TValue> CreateNativeParallelMultiHashMap<TKey, TValue, U>(int length, ref U allocator)
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
where U : unmanaged, AllocatorManager.IAllocator
{
var container = new NativeParallelMultiHashMap<TKey, TValue>();
container.Initialize(length, ref allocator);
return container;
}
/// <summary>
/// Empty job type used for Burst compilation testing
/// </summary>
[BurstCompile]
public struct DummyJob : IJob
{
/// <summary>
/// Empty job execute function used for Burst compilation testing
/// </summary>
public void Execute()
{
}
}
/// <summary>
/// Checks that reflection data was properly registered for a job.
/// </summary>
/// <remarks>This should be called before instantiating JobsUtility.JobScheduleParameters in order to report to the user if they need to take action.</remarks>
/// <param name="reflectionData">The reflection data pointer.</param>
/// <typeparam name="T">Job type</typeparam>
[GenerateTestsForBurstCompatibility(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS",
GenericTypeArguments = new[] { typeof(DummyJob) })]
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
public static void CheckReflectionDataCorrect<T>(IntPtr reflectionData)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
bool burstCompiled = true;
CheckReflectionDataCorrectInternal<T>(reflectionData, ref burstCompiled);
if (burstCompiled && reflectionData == IntPtr.Zero)
throw new InvalidOperationException("Reflection data was not set up by an Initialize() call. For generic job types, please include [assembly: RegisterGenericJobType(typeof(MyJob<MyJobSpecialization>))] in your source file.");
#endif
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
/// <summary>
/// Creates a new AtomicSafetyHandle that is valid until [[CollectionHelper.DisposeSafetyHandle]] is called.
/// </summary>
/// <param name="allocator">The AllocatorHandle to use.</param>
/// <returns>Safety handle.</returns>
[GenerateTestsForBurstCompatibility(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS")]
public static AtomicSafetyHandle CreateSafetyHandle(AllocatorManager.AllocatorHandle allocator)
{
if (allocator.IsCustomAllocator)
{
return AtomicSafetyHandle.Create();
}
return (allocator.ToAllocator == Allocator.Temp) ? AtomicSafetyHandle.GetTempMemoryHandle() : AtomicSafetyHandle.Create();
}
/// <summary>
/// Disposes a previously created AtomicSafetyHandle.
/// </summary>
/// <param name="handle">Safety handle.</param>
[GenerateTestsForBurstCompatibility(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS")]
public static void DisposeSafetyHandle(ref AtomicSafetyHandle handle)
{
AtomicSafetyHandle.CheckDeallocateAndThrow(handle);
// If the safety handle is for a temp allocation, create a new safety handle for this instance which can be marked as invalid
// Setting it to new AtomicSafetyHandle is not enough since the handle needs a valid node pointer in order to give the correct errors
if (AtomicSafetyHandle.IsTempMemoryHandle(handle))
{
int staticSafetyId = handle.staticSafetyId;
handle = AtomicSafetyHandle.Create();
handle.staticSafetyId = staticSafetyId;
}
AtomicSafetyHandle.Release(handle);
}
static unsafe void CreateStaticSafetyIdInternal(ref int id, in FixedString512Bytes name)
{
id = AtomicSafetyHandle.NewStaticSafetyId(name.GetUnsafePtr(), name.Length);
}
[BurstDiscard]
static void CreateStaticSafetyIdInternal<T>(ref int id)
{
CreateStaticSafetyIdInternal(ref id, typeof(T).ToString());
}
/// <summary>
/// Assigns the provided static safety ID to an [[AtomicSafetyHandle]]. The ID's owner type name and any custom error messages are used by the job debugger when reporting errors involving the target handle.
/// </summary>
/// <remarks>This is preferable to AtomicSafetyHandle.NewStaticSafetyId as it is compatible with burst.</remarks>
/// <typeparam name="T">Type of container safety handle refers to.</typeparam>
/// <param name="handle">Safety handle.</param>
/// <param name="sharedStaticId">The static safety ID to associate with the provided handle. This ID must have been allocated with ::ref::NewStaticSafetyId.</param>
[GenerateTestsForBurstCompatibility(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS", GenericTypeArguments = new[] { typeof(NativeArray<int>) })]
public static void SetStaticSafetyId<T>(ref AtomicSafetyHandle handle, ref int sharedStaticId)
{
if (sharedStaticId == 0)
{
// This will eventually either work with burst supporting a subset of typeof()
// or something similar to Burst.BurstRuntime.GetTypeName() will be implemented
// JIRA issue DOTS-5685
CreateStaticSafetyIdInternal<T>(ref sharedStaticId);
}
AtomicSafetyHandle.SetStaticSafetyId(ref handle, sharedStaticId);
}
/// <summary>
/// Assigns the provided static safety ID to an [[AtomicSafetyHandle]]. The ID's owner type name and any custom error messages are used by the job debugger when reporting errors involving the target handle.
/// </summary>
/// <remarks>This is preferable to AtomicSafetyHandle.NewStaticSafetyId as it is compatible with burst.</remarks>
/// <param name="handle">Safety handle.</param>
/// <param name="sharedStaticId">The static safety ID to associate with the provided handle. This ID must have been allocated with ::ref::NewStaticSafetyId.</param>
/// <param name="name">The name of the resource type.</param>
[GenerateTestsForBurstCompatibility(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS")]
public static unsafe void SetStaticSafetyId(ref AtomicSafetyHandle handle, ref int sharedStaticId, FixedString512Bytes name)
{
if (sharedStaticId == 0)
{
CreateStaticSafetyIdInternal(ref sharedStaticId, name);
}
AtomicSafetyHandle.SetStaticSafetyId(ref handle, sharedStaticId);
}
#endif
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
[BurstDiscard]
static void CheckReflectionDataCorrectInternal<T>(IntPtr reflectionData, ref bool burstCompiled)
{
if (reflectionData == IntPtr.Zero)
throw new InvalidOperationException($"Reflection data was not set up by an Initialize() call. For generic job types, please include [assembly: RegisterGenericJobType(typeof({typeof(T)}))] in your source file.");
burstCompiled = false;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6901d664ec07a214cab08cbd83ca8deb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,209 @@
using System;
using System.Threading;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
#pragma warning disable 0649
namespace Unity.Collections
{
internal struct Long8
{
internal long f0,f1,f2,f3,f4,f5,f6,f7;
}
internal struct Long64
{
internal Long8 f0,f1,f2,f3,f4,f5,f6,f7;
}
internal struct Long512
{
internal Long64 f0,f1,f2,f3,f4,f5,f6,f7;
}
internal struct Long1024 : IIndexable<long>
{
internal Long512 f0,f1;
public int Length { get { return 1024;} set {} }
public ref long ElementAt(int index)
{
unsafe { fixed(Long512* p = &f0) {
return ref UnsafeUtility.AsRef<long>((long*)p + index);
} }
}
}
internal class ConcurrentMask
{
internal static long AtomicOr(ref long destination, long source)
{
var readValue = Interlocked.Read(ref destination);
long oldReadValue, writtenValue;
do
{
writtenValue = readValue | source;
oldReadValue = readValue;
readValue = Interlocked.CompareExchange(ref destination, writtenValue, oldReadValue);
} while(readValue != oldReadValue);
return writtenValue;
}
internal static long AtomicAnd(ref long destination, long source)
{
var readValue = Interlocked.Read(ref destination);
long oldReadValue, writtenValue;
do
{
writtenValue = readValue & source;
oldReadValue = readValue;
readValue = Interlocked.CompareExchange(ref destination, writtenValue, oldReadValue);
} while(readValue != oldReadValue);
return writtenValue;
}
internal static void longestConsecutiveOnes(long value, out int offset, out int count)
{
count = 0;
var newvalue = value;
while(newvalue != 0)
{
value = newvalue;
newvalue = value & (long)((ulong)value >> 1);
++count;
}
offset = math.tzcnt(value);
}
internal static bool foundAtLeastThisManyConsecutiveOnes(long value, int minimum, out int offset, out int count)
{
if(minimum == 1)
{
offset = math.tzcnt(value); // find offset of first 1 bit
count = 1;
return offset != 64;
}
longestConsecutiveOnes(value, out offset, out count);
return count >= minimum;
}
internal static bool foundAtLeastThisManyConsecutiveZeroes(long value, int minimum, out int offset, out int count)
{
return foundAtLeastThisManyConsecutiveOnes(~value, minimum, out offset, out count);
}
internal const int ErrorFailedToFree = -1;
internal const int ErrorFailedToAllocate = -2;
internal const int ErrorAllocationCrossesWordBoundary = -3;
internal const int EmptyBeforeAllocation = 0;
internal const int EmptyAfterFree = 0;
internal static bool Succeeded(int error)
{
return error >= 0;
}
internal static long MakeMask(int offset, int bits)
{
return (long)(~0UL >> (64-bits)) << offset;
}
internal static int TryAllocate(ref long l, int offset, int bits)
{
var mask = MakeMask(offset, bits);
var readValue = Interlocked.Read(ref l);
long oldReadValue, writtenValue;
do
{
if((readValue & mask) != 0)
return ErrorFailedToAllocate;
writtenValue = readValue | mask;
oldReadValue = readValue;
readValue = Interlocked.CompareExchange(ref l, writtenValue, oldReadValue);
} while(readValue != oldReadValue);
return math.countbits(readValue); // how many bits were set, before i allocated? sometimes if 0, do something special (allocate chunk?)
}
internal static int TryFree(ref long l, int offset, int bits)
{
var mask = MakeMask(offset, bits);
var readValue = Interlocked.Read(ref l);
long oldReadValue, writtenValue;
do
{
if((readValue & mask) != mask)
return ErrorFailedToFree;
writtenValue = readValue & ~mask;
oldReadValue = readValue;
readValue = Interlocked.CompareExchange(ref l, writtenValue, oldReadValue);
} while(readValue != oldReadValue);
return math.countbits(writtenValue); // how many bits are set, after i freed? sometimes if 0, do something special (free chunk?)
}
internal static int TryAllocate(ref long l, out int offset, int bits)
{
var readValue = Interlocked.Read(ref l);
long oldReadValue, writtenValue;
do
{
if(!foundAtLeastThisManyConsecutiveZeroes(readValue, bits, out offset, out int _))
return ErrorFailedToAllocate;
var mask = MakeMask(offset, bits);
writtenValue = readValue | mask;
oldReadValue = readValue;
readValue = Interlocked.CompareExchange(ref l, writtenValue, oldReadValue);
} while(readValue != oldReadValue);
return math.countbits(readValue); // how many bits were set, before i allocated? sometimes if 0, do something special (allocate chunk?)
}
internal static int TryAllocate<T>(ref T t, int offset, int bits) where T : IIndexable<long>
{
var wordOffset = offset >> 6;
var bitOffset = offset & 63;
if(bitOffset + bits > 64)
return ErrorAllocationCrossesWordBoundary;
return TryAllocate(ref t.ElementAt(wordOffset), bitOffset, bits);
}
internal static int TryFree<T>(ref T t, int offset, int bits) where T : IIndexable<long>
{
var wordOffset = offset >> 6;
var bitOffset = offset & 63;
return TryFree(ref t.ElementAt(wordOffset), bitOffset, bits);
}
internal static int TryAllocate<T>(ref T t, out int offset, int begin, int end, int bits) where T : IIndexable<long>
{
var wordOffset = begin;
for(; wordOffset < end; ++wordOffset)
if(t.ElementAt(wordOffset) != ~0L)
break;
for(; wordOffset < end; ++wordOffset)
{
int error, bitOffset;
error = TryAllocate(ref t.ElementAt(wordOffset), out bitOffset, bits);
if(Succeeded(error))
{
offset = wordOffset * 64 + bitOffset;
return error;
}
}
offset = -1;
return ErrorFailedToAllocate;
}
internal static int TryAllocate<T>(ref T t, out int offset, int begin, int bits) where T : IIndexable<long>
{
var error = TryAllocate(ref t, out offset, begin, t.Length, bits);
if(Succeeded(error))
return error;
return TryAllocate(ref t, out offset, 0, begin, bits);
}
internal static int TryAllocate<T>(ref T t, out int offset, int bits) where T : IIndexable<long>
{
return TryAllocate(ref t, out offset, 0, t.Length, bits);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c6561bdb03b3b415a9725d8af46e62d4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,111 @@
namespace Unity.Collections.LowLevel.Unsafe
{
/// <summary>
/// Extension methods for DataStream.
/// </summary>
[GenerateTestsForBurstCompatibility]
public static class DataStreamExtensions
{
/// <summary>
/// Initializes a new instance of the DataStreamWriter struct with externally owned memory
/// </summary>
/// <param name="data">Pointer to the data</param>
/// <param name="length">Length of the data</param>
/// <returns>A new instance of the <see cref="DataStreamWriter"/></returns>
public static unsafe DataStreamWriter Create(byte* data, int length)
{
var na = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(data, length, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref na, AtomicSafetyHandle.GetTempMemoryHandle());
#endif
return new DataStreamWriter(na);
}
/// <summary>
/// Appends a specified number of bytes from the buffer to the data stream.
/// </summary>
/// <param name="writer">Data stream writer.</param>
/// <param name="data">Pointer to the data.</param>
/// <param name="bytes">A positive number of bytes to write.</param>
/// <returns>Whether the write was successful</returns>
public static unsafe bool WriteBytesUnsafe(this ref DataStreamWriter writer, byte* data, int bytes)
{
var dataArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(data, bytes, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref dataArray, AtomicSafetyHandle.GetTempMemoryHandle());
#endif
return writer.WriteBytes(dataArray);
}
/// <summary>
/// Read and copy data to the memory location pointed to, an error will
/// be logged if the <paramref name="length"/> will put the reader out of bounds on the current read pointer.
/// </summary>
/// <param name="reader">Data stream reader.</param>
/// <param name="data">Pointer to the data.</param>
/// <param name="length">Number of bytes to read.</param>
public static unsafe void ReadBytesUnsafe(this ref DataStreamReader reader, byte* data, int length)
{
var dataArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(data, length, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref dataArray, AtomicSafetyHandle.GetTempMemoryHandle());
#endif
reader.ReadBytes(dataArray);
}
/// <summary>
/// Reads a 2-byte length value from the current stream, reads the specified number of bytes
/// to the buffer and advances the current position of the stream by the length of the string.
/// </summary>
/// <param name="reader">Data stream reader.</param>
/// <param name="data">Buffer to write the string bytes to.</param>
/// <param name="maxLength">Max number of bytes allowed to be read into the buffer.</param>
/// <returns>The number of bytes written to the data buffer.</returns>
public static unsafe ushort ReadFixedStringUnsafe(this ref DataStreamReader reader, byte* data, int maxLength)
{
var dataArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(data, maxLength, Allocator.Temp);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref dataArray, AtomicSafetyHandle.GetTempMemoryHandle());
#endif
return reader.ReadFixedString(dataArray);
}
/// <summary>
/// Writes a delta FixedString value to the data stream using a <see cref="StreamCompressionModel"/>.
///
/// If the value cannot be written <see cref="DataStreamReader.HasFailedReads"/> will return true.
/// </summary>
/// <param name="reader">Data stream reader.</param>
/// <param name="data">Pointer to a packed fixed string.</param>
/// <param name="maxLength">Max number of bytes allowed to be read into the pointer.</param>
/// <param name="baseData">Pointer to the previous value, used to compute the diff.</param>
/// <param name="baseLength">The length of the previous value.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public static unsafe ushort ReadPackedFixedStringDeltaUnsafe(this ref DataStreamReader reader, byte* data, int maxLength, byte* baseData, ushort baseLength, StreamCompressionModel model)
{
var current = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(data, maxLength, Allocator.Temp);
var baseline = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(baseData, baseLength, Allocator.Temp);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var safetyHandle = AtomicSafetyHandle.GetTempMemoryHandle();
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref current, safetyHandle);
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref baseline, safetyHandle);
#endif
return reader.ReadPackedFixedStringDelta(current, baseline, model);
}
/// <summary>
/// Get a pointer to the stream's data. Note that the pointer always points at the
/// beginning of the data, no matter how much was read from the stream.
/// </summary>
/// <remarks>Performs a job safety check for read-only access.</remarks>
/// <param name="reader">Data stream reader.</param>
/// <returns>A pointer to the stream's data.</returns>
public static unsafe void* GetUnsafeReadOnlyPtr(this ref DataStreamReader reader)
{
reader.CheckRead();
return reader.m_BufferPtr;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: dde1b485b0c74a789255539c2152dd1b
timeCreated: 1645104483
@@ -0,0 +1,817 @@
using System;
using System.Diagnostics;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Scripting.APIUpdating;
namespace Unity.Collections
{
/// <summary>
/// Writes data in an endian format to deserialize data.
/// </summary>
/// <remarks>
/// The DataStreamReader class is the counterpart of the
/// <see cref="DataStreamWriter"/> class and can be be used to deserialize
/// data which was prepared with it.
///
/// DataStreamWriter writes this data in the endian format native
/// to the current machine architecture.
/// <br/>
/// For network byte order use the so named methods.
/// <br/>
/// Simple usage example:
/// <code>
/// using (var dataWriter = new DataStreamWriter(16, Allocator.Persistent))
/// {
/// dataWriter.Write(42);
/// dataWriter.Write(1234);
/// // Length is the actual amount of data inside the writer,
/// // Capacity is the total amount.
/// var dataReader = new DataStreamReader(dataWriter, 0, dataWriter.Length);
/// var context = default(DataStreamReader.Context);
/// var myFirstInt = dataReader.ReadInt(ref context);
/// var mySecondInt = dataReader.ReadInt(ref context);
/// }
/// </code>
///
/// DataStreamReader carries the position of the read pointer inside the struct,
/// taking a copy of the reader will also copy the read position. This includes passing the
/// reader to a method by value instead of by ref.
///
/// <seealso cref="DataStreamWriter"/>
/// <seealso cref="IsLittleEndian"/>
/// </remarks>
[MovedFrom(true, "Unity.Networking.Transport")]
[GenerateTestsForBurstCompatibility]
public unsafe struct DataStreamReader
{
struct Context
{
public int m_ReadByteIndex;
public int m_BitIndex;
public ulong m_BitBuffer;
public int m_FailedReads;
}
[NativeDisableUnsafePtrRestriction] internal byte* m_BufferPtr;
Context m_Context;
int m_Length;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
#endif
/// <summary>
/// Initializes a new instance of the DataStreamReader struct with a NativeArray&lt;byte&gt;
/// </summary>
/// <param name="array">The buffer to attach to the DataStreamReader.</param>
public DataStreamReader(NativeArray<byte> array)
{
Initialize(out this, array);
}
static void Initialize(out DataStreamReader self, NativeArray<byte> array)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
self.m_Safety = NativeArrayUnsafeUtility.GetAtomicSafetyHandle(array);
#endif
self.m_BufferPtr = (byte*)array.GetUnsafeReadOnlyPtr();
self.m_Length = array.Length;
self.m_Context = default;
}
/// <summary>
/// Show the byte order in which the current computer architecture stores data.
/// </summary>
/// <remarks>
/// Different computer architectures store data using different byte orders.
/// <list type="bullet">
/// <item>Big-endian: the most significant byte is at the left end of a word.</item>
/// <item>Little-endian: means the most significant byte is at the right end of a word.</item>
/// </list>
/// </remarks>
public static bool IsLittleEndian { get { return DataStreamWriter.IsLittleEndian; } }
static short ByteSwap(short val)
{
return (short)(((val & 0xff) << 8) | ((val >> 8) & 0xff));
}
static int ByteSwap(int val)
{
return (int)(((val & 0xff) << 24) | ((val & 0xff00) << 8) | ((val >> 8) & 0xff00) | ((val >> 24) & 0xff));
}
/// <summary>
/// If there is a read failure this returns true. A read failure might happen if this attempts to read more than there is capacity for.
/// </summary>
public readonly bool HasFailedReads => m_Context.m_FailedReads > 0;
/// <summary>
/// The total size of the buffer space this reader is working with.
/// </summary>
public readonly int Length
{
get
{
CheckRead();
return m_Length;
}
}
/// <summary>
/// True if the reader has been pointed to a valid buffer space. This
/// would be false if the reader was created with no arguments.
/// </summary>
public readonly bool IsCreated
{
get { return m_BufferPtr != null; }
}
void ReadBytesInternal(byte* data, int length)
{
CheckRead();
if (GetBytesRead() + length > m_Length)
{
++m_Context.m_FailedReads;
#if (ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG)
UnityEngine.Debug.LogError($"Trying to read {length} bytes from a stream where only {m_Length - GetBytesRead()} are available");
#endif
UnsafeUtility.MemClear(data, length);
return;
}
// Restore the full bytes moved to the bit buffer but no consumed
Flush();
UnsafeUtility.MemCpy(data, m_BufferPtr + m_Context.m_ReadByteIndex, length);
m_Context.m_ReadByteIndex += length;
}
/// <summary>
/// Read and copy data into the given NativeArray of bytes. An error will
/// be logged if not enough bytes are available to fill the array, and
/// <see cref="HasFailedReads"/> will then be true.
/// </summary>
/// <param name="array">Array to copy data into.</param>
public void ReadBytes(NativeArray<byte> array)
{
ReadBytesInternal((byte*)array.GetUnsafePtr(), array.Length);
}
/// <summary>
/// Read and copy data into the given <c>Span</c> of bytes. An error will
/// be logged if not enough bytes are available to fill the array, and
/// <see cref="HasFailedReads"/> will then be true.
/// </summary>
/// <param name="span">Span to copy data into.</param>
public void ReadBytes(Span<byte> span)
{
fixed (byte* ptr = span)
{
ReadBytesInternal(ptr, span.Length);
}
}
/// <summary>
/// Gets the number of bytes read from the data stream.
/// </summary>
/// <returns>Number of bytes read.</returns>
public int GetBytesRead()
{
return m_Context.m_ReadByteIndex - (m_Context.m_BitIndex >> 3);
}
/// <summary>
/// Gets the number of bits read from the data stream.
/// </summary>
/// <returns>Number of bits read.</returns>
public int GetBitsRead()
{
return (m_Context.m_ReadByteIndex << 3) - m_Context.m_BitIndex;
}
/// <summary>
/// Sets the current position of this stream to the given value.
/// An error will be logged if <paramref name="pos"/> is outside the length of the stream.
/// <br/>
/// In addition this will reset the bit index and the bit buffer.
/// </summary>
/// <param name="pos">Seek position.</param>
public void SeekSet(int pos)
{
if (pos > m_Length)
{
++m_Context.m_FailedReads;
#if (ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG)
UnityEngine.Debug.LogError($"Trying to seek to {pos} in a stream of length {m_Length}");
#endif
return;
}
m_Context.m_ReadByteIndex = pos;
m_Context.m_BitIndex = 0;
m_Context.m_BitBuffer = 0UL;
}
/// <summary>
/// Reads an unsigned byte from the current stream and advances the current position of the stream by one byte.
/// </summary>
/// <returns>The next byte read from the current stream, or 0 if the end of the stream has been reached.</returns>
public byte ReadByte()
{
byte data;
ReadBytesInternal((byte*)&data, sizeof(byte));
return data;
}
/// <summary>
/// Reads a 2-byte signed short from the current stream and advances the current position of the stream by two bytes.
/// </summary>
/// <returns>A 2-byte signed short read from the current stream, or 0 if the end of the stream has been reached.</returns>
public short ReadShort()
{
short data;
ReadBytesInternal((byte*)&data, sizeof(short));
return data;
}
/// <summary>
/// Reads a 2-byte unsigned short from the current stream and advances the current position of the stream by two bytes.
/// </summary>
/// <returns>A 2-byte unsigned short read from the current stream, or 0 if the end of the stream has been reached.</returns>
public ushort ReadUShort()
{
ushort data;
ReadBytesInternal((byte*)&data, sizeof(ushort));
return data;
}
/// <summary>
/// Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.
/// </summary>
/// <returns>A 4-byte signed integer read from the current stream, or 0 if the end of the stream has been reached.</returns>
public int ReadInt()
{
int data;
ReadBytesInternal((byte*)&data, sizeof(int));
return data;
}
/// <summary>
/// Reads a 4-byte unsigned integer from the current stream and advances the current position of the stream by four bytes.
/// </summary>
/// <returns>A 4-byte unsigned integer read from the current stream, or 0 if the end of the stream has been reached.</returns>
public uint ReadUInt()
{
uint data;
ReadBytesInternal((byte*)&data, sizeof(uint));
return data;
}
/// <summary>
/// Reads an 8-byte signed long from the stream and advances the current position of the stream by eight bytes.
/// </summary>
/// <returns>An 8-byte signed long read from the current stream, or 0 if the end of the stream has been reached.</returns>
public long ReadLong()
{
long data;
ReadBytesInternal((byte*)&data, sizeof(long));
return data;
}
/// <summary>
/// Reads an 8-byte unsigned long from the stream and advances the current position of the stream by eight bytes.
/// </summary>
/// <returns>An 8-byte unsigned long read from the current stream, or 0 if the end of the stream has been reached.</returns>
public ulong ReadULong()
{
ulong data;
ReadBytesInternal((byte*)&data, sizeof(ulong));
return data;
}
/// <summary>
/// Aligns the read pointer to the next byte-aligned position. Does nothing if already aligned.
/// </summary>
/// <remarks>If you call <see cref="DataStreamWriter.Flush"/>, call this to bit-align the reader.</remarks>
public void Flush()
{
m_Context.m_ReadByteIndex -= (m_Context.m_BitIndex >> 3);
m_Context.m_BitIndex = 0;
m_Context.m_BitBuffer = 0;
}
/// <summary>
/// Reads a 2-byte signed short from the current stream in Big-endian byte order and advances the current position of the stream by two bytes.
/// If the current endianness is in little-endian order, the byte order will be swapped.
/// </summary>
/// <returns>A 2-byte signed short read from the current stream, or 0 if the end of the stream has been reached.</returns>
public short ReadShortNetworkByteOrder()
{
short data;
ReadBytesInternal((byte*)&data, sizeof(short));
return IsLittleEndian ? ByteSwap(data) : data;
}
/// <summary>
/// Reads a 2-byte unsigned short from the current stream in Big-endian byte order and advances the current position of the stream by two bytes.
/// If the current endianness is in little-endian order, the byte order will be swapped.
/// </summary>
/// <returns>A 2-byte unsigned short read from the current stream, or 0 if the end of the stream has been reached.</returns>
public ushort ReadUShortNetworkByteOrder()
{
return (ushort)ReadShortNetworkByteOrder();
}
/// <summary>
/// Reads a 4-byte signed integer from the current stream in Big-endian byte order and advances the current position of the stream by four bytes.
/// If the current endianness is in little-endian order, the byte order will be swapped.
/// </summary>
/// <returns>A 4-byte signed integer read from the current stream, or 0 if the end of the stream has been reached.</returns>
public int ReadIntNetworkByteOrder()
{
int data;
ReadBytesInternal((byte*)&data, sizeof(int));
return IsLittleEndian ? ByteSwap(data) : data;
}
/// <summary>
/// Reads a 4-byte unsigned integer from the current stream in Big-endian byte order and advances the current position of the stream by four bytes.
/// If the current endianness is in little-endian order, the byte order will be swapped.
/// </summary>
/// <returns>A 4-byte unsigned integer read from the current stream, or 0 if the end of the stream has been reached.</returns>
public uint ReadUIntNetworkByteOrder()
{
return (uint)ReadIntNetworkByteOrder();
}
/// <summary>
/// Reads a 4-byte floating point value from the current stream and advances the current position of the stream by four bytes.
/// </summary>
/// <returns>A 4-byte floating point value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public float ReadFloat()
{
UIntFloat uf = new UIntFloat();
uf.intValue = (uint)ReadInt();
return uf.floatValue;
}
/// <summary>
/// Reads a 8-byte floating point value from the current stream and advances the current position of the stream by four bytes.
/// </summary>
/// <returns>A 8-byte floating point value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public double ReadDouble()
{
UIntFloat uf = new UIntFloat();
uf.longValue = (ulong)ReadLong();
return uf.doubleValue;
}
/// <summary>
/// Reads a 4-byte unsigned integer from the current stream using a <see cref="StreamCompressionModel"/> and advances the current position the number of bits depending on the model.
/// </summary>
/// <param name="model"><see cref="StreamCompressionModel"/> model for reading value in a packed manner.</param>
/// <returns>A 4-byte unsigned integer read from the current stream, or 0 if the end of the stream has been reached.</returns>
public uint ReadPackedUInt(in StreamCompressionModel model)
{
return ReadPackedUIntInternal(StreamCompressionModel.k_MaxHuffmanSymbolLength, model);
}
uint ReadPackedUIntInternal(int maxSymbolLength, in StreamCompressionModel model)
{
CheckRead();
FillBitBuffer();
uint peekMask = (1u << maxSymbolLength) - 1u;
uint peekBits = (uint)m_Context.m_BitBuffer & peekMask;
ushort huffmanEntry = model.decodeTable[(int)peekBits];
int symbol = huffmanEntry >> 8;
int length = huffmanEntry & 0xFF;
if (m_Context.m_BitIndex < length)
{
++m_Context.m_FailedReads;
#if (ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG)
UnityEngine.Debug.LogError($"Trying to read {length} bits from a stream where only {m_Context.m_BitIndex} are available");
#endif
return 0;
}
// Skip Huffman bits
m_Context.m_BitBuffer >>= length;
m_Context.m_BitIndex -= length;
uint offset = model.bucketOffsets[symbol];
byte bits = model.bucketSizes[symbol];
return ReadRawBitsInternal(bits) + offset;
}
void FillBitBuffer()
{
while (m_Context.m_BitIndex <= 56 && m_Context.m_ReadByteIndex < m_Length)
{
m_Context.m_BitBuffer |= (ulong)m_BufferPtr[m_Context.m_ReadByteIndex++] << m_Context.m_BitIndex;
m_Context.m_BitIndex += 8;
}
}
uint ReadRawBitsInternal(int numbits)
{
CheckBits(numbits);
if (m_Context.m_BitIndex < numbits)
{
++m_Context.m_FailedReads;
#if (ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG)
UnityEngine.Debug.LogError($"Trying to read {numbits} bits from a stream where only {m_Context.m_BitIndex} are available");
#endif
return 0;
}
uint res = (uint)(m_Context.m_BitBuffer & ((1UL << numbits) - 1UL));
m_Context.m_BitBuffer >>= numbits;
m_Context.m_BitIndex -= numbits;
return res;
}
/// <summary>
/// Reads a specified number of bits from the data stream.
/// </summary>
/// <param name="numbits">A positive number of bytes to write.</param>
/// <returns>A 4-byte unsigned integer read from the current stream, or 0 if the end of the stream has been reached.</returns>
public uint ReadRawBits(int numbits)
{
CheckRead();
FillBitBuffer();
return ReadRawBitsInternal(numbits);
}
/// <summary>
/// Reads an 8-byte unsigned long value from the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="model"><see cref="StreamCompressionModel"/> model for reading value in a packed manner.</param>
/// <returns>An 8-byte unsigned long read from the current stream, or 0 if the end of the stream has been reached.</returns>
public ulong ReadPackedULong(in StreamCompressionModel model)
{
ulong value = ReadPackedUInt(model);
value |= (ulong)ReadPackedUInt(model) << 32;
return value;
}
/// <summary>
/// Reads a 4-byte signed integer value from the data stream using a <see cref="StreamCompressionModel"/>.
/// <br/>
/// Negative values de-interleaves from positive values before returning, for example (0, -1, 1, -2, 2) -> (-2, -1, 0, 1, 2)
/// </summary>
/// <param name="model"><see cref="StreamCompressionModel"/> model for reading value in a packed manner.</param>
/// <returns>A 4-byte signed integer read from the current stream, or 0 if the end of the stream has been reached.</returns>
public int ReadPackedInt(in StreamCompressionModel model)
{
uint folded = ReadPackedUInt(model);
return (int)(folded >> 1) ^ -(int)(folded & 1); // Deinterleave values from [0, -1, 1, -2, 2...] to [..., -2, -1, -0, 1, 2, ...]
}
/// <summary>
/// Reads an 8-byte signed long value from the data stream using a <see cref="StreamCompressionModel"/>.
/// <br/>
/// Negative values de-interleaves from positive values before returning, for example (0, -1, 1, -2, 2) -> (-2, -1, 0, 1, 2)
/// </summary>
/// <param name="model"><see cref="StreamCompressionModel"/> model for reading value in a packed manner.</param>
/// <returns>An 8-byte signed long read from the current stream, or 0 if the end of the stream has been reached.</returns>
public long ReadPackedLong(in StreamCompressionModel model)
{
ulong folded = ReadPackedULong(model);
return (long)(folded >> 1) ^ -(long)(folded & 1); // Deinterleave values from [0, -1, 1, -2, 2...] to [..., -2, -1, -0, 1, 2, ...]
}
/// <summary>
/// Reads a 4-byte floating point value from the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="model"><see cref="StreamCompressionModel"/> model for reading value in a packed manner.</param>
/// <returns>A 4-byte floating point value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public float ReadPackedFloat(in StreamCompressionModel model)
{
return ReadPackedFloatDelta(0, model);
}
/// <summary>
/// Reads a 8-byte floating point value from the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="model"><see cref="StreamCompressionModel"/> model for reading value in a packed manner.</param>
/// <returns>A 8-byte floating point value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public double ReadPackedDouble(in StreamCompressionModel model)
{
return ReadPackedDoubleDelta(0, model);
}
/// <summary>
/// Reads a 4-byte signed integer delta value from the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="baseline">The previous 4-byte signed integer value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for reading value in a packed manner.</param>
/// <returns>A 4-byte signed integer read from the current stream, or 0 if the end of the stream has been reached.
/// If the data did not change, this also returns 0.
/// <br/>
/// See: <see cref="HasFailedReads"/> to verify if the read failed.</returns>
public int ReadPackedIntDelta(int baseline, in StreamCompressionModel model)
{
int delta = ReadPackedInt(model);
return baseline - delta;
}
/// <summary>
/// Reads a 4-byte unsigned integer delta value from the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="baseline">The previous 4-byte unsigned integer value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for reading value in a packed manner.</param>
/// <returns>A 4-byte unsigned integer read from the current stream, or 0 if the end of the stream has been reached.
/// If the data did not change, this also returns 0.
/// <br/>
/// See: <see cref="HasFailedReads"/> to verify if the read failed.</returns>
public uint ReadPackedUIntDelta(uint baseline, in StreamCompressionModel model)
{
uint delta = (uint)ReadPackedInt(model);
return baseline - delta;
}
/// <summary>
/// Reads an 8-byte signed long delta value from the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="baseline">The previous 8-byte signed long value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for reading value in a packed manner.</param>
/// <returns>An 8-byte signed long read from the current stream, or 0 if the end of the stream has been reached.
/// If the data did not change, this also returns 0.
/// <br/>
/// See: <see cref="HasFailedReads"/> to verify if the read failed.</returns>
public long ReadPackedLongDelta(long baseline, in StreamCompressionModel model)
{
long delta = ReadPackedLong(model);
return baseline - delta;
}
/// <summary>
/// Reads an 8-byte unsigned long delta value from the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="baseline">The previous 8-byte unsigned long value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for reading value in a packed manner.</param>
/// <returns>An 8-byte unsigned long read from the current stream, or 0 if the end of the stream has been reached.
/// If the data did not change, this also returns 0.
/// <br/>
/// See: <see cref="HasFailedReads"/> to verify if the read failed.</returns>
public ulong ReadPackedULongDelta(ulong baseline, in StreamCompressionModel model)
{
ulong delta = (ulong)ReadPackedLong(model);
return baseline - delta;
}
/// <summary>
/// Reads a 4-byte floating point value from the data stream.
///
/// If the first bit is 0, the data did not change and <paramref name="baseline"/> will be returned.
/// </summary>
/// <param name="baseline">The previous 4-byte floating point value.</param>
/// <param name="model">Not currently used.</param>
/// <returns>A 4-byte floating point value read from the current stream, or <paramref name="baseline"/> if there are no changes to the value.
/// <br/>
/// See: <see cref="HasFailedReads"/> to verify if the read failed.</returns>
public float ReadPackedFloatDelta(float baseline, in StreamCompressionModel model)
{
CheckRead();
FillBitBuffer();
if (ReadRawBitsInternal(1) == 0)
return baseline;
var bits = 32;
UIntFloat uf = new UIntFloat();
uf.intValue = ReadRawBitsInternal(bits);
return uf.floatValue;
}
/// <summary>
/// Reads a 8-byte floating point value from the data stream.
///
/// If the first bit is 0, the data did not change and <paramref name="baseline"/> will be returned.
/// </summary>
/// <param name="baseline">The previous 8-byte floating point value.</param>
/// <param name="model">Not currently used.</param>
/// <returns>A 8-byte floating point value read from the current stream, or <paramref name="baseline"/> if there are no changes to the value.
/// <br/>
/// See: <see cref="HasFailedReads"/> to verify if the read failed.</returns>
public double ReadPackedDoubleDelta(double baseline, in StreamCompressionModel model)
{
CheckRead();
FillBitBuffer();
if (ReadRawBitsInternal(1) == 0)
return baseline;
var bits = 32;
UIntFloat uf = new UIntFloat();
var data = (uint*)&uf.longValue;
data[0] = ReadRawBitsInternal(bits);
FillBitBuffer();
data[1] |= ReadRawBitsInternal(bits);
return uf.doubleValue;
}
/// <summary>
/// Reads a <c>FixedString32Bytes</c> value from the current stream and advances the current position of the stream by the length of the string.
/// </summary>
/// <returns>A <c>FixedString32Bytes</c> value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public unsafe FixedString32Bytes ReadFixedString32()
{
FixedString32Bytes str;
byte* data = ((byte*)&str) + 2;
*(ushort*)&str = ReadFixedStringInternal(data, str.Capacity);
return str;
}
/// <summary>
/// Reads a <c>FixedString64Bytes</c> value from the current stream and advances the current position of the stream by the length of the string.
/// </summary>
/// <returns>A <c>FixedString64Bytes</c> value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public unsafe FixedString64Bytes ReadFixedString64()
{
FixedString64Bytes str;
byte* data = ((byte*)&str) + 2;
*(ushort*)&str = ReadFixedStringInternal(data, str.Capacity);
return str;
}
/// <summary>
/// Reads a <c>FixedString128Bytes</c> value from the current stream and advances the current position of the stream by the length of the string.
/// </summary>
/// <returns>A <c>FixedString128Bytes</c> value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public unsafe FixedString128Bytes ReadFixedString128()
{
FixedString128Bytes str;
byte* data = ((byte*)&str) + 2;
*(ushort*)&str = ReadFixedStringInternal(data, str.Capacity);
return str;
}
/// <summary>
/// Reads a <c>FixedString512Bytes</c> value from the current stream and advances the current position of the stream by the length of the string.
/// </summary>
/// <returns>A <c>FixedString512Bytes</c> value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public unsafe FixedString512Bytes ReadFixedString512()
{
FixedString512Bytes str;
byte* data = ((byte*)&str) + 2;
*(ushort*)&str = ReadFixedStringInternal(data, str.Capacity);
return str;
}
/// <summary>
/// Reads a <c>FixedString4096Bytes</c> value from the current stream and advances the current position of the stream by the length of the string.
/// </summary>
/// <returns>A <c>FixedString4096Bytes</c> value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public unsafe FixedString4096Bytes ReadFixedString4096()
{
FixedString4096Bytes str;
byte* data = ((byte*)&str) + 2;
*(ushort*)&str = ReadFixedStringInternal(data, str.Capacity);
return str;
}
/// <summary>
/// Read and copy data into the given NativeArray of bytes, an error will
/// be logged if not enough bytes are available in the array.
/// </summary>
/// <param name="array">Buffer to write the string bytes to.</param>
/// <returns>Length of data read into byte array, or zero if error occurred.</returns>
public ushort ReadFixedString(NativeArray<byte> array)
{
return ReadFixedStringInternal((byte*)array.GetUnsafePtr(), array.Length);
}
unsafe ushort ReadFixedStringInternal(byte* data, int maxLength)
{
ushort length = ReadUShort();
if (length > maxLength)
{
#if (ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG)
UnityEngine.Debug.LogError($"Trying to read a string of length {length} but max length is {maxLength}");
#endif
return 0;
}
ReadBytesInternal(data, length);
return length;
}
/// <summary>
/// Reads a <c>FixedString32Bytes</c> delta value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="baseline">The previous <c>FixedString32Bytes</c> value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>A <c>FixedString32Bytes</c> value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public unsafe FixedString32Bytes ReadPackedFixedString32Delta(FixedString32Bytes baseline, in StreamCompressionModel model)
{
FixedString32Bytes str;
byte* data = ((byte*)&str) + 2;
*(ushort*)&str = ReadPackedFixedStringDeltaInternal(data, str.Capacity, ((byte*)&baseline) + 2, *((ushort*)&baseline), model);
return str;
}
/// <summary>
/// Reads a <c>FixedString64Bytes</c> delta value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="baseline">The previous <c>FixedString64Bytes</c> value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>A <c>FixedString64Bytes</c> value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public unsafe FixedString64Bytes ReadPackedFixedString64Delta(FixedString64Bytes baseline, in StreamCompressionModel model)
{
FixedString64Bytes str;
byte* data = ((byte*)&str) + 2;
*(ushort*)&str = ReadPackedFixedStringDeltaInternal(data, str.Capacity, ((byte*)&baseline) + 2, *((ushort*)&baseline), model);
return str;
}
/// <summary>
/// Reads a <c>FixedString128Bytes</c> delta value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="baseline">The previous <c>FixedString128Bytes</c> value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>A <c>FixedString128Bytes</c> value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public unsafe FixedString128Bytes ReadPackedFixedString128Delta(FixedString128Bytes baseline, in StreamCompressionModel model)
{
FixedString128Bytes str;
byte* data = ((byte*)&str) + 2;
*(ushort*)&str = ReadPackedFixedStringDeltaInternal(data, str.Capacity, ((byte*)&baseline) + 2, *((ushort*)&baseline), model);
return str;
}
/// <summary>
/// Reads a <c>FixedString512Bytes</c> delta value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="baseline">The previous <c>FixedString512Bytes</c> value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>A <c>FixedString512Bytes</c> value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public unsafe FixedString512Bytes ReadPackedFixedString512Delta(FixedString512Bytes baseline, in StreamCompressionModel model)
{
FixedString512Bytes str;
byte* data = ((byte*)&str) + 2;
*(ushort*)&str = ReadPackedFixedStringDeltaInternal(data, str.Capacity, ((byte*)&baseline) + 2, *((ushort*)&baseline), model);
return str;
}
/// <summary>
/// Reads a <c>FixedString4096Bytes</c> delta value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="baseline">The previous <c>FixedString4096Bytes</c> value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>A <c>FixedString4096Bytes</c> value read from the current stream, or 0 if the end of the stream has been reached.</returns>
public unsafe FixedString4096Bytes ReadPackedFixedString4096Delta(FixedString4096Bytes baseline, in StreamCompressionModel model)
{
FixedString4096Bytes str;
byte* data = ((byte*)&str) + 2;
*(ushort*)&str = ReadPackedFixedStringDeltaInternal(data, str.Capacity, ((byte*)&baseline) + 2, *((ushort*)&baseline), model);
return str;
}
/// <summary>
/// Read and copy data into the given NativeArray of bytes, an error will
/// be logged if not enough bytes are available in the array.
/// </summary>
/// <param name="data">Array for the current fixed string.</param>
/// <param name="baseData">Array containing the previous value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Length of data read into byte array, or zero if error occurred.</returns>
public ushort ReadPackedFixedStringDelta(NativeArray<byte> data, NativeArray<byte> baseData, in StreamCompressionModel model)
{
return ReadPackedFixedStringDeltaInternal((byte*)data.GetUnsafePtr(), data.Length, (byte*)baseData.GetUnsafePtr(), (ushort)baseData.Length, model);
}
unsafe ushort ReadPackedFixedStringDeltaInternal(byte* data, int maxLength, byte* baseData, ushort baseLength, in StreamCompressionModel model)
{
uint length = ReadPackedUIntDelta(baseLength, model);
if (length > (uint)maxLength)
{
#if (ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG)
UnityEngine.Debug.LogError($"Trying to read a string of length {length} but max length is {maxLength}");
#endif
return 0;
}
if (length <= baseLength)
{
for (int i = 0; i < length; ++i)
data[i] = (byte)ReadPackedUIntDelta(baseData[i], model);
}
else
{
for (int i = 0; i < baseLength; ++i)
data[i] = (byte)ReadPackedUIntDelta(baseData[i], model);
for (int i = baseLength; i < length; ++i)
data[i] = (byte)ReadPackedUInt(model);
}
return (ushort)length;
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
internal readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void CheckBits(int numBits)
{
if (numBits < 0 || numBits > 32)
throw new ArgumentOutOfRangeException($"Invalid number of bits specified: {numBits}! Valid range is (0, 32) inclusive.");
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: fd7af7f776a94a2d8333d503666dc904
timeCreated: 1643805334
@@ -0,0 +1,920 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Scripting.APIUpdating;
namespace Unity.Collections
{
/// <summary>
/// Writes data in an endian format to serialize data.
/// </summary>
/// <remarks>
/// Data streams can be used to serialize data (e.g. over the network). The
/// DataStreamWriter and <see cref="DataStreamReader"/> classes work together
/// to serialize data for sending and then to deserialize when receiving.
///
/// DataStreamWriter writes data in the endian format native to the current machine architecture.
/// For network byte order use the so named methods.
/// <br/>
/// The reader can be used to deserialize the data from a NativeArray&lt;byte&gt;, writing data
/// to a NativeArray&lt;byte&gt; and reading it back can be done like this:
/// <code>
/// using (var data = new NativeArray&lt;byte&gt;(16, Allocator.Persistent))
/// {
/// var dataWriter = new DataStreamWriter(data);
/// dataWriter.WriteInt(42);
/// dataWriter.WriteInt(1234);
/// // Length is the actual amount of data inside the writer,
/// // Capacity is the total amount.
/// var dataReader = new DataStreamReader(nativeArrayOfBytes.GetSubArray(0, dataWriter.Length));
/// var myFirstInt = dataReader.ReadInt();
/// var mySecondInt = dataReader.ReadInt();
/// }
/// </code>
///
/// There are a number of functions for various data types. If a copy of the writer
/// is stored it can be used to overwrite the data later on. This is particularly useful when
/// the size of the data is written at the start and you want to write it at
/// the end when you know the value.
/// <seealso cref="IsLittleEndian"/>
///
/// <code>
/// using (var data = new NativeArray&lt;byte&gt;(16, Allocator.Persistent))
/// {
/// var dataWriter = new DataStreamWriter(data);
/// // My header data
/// var headerSizeMark = dataWriter;
/// dataWriter.WriteUShort((ushort)0);
/// var payloadSizeMark = dataWriter;
/// dataWriter.WriteUShort((ushort)0);
/// dataWriter.WriteInt(42);
/// dataWriter.WriteInt(1234);
/// var headerSize = data.Length;
/// // Update header size to correct value
/// headerSizeMark.WriteUShort((ushort)headerSize);
/// // My payload data
/// byte[] someBytes = Encoding.ASCII.GetBytes("some string");
/// dataWriter.Write(someBytes, someBytes.Length);
/// // Update payload size to correct value
/// payloadSizeMark.WriteUShort((ushort)(dataWriter.Length - headerSize));
/// }
/// </code>
/// </remarks>
[MovedFrom(true, "Unity.Networking.Transport", "Unity.Networking.Transport")]
[StructLayout(LayoutKind.Sequential)]
[GenerateTestsForBurstCompatibility]
public unsafe struct DataStreamWriter
{
/// <summary>
/// Show the byte order in which the current computer architecture stores data.
/// </summary>
/// <remarks>
/// Different computer architectures store data using different byte orders.
/// <list type="bullet">
/// <item>Big-endian: the most significant byte is at the left end of a word.</item>
/// <item>Little-endian: means the most significant byte is at the right end of a word.</item>
/// </list>
/// </remarks>
public static bool IsLittleEndian
{
get
{
uint test = 1;
byte* testPtr = (byte*)&test;
return testPtr[0] == 1;
}
}
struct StreamData
{
public byte* buffer;
public int length;
public int capacity;
public ulong bitBuffer;
public int bitIndex;
public int failedWrites;
}
[NativeDisableUnsafePtrRestriction] StreamData m_Data;
/// <summary>
/// Used for sending data asynchronously.
/// </summary>
public IntPtr m_SendHandleData;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
#endif
/// <summary>
/// Initializes a new instance of the DataStreamWriter struct.
/// </summary>
/// <param name="length">The number of bytes available in the buffer.</param>
/// <param name="allocator">The <see cref="Allocator"/> used to allocate the memory.</param>
public DataStreamWriter(int length, AllocatorManager.AllocatorHandle allocator)
{
CheckAllocator(allocator);
Initialize(out this, CollectionHelper.CreateNativeArray<byte>(length, allocator));
}
/// <summary>
/// Initializes a new instance of the DataStreamWriter struct with a NativeArray&lt;byte&gt;
/// </summary>
/// <param name="data">The buffer to attach to the DataStreamWriter.</param>
public DataStreamWriter(NativeArray<byte> data)
{
Initialize(out this, data);
}
/// <summary>
/// Initializes a new instance of the DataStreamWriter struct with a memory we don't own
/// </summary>
/// <param name="data">Pointer to the data</param>
/// <param name="length">Length of the data</param>
public DataStreamWriter(byte* data, int length)
{
var na = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(data, length, Allocator.Invalid);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref na, AtomicSafetyHandle.GetTempMemoryHandle());
#endif
Initialize(out this, na);
}
/// <summary>
/// Convert internal data buffer to NativeArray for use in entities APIs.
/// </summary>
/// <returns>NativeArray representation of internal buffer.</returns>
public NativeArray<byte> AsNativeArray()
{
var na = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(m_Data.buffer, Length, Allocator.Invalid);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref na, m_Safety);
#endif
return na;
}
static void Initialize(out DataStreamWriter self, NativeArray<byte> data)
{
self.m_SendHandleData = IntPtr.Zero;
self.m_Data.capacity = data.Length;
self.m_Data.length = 0;
self.m_Data.buffer = (byte*)data.GetUnsafePtr();
self.m_Data.bitBuffer = 0;
self.m_Data.bitIndex = 0;
self.m_Data.failedWrites = 0;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
self.m_Safety = NativeArrayUnsafeUtility.GetAtomicSafetyHandle(data);
#endif
}
static short ByteSwap(short val)
{
return (short)(((val & 0xff) << 8) | ((val >> 8) & 0xff));
}
static int ByteSwap(int val)
{
return (int)(((val & 0xff) << 24) | ((val & 0xff00) << 8) | ((val >> 8) & 0xff00) | ((val >> 24) & 0xff));
}
/// <summary>
/// True if there is a valid data buffer present. This would be false
/// if the writer was created with no arguments.
/// </summary>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_Data.buffer != null; }
}
/// <summary>
/// If there is a write failure this returns true.
/// A failure might happen if an attempt is made to write more than there is capacity for.
/// </summary>
public readonly bool HasFailedWrites
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Data.failedWrites > 0;
}
/// <summary>
/// The total size of the data buffer, see <see cref="Length"/> for
/// the size of space used in the buffer.
/// </summary>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return m_Data.capacity;
}
}
/// <summary>
/// The size of the buffer used. See <see cref="Capacity"/> for the total size.
/// </summary>
public int Length
{
get
{
CheckRead();
SyncBitData();
return m_Data.length + ((m_Data.bitIndex + 7) >> 3);
}
}
/// <summary>
/// The size of the buffer used in bits. See <see cref="Length"/> for the length in bytes.
/// </summary>
public int LengthInBits
{
get
{
CheckRead();
SyncBitData();
return m_Data.length * 8 + m_Data.bitIndex;
}
}
void SyncBitData()
{
var bitIndex = m_Data.bitIndex;
if (bitIndex <= 0)
return;
CheckWrite();
var bitBuffer = m_Data.bitBuffer;
int offset = 0;
while (bitIndex > 0)
{
m_Data.buffer[m_Data.length + offset] = (byte)bitBuffer;
bitIndex -= 8;
bitBuffer >>= 8;
++offset;
}
}
/// <summary>
/// Causes any buffered bits to be written to the data buffer.
/// Note this needs to be invoked after using methods that writes directly to the bit buffer.
/// </summary>
public void Flush()
{
while (m_Data.bitIndex > 0)
{
m_Data.buffer[m_Data.length++] = (byte)m_Data.bitBuffer;
m_Data.bitIndex -= 8;
m_Data.bitBuffer >>= 8;
}
m_Data.bitIndex = 0;
}
bool WriteBytesInternal(byte* data, int bytes)
{
CheckWrite();
if (m_Data.length + ((m_Data.bitIndex + 7) >> 3) + bytes > m_Data.capacity)
{
++m_Data.failedWrites;
return false;
}
Flush();
UnsafeUtility.MemCpy(m_Data.buffer + m_Data.length, data, bytes);
m_Data.length += bytes;
return true;
}
/// <summary>
/// Writes an unsigned byte to the current stream and advances the stream position by one byte.
/// </summary>
/// <param name="value">The unsigned byte to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteByte(byte value)
{
return WriteBytesInternal((byte*)&value, sizeof(byte));
}
/// <summary>
/// Copy NativeArray of bytes into the writer's data buffer.
/// </summary>
/// <param name="value">Source byte array</param>
/// <returns>Whether the write was successful</returns>
public bool WriteBytes(NativeArray<byte> value)
{
return WriteBytesInternal((byte*)value.GetUnsafeReadOnlyPtr(), value.Length);
}
/// <summary>
/// Copy <c>Span</c> of bytes into the writer's data buffer.
/// </summary>
/// <param name="value">Source byte span</param>
/// <returns>Whether the write was successful</returns>
public bool WriteBytes(Span<byte> value)
{
fixed (byte* data = value)
{
return WriteBytesInternal(data, value.Length);
}
}
/// <summary>
/// Writes a 2-byte signed short to the current stream and advances the stream position by two bytes.
/// </summary>
/// <param name="value">The 2-byte signed short to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteShort(short value)
{
return WriteBytesInternal((byte*)&value, sizeof(short));
}
/// <summary>
/// Writes a 2-byte unsigned short to the current stream and advances the stream position by two bytes.
/// </summary>
/// <param name="value">The 2-byte unsigned short to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteUShort(ushort value)
{
return WriteBytesInternal((byte*)&value, sizeof(ushort));
}
/// <summary>
/// Writes a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.
/// </summary>
/// <param name="value">The 4-byte signed integer to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteInt(int value)
{
return WriteBytesInternal((byte*)&value, sizeof(int));
}
/// <summary>
/// Reads a 4-byte unsigned integer from the current stream and advances the current position of the stream by four bytes.
/// </summary>
/// <param name="value">The 4-byte unsigned integer to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteUInt(uint value)
{
return WriteBytesInternal((byte*)&value, sizeof(uint));
}
/// <summary>
/// Writes an 8-byte signed long from the stream and advances the current position of the stream by eight bytes.
/// </summary>
/// <param name="value">The 8-byte signed long to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteLong(long value)
{
return WriteBytesInternal((byte*)&value, sizeof(long));
}
/// <summary>
/// Reads an 8-byte unsigned long from the stream and advances the current position of the stream by eight bytes.
/// </summary>
/// <param name="value">The 8-byte unsigned long to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteULong(ulong value)
{
return WriteBytesInternal((byte*)&value, sizeof(ulong));
}
/// <summary>
/// Writes a 2-byte signed short to the current stream using Big-endian byte order and advances the stream position by two bytes.
/// If the stream is in little-endian order, the byte order will be swapped.
/// </summary>
/// <param name="value">The 2-byte signed short to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteShortNetworkByteOrder(short value)
{
short netValue = IsLittleEndian ? ByteSwap(value) : value;
return WriteBytesInternal((byte*)&netValue, sizeof(short));
}
/// <summary>
/// Writes a 2-byte unsigned short to the current stream using Big-endian byte order and advances the stream position by two bytes.
/// If the stream is in little-endian order, the byte order will be swapped.
/// </summary>
/// <param name="value">The 2-byte unsigned short to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteUShortNetworkByteOrder(ushort value)
{
return WriteShortNetworkByteOrder((short)value);
}
/// <summary>
/// Writes a 4-byte signed integer from the current stream using Big-endian byte order and advances the current position of the stream by four bytes.
/// If the current machine is in little-endian order, the byte order will be swapped.
/// </summary>
/// <param name="value">The 4-byte signed integer to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteIntNetworkByteOrder(int value)
{
int netValue = IsLittleEndian ? ByteSwap(value) : value;
return WriteBytesInternal((byte*)&netValue, sizeof(int));
}
/// <summary>
/// Writes a 4-byte unsigned integer from the current stream using Big-endian byte order and advances the current position of the stream by four bytes.
/// If the stream is in little-endian order, the byte order will be swapped.
/// </summary>
/// <param name="value">The 4-byte unsigned integer to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteUIntNetworkByteOrder(uint value)
{
return WriteIntNetworkByteOrder((int)value);
}
/// <summary>
/// Writes a 4-byte floating point value to the data stream.
/// </summary>
/// <param name="value">The 4-byte floating point value to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteFloat(float value)
{
UIntFloat uf = new UIntFloat();
uf.floatValue = value;
return WriteInt((int)uf.intValue);
}
/// <summary>
/// Writes a 8-byte floating point value to the data stream.
/// </summary>
/// <param name="value">The 8-byte floating point value to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteDouble(double value)
{
UIntFloat uf = new UIntFloat();
uf.doubleValue = value;
return WriteLong((long)uf.longValue);
}
void FlushBits()
{
while (m_Data.bitIndex >= 8)
{
m_Data.buffer[m_Data.length++] = (byte)m_Data.bitBuffer;
m_Data.bitIndex -= 8;
m_Data.bitBuffer >>= 8;
}
}
void WriteRawBitsInternal(uint value, int numbits)
{
CheckBits(value, numbits);
m_Data.bitBuffer |= ((ulong)value << m_Data.bitIndex);
m_Data.bitIndex += numbits;
}
/// <summary>
/// Appends a specified number of bits to the data stream.
/// </summary>
/// <param name="value">The bits to write.</param>
/// <param name="numbits">A positive number of bytes to write.</param>
/// <returns>Whether the write was successful</returns>
public bool WriteRawBits(uint value, int numbits)
{
CheckWrite();
if (m_Data.length + ((m_Data.bitIndex + numbits + 7) >> 3) > m_Data.capacity)
{
++m_Data.failedWrites;
return false;
}
WriteRawBitsInternal(value, numbits);
FlushBits();
return true;
}
/// <summary>
/// Writes a 4-byte unsigned integer value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="value">The 4-byte unsigned integer to write.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedUInt(uint value, in StreamCompressionModel model)
{
CheckWrite();
int bucket = model.CalculateBucket(value);
uint offset = model.bucketOffsets[bucket];
int bits = model.bucketSizes[bucket];
ushort encodeEntry = model.encodeTable[bucket];
if (m_Data.length + ((m_Data.bitIndex + (encodeEntry & 0xff) + bits + 7) >> 3) > m_Data.capacity)
{
++m_Data.failedWrites;
return false;
}
WriteRawBitsInternal((uint)(encodeEntry >> 8), encodeEntry & 0xFF);
WriteRawBitsInternal(value - offset, bits);
FlushBits();
return true;
}
/// <summary>
/// Writes an 8-byte unsigned long value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="value">The 8-byte unsigned long to write.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedULong(ulong value, in StreamCompressionModel model)
{
var data = (uint*)&value;
return WritePackedUInt(data[0], model) &
WritePackedUInt(data[1], model);
}
/// <summary>
/// Writes a 4-byte signed integer value to the data stream using a <see cref="StreamCompressionModel"/>.
/// Negative values are interleaved between positive values, i.e. (0, -1, 1, -2, 2)
/// </summary>
/// <param name="value">The 4-byte signed integer to write.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedInt(int value, in StreamCompressionModel model)
{
uint interleaved = (uint)((value >> 31) ^ (value << 1)); // interleave negative values between positive values: 0, -1, 1, -2, 2
return WritePackedUInt(interleaved, model);
}
/// <summary>
/// Writes a 8-byte signed long value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="value">The 8-byte signed long to write.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedLong(long value, in StreamCompressionModel model)
{
ulong interleaved = (ulong)((value >> 63) ^ (value << 1)); // interleave negative values between positive values: 0, -1, 1, -2, 2
return WritePackedULong(interleaved, model);
}
/// <summary>
/// Writes a 4-byte floating point value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="value">The 4-byte floating point value to write.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedFloat(float value, in StreamCompressionModel model)
{
return WritePackedFloatDelta(value, 0, model);
}
/// <summary>
/// Writes a 8-byte floating point value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="value">The 8-byte floating point value to write.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedDouble(double value, in StreamCompressionModel model)
{
return WritePackedDoubleDelta(value, 0, model);
}
/// <summary>
/// Writes a delta 4-byte unsigned integer value to the data stream using a <see cref="StreamCompressionModel"/>.
/// Note that the Uint values are cast to an Int after computing the diff.
/// </summary>
/// <param name="value">The current 4-byte unsigned integer value.</param>
/// <param name="baseline">The previous 4-byte unsigned integer value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedUIntDelta(uint value, uint baseline, in StreamCompressionModel model)
{
int diff = (int)(baseline - value);
return WritePackedInt(diff, model);
}
/// <summary>
/// Writes a delta 4-byte signed integer value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="value">The current 4-byte signed integer value.</param>
/// <param name="baseline">The previous 4-byte signed integer value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedIntDelta(int value, int baseline, in StreamCompressionModel model)
{
int diff = (int)(baseline - value);
return WritePackedInt(diff, model);
}
/// <summary>
/// Writes a delta 8-byte signed long value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="value">The current 8-byte signed long value.</param>
/// <param name="baseline">The previous 8-byte signed long value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedLongDelta(long value, long baseline, in StreamCompressionModel model)
{
long diff = (long)(baseline - value);
return WritePackedLong(diff, model);
}
/// <summary>
/// Writes a delta 8-byte unsigned long value to the data stream using a <see cref="StreamCompressionModel"/>.
/// Note that the unsigned long values are cast to a signed long after computing the diff.
/// </summary>
/// <param name="value">The current 8-byte unsigned long value.</param>
/// <param name="baseline">The previous 8-byte unsigned long, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedULongDelta(ulong value, ulong baseline, in StreamCompressionModel model)
{
long diff = (long)(baseline - value);
return WritePackedLong(diff, model);
}
/// <summary>
/// Writes a 4-byte floating point value to the data stream.
///
/// If the data did not change a zero bit is prepended, otherwise a 1 bit is prepended.
/// When reading back the data, the first bit is then checked for whether the data was changed or not.
/// </summary>
/// <param name="value">The current 4-byte floating point value.</param>
/// <param name="baseline">The previous 4-byte floating value, used to compute the diff.</param>
/// <param name="model">Not currently used.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedFloatDelta(float value, float baseline, in StreamCompressionModel model)
{
CheckWrite();
var bits = 0;
if (value != baseline)
bits = 32;
if (m_Data.length + ((m_Data.bitIndex + 1 + bits + 7) >> 3) > m_Data.capacity)
{
++m_Data.failedWrites;
return false;
}
if (bits == 0)
WriteRawBitsInternal(0, 1);
else
{
WriteRawBitsInternal(1, 1);
UIntFloat uf = new UIntFloat();
uf.floatValue = value;
WriteRawBitsInternal(uf.intValue, bits);
}
FlushBits();
return true;
}
/// <summary>
/// Writes a 8-byte floating point value to the data stream.
///
/// If the data did not change a zero bit is prepended, otherwise a 1 bit is prepended.
/// When reading back the data, the first bit is then checked for whether the data was changed or not.
/// </summary>
/// <param name="value">The current 8-byte floating point value.</param>
/// <param name="baseline">The previous 8-byte floating value, used to compute the diff.</param>
/// <param name="model">Not currently used.</param>
/// <returns>Whether the write was successful</returns>
public bool WritePackedDoubleDelta(double value, double baseline, in StreamCompressionModel model)
{
CheckWrite();
var bits = 0;
if (value != baseline)
bits = 64;
if (m_Data.length + ((m_Data.bitIndex + 1 + bits + 7) >> 3) > m_Data.capacity)
{
++m_Data.failedWrites;
return false;
}
if (bits == 0)
WriteRawBitsInternal(0, 1);
else
{
WriteRawBitsInternal(1, 1);
UIntFloat uf = new UIntFloat();
uf.doubleValue = value;
var data = (uint*)&uf.longValue;
WriteRawBitsInternal(data[0], 32);
FlushBits();
WriteRawBitsInternal(data[1], 32);
}
FlushBits();
return true;
}
/// <summary>
/// Writes a <c>FixedString32Bytes</c> value to the data stream.
/// </summary>
/// <param name="str">The <c>FixedString32Bytes</c> to write.</param>
/// <returns>Whether the write was successful</returns>
public unsafe bool WriteFixedString32(FixedString32Bytes str)
{
int length = (int)*((ushort*)&str) + 2;
byte* data = ((byte*)&str);
return WriteBytesInternal(data, length);
}
/// <summary>
/// Writes a <c>FixedString64Bytes</c> value to the data stream.
/// </summary>
/// <param name="str">The <c>FixedString64Bytes</c> to write.</param>
/// <returns>Whether the write was successful</returns>
public unsafe bool WriteFixedString64(FixedString64Bytes str)
{
int length = (int)*((ushort*)&str) + 2;
byte* data = ((byte*)&str);
return WriteBytesInternal(data, length);
}
/// <summary>
/// Writes a <c>FixedString128Bytes</c> value to the data stream.
/// </summary>
/// <param name="str">The <c>FixedString128Bytes</c> to write.</param>
/// <returns>Whether the write was successful</returns>
public unsafe bool WriteFixedString128(FixedString128Bytes str)
{
int length = (int)*((ushort*)&str) + 2;
byte* data = ((byte*)&str);
return WriteBytesInternal(data, length);
}
/// <summary>
/// Writes a <c>FixedString512Bytes</c> value to the data stream.
/// </summary>
/// <param name="str">The <c>FixedString512Bytes</c> to write.</param>
/// <returns>Whether the write was successful</returns>
public unsafe bool WriteFixedString512(FixedString512Bytes str)
{
int length = (int)*((ushort*)&str) + 2;
byte* data = ((byte*)&str);
return WriteBytesInternal(data, length);
}
/// <summary>
/// Writes a <c>FixedString4096Bytes</c> value to the data stream.
/// </summary>
/// <param name="str">The <c>FixedString4096Bytes</c> to write.</param>
/// <returns>Whether the write was successful</returns>
public unsafe bool WriteFixedString4096(FixedString4096Bytes str)
{
int length = (int)*((ushort*)&str) + 2;
byte* data = ((byte*)&str);
return WriteBytesInternal(data, length);
}
/// <summary>
/// Writes a <c>FixedString32Bytes</c> delta value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="str">The current <c>FixedString32Bytes</c> value.</param>
/// <param name="baseline">The previous <c>FixedString32Bytes</c> value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public unsafe bool WritePackedFixedString32Delta(FixedString32Bytes str, FixedString32Bytes baseline, in StreamCompressionModel model)
{
ushort length = *((ushort*)&str);
byte* data = ((byte*)&str) + 2;
return WritePackedFixedStringDelta(data, length, ((byte*)&baseline) + 2, *((ushort*)&baseline), model);
}
/// <summary>
/// Writes a delta <c>FixedString64Bytes</c> value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="str">The current <c>FixedString64Bytes</c> value.</param>
/// <param name="baseline">The previous <c>FixedString64Bytes</c> value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public unsafe bool WritePackedFixedString64Delta(FixedString64Bytes str, FixedString64Bytes baseline, in StreamCompressionModel model)
{
ushort length = *((ushort*)&str);
byte* data = ((byte*)&str) + 2;
return WritePackedFixedStringDelta(data, length, ((byte*)&baseline) + 2, *((ushort*)&baseline), model);
}
/// <summary>
/// Writes a delta <c>FixedString128Bytes</c> value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="str">The current <c>FixedString128Bytes</c> value.</param>
/// <param name="baseline">The previous <c>FixedString128Bytes</c> value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public unsafe bool WritePackedFixedString128Delta(FixedString128Bytes str, FixedString128Bytes baseline, in StreamCompressionModel model)
{
ushort length = *((ushort*)&str);
byte* data = ((byte*)&str) + 2;
return WritePackedFixedStringDelta(data, length, ((byte*)&baseline) + 2, *((ushort*)&baseline), model);
}
/// <summary>
/// Writes a delta <c>FixedString512Bytes</c> value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="str">The current <c>FixedString512Bytes</c> value.</param>
/// <param name="baseline">The previous <c>FixedString512Bytes</c> value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public unsafe bool WritePackedFixedString512Delta(FixedString512Bytes str, FixedString512Bytes baseline, in StreamCompressionModel model)
{
ushort length = *((ushort*)&str);
byte* data = ((byte*)&str) + 2;
return WritePackedFixedStringDelta(data, length, ((byte*)&baseline) + 2, *((ushort*)&baseline), model);
}
/// <summary>
/// Writes a delta <c>FixedString4096Bytes</c> value to the data stream using a <see cref="StreamCompressionModel"/>.
/// </summary>
/// <param name="str">The current <c>FixedString4096Bytes</c> value.</param>
/// <param name="baseline">The previous <c>FixedString4096Bytes</c> value, used to compute the diff.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
public unsafe bool WritePackedFixedString4096Delta(FixedString4096Bytes str, FixedString4096Bytes baseline, in StreamCompressionModel model)
{
ushort length = *((ushort*)&str);
byte* data = ((byte*)&str) + 2;
return WritePackedFixedStringDelta(data, length, ((byte*)&baseline) + 2, *((ushort*)&baseline), model);
}
/// <summary>
/// Writes a delta FixedString value to the data stream using a <see cref="StreamCompressionModel"/>.
///
/// If the value cannot be written <see cref="HasFailedWrites"/> will return true. This state can be cleared by
/// calling <see cref="Clear"/>.
/// </summary>
/// <param name="data">Pointer to a packed fixed string.</param>
/// <param name="length">The length of the new value.</param>
/// <param name="baseData">The previous value, used to compute the diff.</param>
/// <param name="baseLength">The length of the previous value.</param>
/// <param name="model"><see cref="StreamCompressionModel"/> model for writing value in a packed manner.</param>
/// <returns>Whether the write was successful</returns>
unsafe bool WritePackedFixedStringDelta(byte* data, uint length, byte* baseData, uint baseLength, in StreamCompressionModel model)
{
var oldData = m_Data;
if (!WritePackedUIntDelta(length, baseLength, model))
return false;
bool didFailWrite = false;
if (length <= baseLength)
{
for (uint i = 0; i < length; ++i)
didFailWrite |= !WritePackedUIntDelta(data[i], baseData[i], model);
}
else
{
for (uint i = 0; i < baseLength; ++i)
didFailWrite |= !WritePackedUIntDelta(data[i], baseData[i], model);
for (uint i = baseLength; i < length; ++i)
didFailWrite |= !WritePackedUInt(data[i], model);
}
// If anything was not written, rewind to the previous position
if (didFailWrite)
{
m_Data = oldData;
++m_Data.failedWrites;
}
return !didFailWrite;
}
/// <summary>
/// Moves the write position to the start of the data buffer used.
/// </summary>
public void Clear()
{
m_Data.length = 0;
m_Data.bitIndex = 0;
m_Data.bitBuffer = 0;
m_Data.failedWrites = 0;
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void CheckWrite()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void CheckAllocator(AllocatorManager.AllocatorHandle allocator)
{
if (allocator.ToAllocator != Allocator.Temp)
throw new InvalidOperationException("DataStreamWriters can only be created with temp memory");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void CheckBits(uint value, int numBits)
{
if (numBits < 0 || numBits > 32)
throw new ArgumentOutOfRangeException($"Invalid number of bits specified: {numBits}! Valid range is (0, 32) inclusive.");
var errValue = (1UL << numBits);
if (value >= errValue)
throw new ArgumentOutOfRangeException($"Value {value} does not fit in the specified number of bits: {numBits}! Range (inclusive) is (0, {errValue-1})!");
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 13912e20398d4a03883c4ee9ee4d8818
timeCreated: 1643805345
@@ -0,0 +1,48 @@
using System;
using System.Collections;
namespace Unity.Collections
{
internal struct Pair<Key, Value>
{
public Key key;
public Value value;
public Pair(Key k, Value v)
{
key = k;
value = v;
}
public override string ToString()
{
return $"{key} = {value}";
}
}
// Tiny does not contains an IList definition (or even ICollection)
internal struct ListPair<Key, Value> where Value : IList
{
public Key key;
public Value value;
public ListPair(Key k, Value v)
{
key = k;
value = v;
}
public override string ToString()
{
String result = $"{key} = [";
for (var v = 0; v < value.Count; ++v)
{
result += value[v];
if (v < value.Count - 1)
result += ", ";
}
result += "]";
return result;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 66302e43465db41bc9a7b142b2157ac6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,120 @@
using System;
using System.Diagnostics;
using UnityEngine.Assertions;
using Unity.Collections.LowLevel.Unsafe;
namespace Unity.Collections
{
/// <summary>
/// A double rewindable allocators <see cref="RewindableAllocator"/>.
/// </summary>
unsafe public struct DoubleRewindableAllocators : IDisposable
{
RewindableAllocator* Pointer;
AllocatorHelper<RewindableAllocator> UpdateAllocatorHelper0;
AllocatorHelper<RewindableAllocator> UpdateAllocatorHelper1;
/// <summary>
/// Update the double rewindable allocators, switch Pointer to another allocator and rewind the newly switched allocator.
/// </summary>
public void Update()
{
var UpdateAllocator0 = (RewindableAllocator*)UnsafeUtility.AddressOf(ref UpdateAllocatorHelper0.Allocator);
var UpdateAllocator1 = (RewindableAllocator*)UnsafeUtility.AddressOf(ref UpdateAllocatorHelper1.Allocator);
Pointer = (Pointer == UpdateAllocator0) ? UpdateAllocator1 : UpdateAllocator0;
CheckIsCreated();
Allocator.Rewind();
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckIsCreated()
{
if (!IsCreated)
{
throw new InvalidOperationException($"DoubleRewindableAllocators is not created.");
}
}
/// <summary>
/// Retrieve the current rewindable allocator.
/// </summary>
/// <value>The Allocator retrieved.</value>
public ref RewindableAllocator Allocator
{
get
{
CheckIsCreated();
return ref UnsafeUtility.AsRef<RewindableAllocator>(Pointer);
}
}
/// <summary>
/// Check whether the double rewindable allocators is created.
/// </summary>
/// <value>True if current allocator is not null, otherwise false.</value>
public bool IsCreated => Pointer != null;
/// <summary>
/// Construct a double rewindable allocators by allocating the allocators from backingAllocator and registering them.
/// </summary>
/// <param name="backingAllocator">Allocator used to allocate the double rewindable allocators.</param>
/// <param name="initialSizeInBytes">The initial capacity of the allocators, in bytes</param>
public DoubleRewindableAllocators(AllocatorManager.AllocatorHandle backingAllocator, int initialSizeInBytes)
{
this = default;
// With code reloading, whenever we enter/exit the playmode,
// we enter OnCodeLoaded scope, so we need to ensure that we don’t store old references from previous playmode sessions.
// Here, in an instance constructor, we have ensured the constructed object can't outlive the current CodeLoaded scope.
// So it's safe to suppress the UAL0015 warning.
#pragma warning disable UAL0015
Initialize(backingAllocator, initialSizeInBytes);
#pragma warning restore UAL0015
}
/// <summary>
/// Initialize a double rewindable allocators by allocating the allocators from backingAllocator and registering them.
/// </summary>
/// <param name="backingAllocator">Allocator used to allocate the double rewindable allocators.</param>
/// <param name="initialSizeInBytes">The initial capacity of the allocators, in bytes</param>
public void Initialize(AllocatorManager.AllocatorHandle backingAllocator, int initialSizeInBytes)
{
UpdateAllocatorHelper0 = new AllocatorHelper<RewindableAllocator>(backingAllocator);
UpdateAllocatorHelper1 = new AllocatorHelper<RewindableAllocator>(backingAllocator);
UpdateAllocatorHelper0.Allocator.Initialize(initialSizeInBytes);
UpdateAllocatorHelper1.Allocator.Initialize(initialSizeInBytes);
Pointer = null;
Update();
}
/// <summary>
/// the double rewindable allocators and unregister it.
/// </summary>
public void Dispose()
{
if (!IsCreated)
{
return;
}
UpdateAllocatorHelper0.Allocator.Dispose();
UpdateAllocatorHelper1.Allocator.Dispose();
UpdateAllocatorHelper0.Dispose();
UpdateAllocatorHelper1.Dispose();
}
internal bool EnableBlockFree
{
get
{
Assert.IsTrue(UpdateAllocatorHelper0.Allocator.EnableBlockFree == UpdateAllocatorHelper1.Allocator.EnableBlockFree);
return UpdateAllocatorHelper0.Allocator.EnableBlockFree;
}
set
{
UpdateAllocatorHelper0.Allocator.EnableBlockFree = value;
UpdateAllocatorHelper1.Allocator.EnableBlockFree = value;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 07dc69c5229468f40a380bf9161fb7c4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fb24b35aa8286aa45a866596124a241d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f16da17e34bf5f149a196c3f6b32e37f
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ab361814f7174e46989e7f79e89f7c24
timeCreated: 1590896536
@@ -0,0 +1,882 @@
<#/*THIS IS A T4 FILE - see t4_text_templating.md for what it is and how to run codegen*/#>
<#@ template debug="True" #>
<#@ output extension=".gen.cs" encoding="utf-8" #>
<#@ assembly name="System.Core" #>
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// t4 Samples/Packages/com.unity.collections/Unity.Collections/FixedString.tt
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
using UnityEngine.Internal;
using UnityEngine;
using Unity.Burst;
using Unity.Properties;
namespace Unity.Collections
{
// A temporary copy of a struct is made before it is displayed in a C# debugger.
// However, only the first element of data members with names is copied at this time.
// Therefore, it's important that all data visible in the debugger, has a name
// and includes no 'fixed' array. This is why we name every byte in the following struct.
/// <summary>
/// For internal use only. This type is 8 byte aligned
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Explicit, Size=16)]
[GenerateTestsForBurstCompatibility]
internal struct FixedBytes16Align8
{
<#
for(var i = 0; i < 2; ++i)
{
var offset = (i*8).ToString("D4");
#>
/// <summary>
/// For internal use only.
/// </summary>
[SerializeField] [FieldOffset(<#=i*8#>)] public ulong byte<#=offset#>;
<#
}
#>
}
/// <summary>
/// For internal use only.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Explicit, Size=16)]
[GenerateTestsForBurstCompatibility]
public struct FixedBytes16
{
<#
for(var i = 0; i < 16; ++i)
{
var offset = i.ToString("D4");
#>
/// <summary>
/// For internal use only.
/// </summary>
[FieldOffset(<#=i#>)] public byte byte<#=offset#>;
<#
}
#>
}
<#
{
var SIZES = new [] {32,64,128,512,4096};
foreach (var BYTES in SIZES) {
#>
// A temporary copy of a struct is made before it is displayed in a C# debugger.
// However, only the first element of data members with names is copied at this time.
// Therefore, it's important that all data visible in the debugger, has a name
// and includes no 'fixed' array. This is why we name every byte in the following struct.
/// <summary>
/// For internal use only.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Explicit, Size=<#=BYTES#>)]
[GenerateTestsForBurstCompatibility]
internal struct FixedBytes<#=BYTES#>Align8
{
<#
for(var i = 0; i < (BYTES/16)*16; i += 16)
{
var offset = i.ToString("D4");
#>
/// <summary>
/// For internal use only.
/// </summary>
[SerializeField] [FieldOffset(<#=i#>)] internal FixedBytes16Align8 offset<#=offset#>;
<#
}
#>
}
<#
}}
#>
<#
{
var SIZES = new [] {32,64,128,512,4096};
foreach (var BYTES in SIZES) {
// 2 bytes for the ushort length
var MAXLENGTH = BYTES - 2;
var TYPENAME = $"FixedString{BYTES}Bytes";
var OLD_TYPENAME = $"FixedString{BYTES}";
#>
// A temporary copy of a struct is made before it is displayed in a C# debugger.
// However, only the first element of data members with names is copied at this time.
// Therefore, it's important that all data visible in the debugger, has a name
// and includes no 'fixed' array. This is why we name every byte in the following struct.
/// <summary>
/// For internal use only.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Explicit, Size=<#=MAXLENGTH#>)]
[GenerateTestsForBurstCompatibility]
public struct FixedBytes<#=MAXLENGTH#>
{
<#
for(var i = 0; i < (MAXLENGTH/16)*16; i += 16)
{
var offset = i.ToString("D4");
#>
/// <summary>
/// For internal use only.
/// </summary>
[FieldOffset(<#=i#>)] public FixedBytes16 offset<#=offset#>;
<#
}
for(var i = (MAXLENGTH/16)*16; i < MAXLENGTH; ++i)
{
var offset = i.ToString("D4");
#>
/// <summary>
/// For internal use only.
/// </summary>
[FieldOffset(<#=i#>)] public byte byte<#=offset#>;
<#
}
#>
}
/// <summary>
/// An unmanaged UTF-8 string whose content is stored directly in the <#=BYTES#>-byte struct.
/// </summary>
/// <remarks>
/// The binary layout of this string is guaranteed, for now and all time, to be a length (a little-endian two byte integer)
/// followed by the bytes of the characters (with no padding). A zero byte always immediately follows the last character.
/// Effectively, the number of bytes for storing characters is 3 less than <#=BYTES#> (two length bytes and one null byte).
///
/// This layout is identical to a <see cref="FixedList<#=BYTES#>Bytes{T}"/> of bytes, thus allowing reinterpretation between FixedString<#=BYTES#>Bytes and FixedList<#=BYTES#>Bytes.
///
/// By virtue of being an unmanaged, non-allocated struct with no pointers, this string is fully compatible with jobs and Burst compilation.
/// Unlike managed string types, these strings can be put in any unmanaged ECS components, FixedList, or any other unmanaged structs.
/// </remarks>
[Serializable]
[StructLayout(LayoutKind.Sequential, Size=<#=BYTES#>)]
[GenerateTestsForBurstCompatibility]
public partial struct <#=TYPENAME#>
: INativeList<byte>
, IUTF8Bytes
, IComparable<String>
, IEquatable<String>
<#
foreach (var OTHERBYTES in SIZES)
{
#>
, IComparable<FixedString<#=OTHERBYTES#>Bytes>
, IEquatable<FixedString<#=OTHERBYTES#>Bytes>
<#
}
#>
{
internal const ushort utf8MaxLengthInBytes = <#=MAXLENGTH-1#>;
[SerializeField] internal ushort utf8LengthInBytes;
[SerializeField] internal FixedBytes<#=MAXLENGTH#> bytes;
/// <summary>
/// Returns the maximum number of UTF-8 bytes that can be stored in this string.
/// </summary>
/// <returns>
/// The maximum number of UTF-8 bytes that can be stored in this string.
/// </returns>
public static int UTF8MaxLengthInBytes => utf8MaxLengthInBytes;
/// <summary>
/// For internal use only. Use <see cref="ToString"/> instead.
/// </summary>
/// <value>For internal use only. Use <see cref="ToString"/> instead.</value>
[CreateProperty]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[ExcludeFromBurstCompatTesting("Returns managed string")]
public string Value => ToString();
/// <summary>
/// Returns a pointer to the character bytes.
/// </summary>
/// <remarks>
/// The pointer returned by this method points into the internals of the target FixedString object. It is the
/// caller's responsibility to ensure that the pointer is not used after the FixedString object is destroyed or goes
/// out of scope.
/// </remarks>
/// <returns>A pointer to the character bytes.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly unsafe byte* GetUnsafePtr()
{
fixed(void* b = &bytes)
return (byte*)b;
}
/// <summary>
/// The current length in bytes of this string's content.
/// </summary>
/// <remarks>
/// The length value does not include the null-terminator byte.
/// </remarks>
/// <param name="value">The new length in bytes of the string's content.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the new length is out of bounds.</exception>
/// <value>
/// The current length in bytes of this string's content.
/// </value>
public int Length
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get
{
return utf8LengthInBytes;
}
set
{
CheckLengthInRange(value);
utf8LengthInBytes = (ushort)value;
unsafe
{
GetUnsafePtr()[utf8LengthInBytes] = 0;
}
}
}
/// <summary>
/// The number of bytes this string has for storing UTF-8 characters.
/// </summary>
/// <value>The number of bytes this string has for storing UTF-8 characters.</value>
/// <remarks>
/// Does not include the null-terminator byte.
///
/// A setter is included for conformity with <see cref="INativeList{T}"/>, but <see cref="Capacity"/> is fixed at <#=BYTES-3#>.
/// Setting the value to anything other than <#=BYTES-3#> throws an exception.
///
/// In UTF-8 encoding, each Unicode code point (character) requires 1 to 4 bytes,
/// so the number of characters that can be stored may be less than the capacity.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">Thrown if attempting to set the capacity to anything other than <#=BYTES-3#>.</exception>
public int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get
{
return utf8MaxLengthInBytes;
}
set
{
CheckCapacityInRange(value);
}
}
/// <summary>
/// Attempts to set the length in bytes. Does nothing if the new length is invalid.
/// </summary>
/// <param name="newLength">The desired length.</param>
/// <param name="clearOptions">Whether added or removed bytes should be cleared (zeroed). (Increasing the length adds bytes; decreasing the length removes bytes.)</param>
/// <returns>True if the new length is valid.</returns>
public bool TryResize(int newLength, NativeArrayOptions clearOptions = NativeArrayOptions.ClearMemory)
{
if (newLength < 0 || newLength > utf8MaxLengthInBytes)
return false;
if (newLength == utf8LengthInBytes)
return true;
unsafe
{
if (clearOptions == NativeArrayOptions.ClearMemory)
{
if (newLength > utf8LengthInBytes)
UnsafeUtility.MemClear(GetUnsafePtr() + utf8LengthInBytes, newLength - utf8LengthInBytes);
else
UnsafeUtility.MemClear(GetUnsafePtr() + newLength, utf8LengthInBytes - newLength);
}
utf8LengthInBytes = (ushort)newLength;
// always null terminate
GetUnsafePtr()[utf8LengthInBytes] = 0;
}
return true;
}
/// <summary>
/// Returns true if this string is empty (has no characters).
/// </summary>
/// <value>True if this string is empty (has no characters).</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => utf8LengthInBytes == 0;
}
/// <summary>
/// Returns the byte (not character) at an index.
/// </summary>
/// <param name="index">A byte index.</param>
/// <value>The byte at the index.</value>
/// <exception cref="IndexOutOfRangeException">Thrown if the index is out of bounds.</exception>
public byte this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get
{
unsafe
{
CheckIndexInRange(index);
return GetUnsafePtr()[index];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
unsafe
{
CheckIndexInRange(index);
GetUnsafePtr()[index] = value;
}
}
}
/// <summary>
/// Returns the reference to a byte (not character) at an index.
/// </summary>
/// <param name="index">A byte index.</param>
/// <returns>A reference to the byte at the index.</returns>
/// <exception cref="IndexOutOfRangeException">Thrown if the index is out of bounds.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref byte ElementAt(int index)
{
unsafe
{
CheckIndexInRange(index);
return ref GetUnsafePtr()[index];
}
}
/// <summary>
/// Sets the length to 0.
/// </summary>
public void Clear()
{
Length = 0;
}
/// <summary>
/// Appends a byte.
/// </summary>
/// <remarks>
/// A zero byte will always follow the newly appended byte.
///
/// No validation is performed: it is your responsibility for the bytes of the string to form valid UTF-8 when you're done appending bytes.
/// </remarks>
/// <param name="value">A byte to append.</param>
public void Add(in byte value)
{
this[Length++] = value;
}
/// <summary>
/// An enumerator over the characters (not bytes) of a FixedString<#=BYTES#>Bytes.
/// </summary>
/// <remarks>
/// In an enumerator's initial state, <see cref="Current"/> is not valid to read.
/// The first <see cref="MoveNext"/> call advances the enumerator's index to the first character.
/// </remarks>
public struct Enumerator : IEnumerator
{
FixedString<#=BYTES#>Bytes target;
int offset;
Unicode.Rune current;
/// <summary>
/// Initializes and returns an instance of FixedString<#=BYTES#>Bytes.Enumerator.
/// </summary>
/// <param name="other">A FixeString<#=BYTES#> for which to create an enumerator.</param>
public Enumerator(FixedString<#=BYTES#>Bytes other)
{
target = other;
offset = 0;
current = default;
}
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose()
{
}
/// <summary>
/// Advances the enumerator to the next character.
/// </summary>
/// <returns>True if <see cref="Current"/> is valid to read after the call.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
if (offset >= target.Length)
return false;
unsafe
{
Unicode.Utf8ToUcs(out current, target.GetUnsafePtr(), ref offset, target.Length);
}
return true;
}
/// <summary>
/// Resets the enumerator to its initial state.
/// </summary>
public void Reset()
{
offset = 0;
current = default;
}
/// <summary>
/// The current character.
/// </summary>
/// <remarks>
/// In an enumerator's initial state, <see cref="Current"/> is not valid to read.
/// </remarks>
/// <value>The current character.</value>
public Unicode.Rune Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => current;
}
object IEnumerator.Current => Current;
}
/// <summary>
/// Returns an enumerator for iterating over the characters of this string.
/// </summary>
/// <returns>An enumerator for iterating over the characters of the FixedString<#=BYTES#>Bytes.</returns>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <summary>
/// Returns the lexicographical sort order of this string relative to another.
/// </summary>
/// <param name="other">A `System.String` to compare with.</param>
/// <returns>An integer denoting the lexicographical sort order of this string relative to the other:
///
/// 0 denotes both strings have the same sort position.<br/>
/// -1 denotes that this string should be sorted to precede the other string.<br/>
/// +1 denotes that this string should be sorted to follow the other string.<br/>
/// </returns>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public int CompareTo(String other)
{
return ToString().CompareTo(other);
}
/// <summary>
/// Returns true if this string and another have the same length and all the same characters.
/// </summary>
/// <param name="other">A string to compare for equality.</param>
/// <returns>True if this string and the other have the same length and all the same characters.</returns>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public bool Equals(String other)
{
unsafe {
int alen = utf8LengthInBytes;
int blen = other.Length;
byte* aptr = (byte*) UnsafeUtilityExtensions.AddressOf(bytes);
fixed(char* bptr = other)
{
return UTF8ArrayUnsafeUtility.StrCmp(aptr, alen, bptr, blen) == 0;
}
}
}
/// <summary>
/// Returns a reference to a FixedList<#=BYTES#>Bytes&lt;byte&gt; representation of this string.
/// </summary>
/// <remarks>
/// The referenced FixedListByte<#=BYTES#> is the very same bytes as the original FixedString<#=BYTES#>Bytes,
/// so it is only valid as long as the original FixedString<#=BYTES#>Bytes is valid.
/// </remarks>
/// <returns>A ref to a FixedListByte<#=BYTES#> representation of the FixedString<#=BYTES#>Bytes.</returns>
public unsafe ref FixedList<#=BYTES#>Bytes<byte> AsFixedList()
{
return ref UnsafeUtility.AsRef<FixedList<#=BYTES#>Bytes<byte>>(UnsafeUtility.AddressOf(ref this));
}
/// <summary>
/// Initializes and returns an instance of FixedString<#=BYTES#>Bytes with the characters copied from a string.
/// </summary>
/// <param name="source">The source string to copy.</param>
/// <exception cref="ArgumentException">Thrown if the string to copy's length exceeds the capacity of FixedString<#=BYTES#>Bytes.</exception>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public FixedString<#=BYTES#>Bytes(String source)
{
this = default;
var error = Initialize(source);
CheckCopyError(error, source);
}
/// <summary>
/// Initializes an instance of FixedString<#=BYTES#>Bytes with the characters copied from a string.
/// </summary>
/// <param name="source">The source string to copy.</param>
/// <returns>If the length of the source string exceeds this fixed string's UTF8 capacity, only the portion that fits is copied in and CopyError.Truncation is returned.</returns>
[ExcludeFromBurstCompatTesting("Takes managed string")]
internal CopyError Initialize(String source)
{
return this.CopyFromTruncated(source);
}
/// <summary>
/// Initializes and returns an instance of FixedString<#=BYTES#>Bytes with a single character repeatedly appended some number of times.
/// </summary>
/// <param name="rune">The Unicode.Rune to repeat.</param>
/// <param name="count">The number of times to repeat the character. Default is 1.</param>
public FixedString<#=BYTES#>Bytes(Unicode.Rune rune, int count = 1)
{
this = default;
Initialize(rune, count);
}
/// <summary>
/// Initializes an instance of FixedString<#=BYTES#>Bytes with a single character repeatedly appended some number of times.
/// </summary>
/// <param name="rune">The Unicode.Rune to repeat.</param>
/// <param name="count">The number of times to repeat the character. Default is 1.</param>
/// <returns>If the length of the source string exceeds this fixed string's UTF8 capacity, the entire write operation will fail, and FormatError.Overflow is returned.</returns>
internal FormatError Initialize(Unicode.Rune rune, int count = 1)
{
this = default;
return this.Append(rune, count);
}
/// <summary>
/// Initializes an instance of FixedString<#=BYTES#>Bytes that is a copy of another string.
/// </summary>
/// <param name="srcBytes">The source buffer.</param>
/// <param name="srcLength">The number of bytes to read from the source.</param>
/// <returns>If the length of the source string exceeds this fixed string's UTF8 capacity, the entire write operation will fail, and FormatError.Overflow is returned.</returns>
unsafe internal FormatError Initialize(byte* srcBytes, int srcLength)
{
bytes = default;
utf8LengthInBytes = 0;
unsafe {
int len = 0;
byte* dstBytes = GetUnsafePtr();
var error = UTF8ArrayUnsafeUtility.AppendUTF8Bytes(dstBytes, ref len, utf8MaxLengthInBytes, srcBytes, srcLength);
if(error != FormatError.None)
return error;
this.Length = len;
}
return FormatError.None;
}
/// <summary>
/// Initializes and returns an instance of FixedString<#=BYTES#>Bytes that is a copy of another string.
/// </summary>
/// <param name="other">The string to copy.</param>
/// <exception cref="ArgumentException">Thrown if the string to copy's length exceeds the capacity of FixedString<#=BYTES#>Bytes.</exception>
unsafe public FixedString<#=BYTES#>Bytes(NativeText.ReadOnly other)
{
this = default;
var error = Initialize(other.GetUnsafePtr(), other.Length);
CheckFormatError(error);
}
/// <summary>
/// Initializes and returns an instance of FixedString<#=BYTES#>Bytes that is a copy of another string.
/// </summary>
/// <param name="other">The UnsafeText to copy.</param>
/// <exception cref="ArgumentException">Thrown if the string to copy's length exceeds the capacity of FixedString<#=BYTES#>Bytes.</exception>
unsafe public FixedString<#=BYTES#>Bytes(in UnsafeText other)
{
this = default;
var error = Initialize(other.GetUnsafePtr(), other.Length);
CheckFormatError(error);
}
<#
//
// Generate easy conversion and comparison between this and other FixedString types
//
foreach (var OTHERBYTES in SIZES)
{
#>
/// <summary>
/// Returns the lexicographical sort order of this string relative to another.
/// </summary>
/// <param name="other">A string to compare with.</param>
/// <returns>A number denoting the lexicographical sort order of this string relative to the other:
///
/// 0 denotes that both strings have the same sort position.<br/>
/// -1 denotes that this string should be sorted to precede the other.<br/>
/// +1 denotes that this string should be sorted to follow the other.<br/>
/// </returns>
public int CompareTo(FixedString<#=OTHERBYTES#>Bytes other)
{
return FixedStringMethods.CompareTo(ref this, other);
}
/// <summary>
/// Initializes and returns an instance of FixedString<#=BYTES#>Bytes that is a copy of another string.
/// </summary>
/// <param name="other">The string to copy.</param>
/// <exception cref="ArgumentException">Thrown if the string to copy's length exceeds the capacity of FixedString<#=BYTES#>Bytes.</exception>
public FixedString<#=BYTES#>Bytes(in FixedString<#=OTHERBYTES#>Bytes other)
{
this = default;
var error = Initialize(other);
CheckFormatError(error);
}
/// <summary>
/// Initializes an instance of FixedString<#=BYTES#>Bytes that is a copy of another string.
/// </summary>
/// <param name="other">The string to copy.</param>
/// <returns>If the length of the source string exceeds this fixed string's UTF8 capacity, the entire write operation will fail, and FormatError.Overflow is returned.</returns>
unsafe internal FormatError Initialize(in FixedString<#=OTHERBYTES#>Bytes other)
{
return Initialize((byte*) UnsafeUtilityExtensions.AddressOf(other.bytes), other.utf8LengthInBytes);
}
/// <summary>
/// Returns true if a FixedString<#=BYTES#>Bytes and another string are equal.
/// </summary>
/// <remarks>Two strings are equal if they have equal length and all their characters match.</remarks>
/// <param name="a">A FixedString<#=BYTES#>Bytes to compare for equality.</param>
/// <param name="b">A FixedString<#=OTHERBYTES#>Bytes to compare for equality.</param>
/// <returns>True if the two strings are equal.</returns>
public static bool operator ==(in FixedString<#=BYTES#>Bytes a, in FixedString<#=OTHERBYTES#>Bytes b)
{
// this must not call any methods on 'a' or 'b'
unsafe {
int alen = a.utf8LengthInBytes;
int blen = b.utf8LengthInBytes;
byte* aptr = (byte*) UnsafeUtilityExtensions.AddressOf(a.bytes);
byte* bptr = (byte*) UnsafeUtilityExtensions.AddressOf(b.bytes);
return UTF8ArrayUnsafeUtility.EqualsUTF8Bytes(aptr, alen, bptr, blen);
}
}
/// <summary>
/// Returns true if a FixedString<#=BYTES#>Bytes and another string are unequal.
/// </summary>
/// <remarks>Two strings are equal if they have equal length and all their characters match.</remarks>
/// <param name="a">A FixedString<#=BYTES#>Bytes to compare for inequality.</param>
/// <param name="b">A FixedString<#=OTHERBYTES#>Bytes to compare for inequality.</param>
/// <returns>True if the two strings are unequal.</returns>
public static bool operator !=(in FixedString<#=BYTES#>Bytes a, in FixedString<#=OTHERBYTES#>Bytes b)
{
return !(a == b);
}
/// <summary>
/// Returns true if this string and another string are equal.
/// </summary>
/// <remarks>Two strings are equal if they have equal length and all their characters match.</remarks>
/// <param name="other">A FixedString<#=OTHERBYTES#>Bytes to compare for equality.</param>
/// <returns>True if the two strings are equal.</returns>
public bool Equals(FixedString<#=OTHERBYTES#>Bytes other)
{
return this == other;
}
<#
if (OTHERBYTES > BYTES)
{
// Generate implicit conversions to bigger-sized FixedStrings
#>
/// <summary>
/// Returns a new FixedString<#=OTHERBYTES#>Bytes that is a copy of another string.
/// </summary>
/// <param name="fs">A FixedString<#=BYTES#>Bytes to copy.</param>
/// <returns>A new FixedString<#=OTHERBYTES#>Bytes that is a copy of the other string.</returns>
/// <exception cref="ArgumentException">Thrown if the string to copy's length exceeds the capacity of FixedString<#=OTHERBYTES#>Bytes.</exception>
public static implicit operator FixedString<#=OTHERBYTES#>Bytes(in FixedString<#=BYTES#>Bytes fs) => new FixedString<#=OTHERBYTES#>Bytes(in fs);
<#
}
}
#>
/// <summary>
/// Returns true if a FixedString<#=BYTES#>Bytes and another string are equal.
/// </summary>
/// <remarks>Two strings are equal if they have equal length and all their characters match.</remarks>
/// <param name="a">A `FixedString<#=BYTES#>Bytes` to compare for equality.</param>
/// <param name="b">A `String` to compare for equality.</param>
/// <returns>True if the two strings are equal.</returns>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public static bool operator ==(in FixedString<#=BYTES#>Bytes a, String b)
{
var isManaged = false;
var equal = false;
EqualsManagedString(in a, b ?? "", ref isManaged, ref equal);
if (isManaged)
return equal;
return a == (FixedString<#=BYTES#>Bytes)(b == null ? "" : b);
}
[BurstDiscard]
[ExcludeFromBurstCompatTesting("Takes managed string")]
static unsafe void EqualsManagedString(in FixedString<#=BYTES#>Bytes a, String b, ref bool isManaged, ref bool equal)
{
isManaged = true;
var aptr = (byte*)UnsafeUtilityExtensions.AddressOf(a.bytes);
equal = UTF8ArrayUnsafeUtility.EqualsManagedString(aptr, a.utf8LengthInBytes, b);
}
/// <summary>
/// Returns true if a FixedString<#=BYTES#>Bytes and another string are not equal.
/// </summary>
/// <remarks>Two strings are equal if they have equal length and all their characters match.</remarks>
/// <param name="a">A `FixedString<#=BYTES#>Bytes` to compare for equality.</param>
/// <param name="b">A `String` to compare for equality.</param>
/// <returns>True if the two strings are not equal.</returns>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public static bool operator !=(in FixedString<#=BYTES#>Bytes a, String b) => !(a == b);
/// <summary>
/// Returns true if a string and a FixedString<#=BYTES#>Bytes are equal.
/// </summary>
/// <remarks>Two strings are equal if they have equal length and all their characters match.</remarks>
/// <param name="a">A `String` to compare for equality.</param>
/// <param name="b">A `FixedString<#=BYTES#>Bytes` to compare for equality.</param>
/// <returns>True if the two strings are equal.</returns>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public static bool operator ==(String a, in FixedString<#=BYTES#>Bytes b) => b == a;
/// <summary>
/// Returns true if a string and a FixedString<#=BYTES#>Bytes are not equal.
/// </summary>
/// <remarks>Two strings are equal if they have equal length and all their characters match.</remarks>
/// <param name="a">A `String` to compare for equality.</param>
/// <param name="b">A `FixedString<#=BYTES#>Bytes` to compare for equality.</param>
/// <returns>True if the two strings are not equal.</returns>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public static bool operator !=(String a, in FixedString<#=BYTES#>Bytes b) => !(b == a);
/// <summary>
/// Returns a new FixedString<#=BYTES#>Bytes that is a copy of another string.
/// </summary>
/// <param name="b">A string to copy.</param>
/// <returns>A new FixedString<#=BYTES#>Bytes that is a copy of another string.</returns>
/// <exception cref="ArgumentException">Thrown if the string to copy's length exceeds the capacity of FixedString<#=BYTES#>Bytes.</exception>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public static implicit operator FixedString<#=BYTES#>Bytes(string b) => new FixedString<#=BYTES#>Bytes(b);
/// <summary>
/// Returns a new managed string that is a copy of this string.
/// </summary>
/// <returns>A new managed string that is a copy of this string.</returns>
[ExcludeFromBurstCompatTesting("Returns managed string")]
public override String ToString()
{
return this.ConvertToString();
}
/// <summary>
/// Returns a hash code of this string.
/// </summary>
/// <remarks>Only the character bytes are included in the hash: any bytes beyond <see cref="Length"/> are not part of the hash.</remarks>
/// <returns>The hash code of this string.</returns>
public override int GetHashCode()
{
return this.ComputeHashCode();
}
/// <summary>
/// Returns true if this string and an object are equal.
/// </summary>
/// <remarks>
/// Returns false if the object is neither a System.String or a FixedString.
///
/// Two strings are equal if they have equal length and all their characters match.</remarks>
/// <param name="obj">An object to compare for equality.</param>
/// <returns>True if this string and the object are equal.</returns>
[ExcludeFromBurstCompatTesting("Takes managed object")]
public override bool Equals(object obj)
{
if(ReferenceEquals(null, obj)) return false;
if(obj is String aString) return Equals(aString);
<#
foreach(var OTHERBYTES in SIZES)
{
var OTHERTYPENAME = "FixedString" + OTHERBYTES + "Bytes";
WriteLine(" if(obj is {0} a{0}) return Equals(a{0});", OTHERTYPENAME);
}
#>
return false;
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckIndexInRange(int index)
{
if (index < 0)
throw new IndexOutOfRangeException($"Index {index} must be positive.");
if (index >= utf8LengthInBytes)
throw new IndexOutOfRangeException($"Index {index} is out of range in FixedString<#=BYTES#>Bytes of '{utf8LengthInBytes}' Length.");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckLengthInRange(int length)
{
if (length < 0)
throw new ArgumentOutOfRangeException($"Length {length} must be positive.");
if (length > utf8MaxLengthInBytes)
throw new ArgumentOutOfRangeException($"Length {length} is out of range in FixedString<#=BYTES#>Bytes of '{utf8MaxLengthInBytes}' Capacity.");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckCapacityInRange(int capacity)
{
if (capacity > utf8MaxLengthInBytes)
throw new ArgumentOutOfRangeException($"Capacity {capacity} must be lower than {utf8MaxLengthInBytes}.");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void CheckCopyError(CopyError error, String source)
{
if (error != CopyError.None)
throw new ArgumentException($"FixedString<#=BYTES#>Bytes: {error} while copying \"{source}\"");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void CheckFormatError(FormatError error)
{
if (error != FormatError.None)
throw new ArgumentException("Source is too long to fit into fixed string of this size");
}
}
<#}}#>
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 0a845769eb1dc4f459f64e5c840d07de
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,450 @@
using Unity.Collections.LowLevel.Unsafe;
namespace Unity.Collections
{
/// <summary>
/// Provides extension methods for FixedString*N*Bytes.
/// </summary>
[GenerateTestsForBurstCompatibility]
public unsafe static partial class FixedStringMethods
{
/// <summary>
/// Appends a Unicode.Rune to this string.
/// </summary>
/// <typeparam name="T">The type of FixedString*N*Bytes.</typeparam>
/// <param name="fs">A FixedString*N*Bytes.</param>
/// <param name="rune">A Unicode.Rune to append.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static FormatError Append<T>(ref this T fs, Unicode.Rune rune)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
var len = fs.Length;
var runeLen = rune.LengthInUtf8Bytes();
if (!fs.TryResize(len + runeLen, NativeArrayOptions.UninitializedMemory))
return FormatError.Overflow;
return fs.Write(ref len, rune);
}
/// <summary>
/// Appends a char to this string.
/// </summary>
/// <typeparam name="T">The type of FixedString*N*Bytes.</typeparam>
/// <param name="fs">A FixedString*N*Bytes.</param>
/// <param name="ch">A char to append.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static FormatError Append<T>(ref this T fs, char ch)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
return fs.Append((Unicode.Rune) ch);
}
/// <summary>
/// Appends a byte to this string.
/// </summary>
/// <remarks>
/// No validation is performed: it is your responsibility for the data to be valid UTF-8 when you're done appending bytes.
/// </remarks>
/// <typeparam name="T">The type of FixedString*N*Bytes.</typeparam>
/// <param name="fs">A FixedString*N*Bytes.</param>
/// <param name="a">A byte to append.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static FormatError AppendRawByte<T>(ref this T fs, byte a)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
var origLength = fs.Length;
if (!fs.TryResize(origLength + 1, NativeArrayOptions.UninitializedMemory))
return FormatError.Overflow;
fs.GetUnsafePtr()[origLength] = a;
return FormatError.None;
}
/// <summary>
/// Appends a Unicode.Rune a number of times to this string.
/// </summary>
/// <typeparam name="T">The type of FixedString*N*Bytes.</typeparam>
/// <param name="fs">A FixedString*N*Bytes.</param>
/// <param name="rune">A Unicode.Rune to append some number of times.</param>
/// <param name="count">The number of times to append the rune.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static FormatError Append<T>(ref this T fs, Unicode.Rune rune, int count)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
var origLength = fs.Length;
if (!fs.TryResize(origLength + rune.LengthInUtf8Bytes() * count, NativeArrayOptions.UninitializedMemory))
return FormatError.Overflow;
var cap = fs.Capacity;
var b = fs.GetUnsafePtr();
int offset = origLength;
for (int i = 0; i < count; ++i)
{
var error = Unicode.UcsToUtf8(b, ref offset, cap, rune);
if (error != ConversionError.None)
return FormatError.Overflow;
}
return FormatError.None;
}
/// <summary>
/// Appends a number (converted to UTF-8 characters) to this string.
/// </summary>
/// <typeparam name="T">The type of FixedString*N*Bytes.</typeparam>
/// <param name="fs">A FixedString*N*Bytes.</param>
/// <param name="input">A long integer to append to the string.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static FormatError Append<T>(ref this T fs, long input)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
const int maximumDigits = 20;
var temp = stackalloc byte[maximumDigits];
int offset = maximumDigits;
if (input >= 0)
{
do
{
var digit = (byte)(input % 10);
temp[--offset] = (byte)('0' + digit);
input /= 10;
}
while (input != 0);
}
else
{
do
{
var digit = (byte)(input % 10);
temp[--offset] = (byte)('0' - digit);
input /= 10;
}
while (input != 0);
temp[--offset] = (byte)'-';
}
return fs.Append(temp + offset, maximumDigits - offset);
}
/// <summary>
/// Appends a number (converted to UTF-8 characters) to this string.
/// </summary>
/// <typeparam name="T">The type of FixedString*N*Bytes.</typeparam>
/// <param name="fs">A FixedString*N*Bytes.</param>
/// <param name="input">An int to append to the string.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static FormatError Append<T>(ref this T fs, int input)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
return fs.Append((long)input);
}
/// <summary>
/// Appends a number (converted to UTF-8 characters) to this string.
/// </summary>
/// <typeparam name="T">The type of FixedString*N*Bytes.</typeparam>
/// <param name="fs">A FixedString*N*Bytes.</param>
/// <param name="input">A ulong integer to append to the string.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static FormatError Append<T>(ref this T fs, ulong input)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
const int maximumDigits = 20;
var temp = stackalloc byte[maximumDigits];
int offset = maximumDigits;
do
{
var digit = (byte)(input % 10);
temp[--offset] = (byte)('0' + digit);
input /= 10;
}
while (input != 0);
return fs.Append(temp + offset, maximumDigits - offset);
}
/// <summary>
/// Appends a number (converted to UTF-8 characters) to this string.
/// </summary>
/// <typeparam name="T">The type of FixedString*N*Bytes.</typeparam>
/// <param name="fs">A FixedString*N*Bytes.</param>
/// <param name="input">A uint to append to the string.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static FormatError Append<T>(ref this T fs, uint input)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
return fs.Append((ulong)input);
}
/// <summary>
/// Appends a number (converted to UTF-8 characters) to this string.
/// </summary>
/// <typeparam name="T">The type of FixedString*N*Bytes.</typeparam>
/// <param name="fs">A FixedString*N*Bytes.</param>
/// <param name="input">A float to append to the string.</param>
/// <param name="decimalSeparator">The character to use as the decimal separator. Defaults to a period ('.').</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static FormatError Append<T>(ref this T fs, float input, char decimalSeparator = '.')
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
FixedStringUtils.UintFloatUnion ufu = new FixedStringUtils.UintFloatUnion();
ufu.floatValue = input;
var sign = ufu.uintValue >> 31;
ufu.uintValue &= ~(1 << 31);
FormatError error;
if ((ufu.uintValue & 0x7F800000) == 0x7F800000)
{
if (ufu.uintValue == 0x7F800000)
{
if (sign != 0 && ((error = fs.Append('-')) != FormatError.None))
return error;
return fs.Append('I', 'n', 'f', 'i', 'n', 'i', 't', 'y');
}
return fs.Append('N', 'a', 'N');
}
if (sign != 0 && ufu.uintValue != 0) // C# prints -0 as 0
if ((error = fs.Append('-')) != FormatError.None)
return error;
ulong decimalMantissa = 0;
int decimalExponent = 0;
FixedStringUtils.Base2ToBase10(ref decimalMantissa, ref decimalExponent, ufu.floatValue);
var backwards = stackalloc char[9];
int decimalDigits = 0;
do
{
if (decimalDigits >= 9)
return FormatError.Overflow;
var decimalDigit = decimalMantissa % 10;
backwards[8 - decimalDigits++] = (char)('0' + decimalDigit);
decimalMantissa /= 10;
}
while (decimalMantissa > 0);
char *ascii = backwards + 9 - decimalDigits;
var leadingZeroes = -decimalExponent - decimalDigits + 1;
if (leadingZeroes > 0)
{
if (leadingZeroes > 4)
return fs.AppendScientific(ascii, decimalDigits, decimalExponent, decimalSeparator);
if ((error = fs.Append('0', decimalSeparator)) != FormatError.None)
return error;
--leadingZeroes;
while (leadingZeroes > 0)
{
if ((error = fs.Append('0')) != FormatError.None)
return error;
--leadingZeroes;
}
for (var i = 0; i < decimalDigits; ++i)
{
if ((error = fs.Append(ascii[i])) != FormatError.None)
return error;
}
return FormatError.None;
}
var trailingZeroes = decimalExponent;
if (trailingZeroes > 0)
{
if (trailingZeroes > 4)
return fs.AppendScientific(ascii, decimalDigits, decimalExponent, decimalSeparator);
for (var i = 0; i < decimalDigits; ++i)
{
if ((error = fs.Append(ascii[i])) != FormatError.None)
return error;
}
while (trailingZeroes > 0)
{
if ((error = fs.Append('0')) != FormatError.None)
return error;
--trailingZeroes;
}
return FormatError.None;
}
var indexOfSeparator = decimalDigits + decimalExponent;
for (var i = 0; i < decimalDigits; ++i)
{
if (i == indexOfSeparator)
if ((error = fs.Append(decimalSeparator)) != FormatError.None)
return error;
if ((error = fs.Append(ascii[i])) != FormatError.None)
return error;
}
return FormatError.None;
}
/// <summary>
/// Appends another string to this string.
/// </summary>
/// <remarks>
/// When the method returns an error, the destination string is not modified.
/// </remarks>
/// <typeparam name="T">The type of the destination string.</typeparam>
/// <typeparam name="T2">The type of the source string.</typeparam>
/// <param name="fs">The destination string.</param>
/// <param name="input">The source string.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the destination string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes), typeof(FixedString128Bytes) })]
public static FormatError Append<T,T2>(ref this T fs, in T2 input)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var inputRef = ref UnsafeUtilityExtensions.AsRef(input);
return fs.Append(inputRef.GetUnsafePtr(), inputRef.Length);
}
/// <summary>
/// Copies another string to this string (making the two strings equal).
/// </summary>
/// <remarks>
/// When the method returns an error, the destination string is not modified.
/// </remarks>
/// <typeparam name="T">The type of the destination string.</typeparam>
/// <typeparam name="T2">The type of the source string.</typeparam>
/// <param name="fs">The destination string.</param>
/// <param name="input">The source string.</param>
/// <returns>CopyError.None if successful. Returns CopyError.Truncation if the source string is too large to fit in the destination.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes), typeof(FixedString128Bytes) })]
public static CopyError CopyFrom<T, T2>(ref this T fs, in T2 input)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
{
fs.Length = 0;
var fe = Append(ref fs, input);
if (fe != FormatError.None)
return CopyError.Truncation;
return CopyError.None;
}
/// <summary>
/// Appends bytes to this string.
/// </summary>
/// <remarks>
/// When the method returns an error, the destination string is not modified.
///
/// No validation is performed: it is your responsibility for the destination to contain valid UTF-8 when you're done appending bytes.
/// </remarks>
/// <typeparam name="T">The type of the destination string.</typeparam>
/// <param name="fs">The destination string.</param>
/// <param name="utf8Bytes">The bytes to append.</param>
/// <param name="utf8BytesLength">The number of bytes to append.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the destination string is exceeded.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public unsafe static FormatError Append<T>(ref this T fs, byte* utf8Bytes, int utf8BytesLength)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
var origLength = fs.Length;
if (!fs.TryResize(origLength + utf8BytesLength, NativeArrayOptions.UninitializedMemory))
return FormatError.Overflow;
UnsafeUtility.MemCpy(fs.GetUnsafePtr() + origLength, utf8Bytes, utf8BytesLength);
return FormatError.None;
}
/// <summary>
/// Appends another string to this string.
/// </summary>
/// <remarks>
/// When the method returns an error, the destination string is not modified.
/// </remarks>
/// <typeparam name="T">The type of the destination string.</typeparam>
/// <param name="fs">The destination string.</param>
/// <param name="s">The string to append.</param>
/// <returns>FormatError.None if successful. Returns FormatError.Overflow if the capacity of the destination string is exceeded.</returns>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public unsafe static FormatError Append<T>(ref this T fs, string s)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
// we don't know how big the expansion from UTF16 to UTF8 will be, so we account for worst case.
int worstCaseCapacity = s.Length * 4;
byte* utf8Bytes = stackalloc byte[worstCaseCapacity];
int utf8Len;
fixed (char* chars = s)
{
var err = UTF8ArrayUnsafeUtility.Copy(utf8Bytes, out utf8Len, worstCaseCapacity, chars, s.Length);
if (err != CopyError.None)
{
return FormatError.Overflow;
}
}
return fs.Append(utf8Bytes, utf8Len);
}
/// <summary>
/// Copies another string to this string (making the two strings equal).
/// Replaces any existing content of the FixedString.
/// </summary>
/// <remarks>
/// When the method returns an error, the destination string is not modified.
/// </remarks>
/// <typeparam name="T">The type of the destination string.</typeparam>
/// <param name="fs">The destination string.</param>
/// <param name="s">The source string.</param>
/// <returns>CopyError.None if successful. Returns CopyError.Truncation if the source string is too large to fit in the destination.</returns>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public static CopyError CopyFrom<T>(ref this T fs, string s)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
fs.Length = 0;
var fe = Append(ref fs, s);
if (fe != FormatError.None)
return CopyError.Truncation;
return CopyError.None;
}
/// <summary>
/// Copies another string to this string. If the string exceeds the capacity it will be truncated.
/// Replaces any existing content of the FixedString.
/// </summary>
/// <typeparam name="T">The type of the destination string.</typeparam>
/// <param name="fs">The destination string.</param>
/// <param name="s">The source string.</param>
/// <returns>CopyError.None if successful. Returns CopyError.Truncation if the source string is too large to fit in the destination.</returns>
[ExcludeFromBurstCompatTesting("Takes managed string")]
public static CopyError CopyFromTruncated<T>(ref this T fs, string s)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
if (s == null)
{
fs.Length = 0;
return CopyError.None;
}
int utf8Len;
fixed (char* chars = s)
{
var error = UTF8ArrayUnsafeUtility.Copy(fs.GetUnsafePtr(), out utf8Len, fs.Capacity, chars, s.Length);
fs.Length = utf8Len;
return error;
}
}
/// <summary>
/// Copies another string to this string. If the string exceeds the capacity it will be truncated.
/// </summary>
/// <remarks>
/// When the method returns an error, the destination string is not modified.
/// </remarks>
/// <typeparam name="T">The type of the destination string.</typeparam>
/// <typeparam name="T2">The type of the source string.</typeparam>
/// <param name="fs">The destination string.</param>
/// <param name="input">The source string.</param>
/// <returns>CopyError.None if successful. Returns CopyError.Truncation if the source string is too large to fit in the destination.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes), typeof(FixedString128Bytes) })]
public static CopyError CopyFromTruncated<T, T2>(ref this T fs, in T2 input)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
{
var error = UTF8ArrayUnsafeUtility.Copy(fs.GetUnsafePtr(), out int utf8Len, fs.Capacity, input.GetUnsafePtr(), input.Length);
fs.Length = utf8Len;
return error;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b3d1c84db8ef4e288ba9089a616a3523
timeCreated: 1591061243
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 66f7a4570af244dfacfded8cc0c60aec
timeCreated: 1593669547
@@ -0,0 +1,168 @@
<#/*THIS IS A T4 FILE - see t4_text_templating.md for what it is and how to run codegen*/#>
<#@ template debug="True" #>
<#@ output extension=".gen.cs" encoding="utf-8" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Reflection" #>
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// t4 Samples/Packages/com.unity.collections/Unity.Collections/FixedStringFormat.tt
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Internal;
<#
List<List<T>> AllCombinationsOf<T>(List<List<T>> sets)
{
// need array bounds checking etc for production
var combinations = new List<List<T>>();
// prime the data
foreach (var value in sets[0])
combinations.Add(new List<T> { value });
foreach (var set in sets.Skip(1))
combinations = AddExtraSet(combinations, set);
return combinations;
}
List<List<T>> AddExtraSet<T>(List<List<T>> combinations, List<T> set)
{
var newCombinations = from value in set
from combination in combinations
select new List<T>(combination) { value };
return newCombinations.ToList();
}
string WithCommas(IEnumerable<string> input)
{
return string.Join(", ", input);
}
var ARGTYPES = new[] { "int", "float", "string", "FixedStringN", null };
var ARGCOUNT = 4;
var ARGSETS = new List<List<string>>();
for (int i = 0; i < ARGCOUNT; ++i)
ARGSETS.Add(ARGTYPES.ToList());
var ARGCOMBOS = AllCombinationsOf(ARGSETS);
#>
namespace Unity.Collections
{
/// <summary>
/// Provides formatting methods for FixedString*N*.
/// </summary>
[GenerateTestsForBurstCompatibility]
public static class FixedString
{
<#
foreach (var COMBO in ARGCOMBOS)
{
while (COMBO.Count != 0 && COMBO.Last() == null)
COMBO.RemoveAt(COMBO.Count - 1);
if (COMBO.Count == 0 || COMBO.IndexOf(null) != -1)
continue;
var numFixedStringN = COMBO.Count((s) => s == "FixedStringN");
// turn FixedStringN into T1..Tn
var GENERICSPARAM = "";
var BCOMPAT = "";
if (COMBO.Contains("string"))
{
BCOMPAT = "[ExcludeFromBurstCompatTesting(\"Takes managed string\")]";
}
var GENERICSCONSTRAINT = new StringBuilder();
var TxDOCS = new StringBuilder();
if (numFixedStringN > 0)
{
GENERICSPARAM = $"<{string.Join(",", Enumerable.Range(1, numFixedStringN).Select((n) => $"T{n}"))}>";
if (!COMBO.Contains("string"))
{
BCOMPAT = $"[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] {{ {string.Join(", ", Enumerable.Range(1, numFixedStringN).Select((n) => $"typeof(FixedString32Bytes /*$T{n}*/)"))} }} )]";
}
for (int i = 0; i < numFixedStringN; ++i)
{
var index = COMBO.IndexOf("FixedStringN");
COMBO[index] = $"T{i + 1}";
GENERICSCONSTRAINT.Append($" where T{i + 1} : unmanaged, INativeList<byte>, IUTF8Bytes\n");
TxDOCS.Append($" /// <typeparam name=\"T{i + 1}\"><undoc /></typeparam>\r\n");
}
}
var ARGS = Enumerable.Range(0, COMBO.Count).Select((n) => $"{COMBO[n]} arg{n}");
var ARGNAMES = Enumerable.Range(0, COMBO.Count).Select((n) => $"arg{n}").ToList();
var CONVERSIONS = new StringBuilder();
for (int i = 0; i < COMBO.Count; ++i)
{
if (COMBO[i].StartsWith("T"))
continue;
CONVERSIONS.Append($" FixedString32Bytes carg{i} = default; carg{i}.Append(arg{i});\n");
ARGNAMES[i] = $"carg{i}";
}
var RETURNTYPE = "FixedString128Bytes";
if (COMBO.Count > 3)
RETURNTYPE = "FixedString512Bytes";
var ARGxDOCS = String.Join("\r\n /// ", Enumerable.Range(0, COMBO.Count).Select(n => $"<param name=\"arg{n}\">Value to interpolate into the format string.</param>"));
#>
/// <summary>
/// Returns a new string produced by interpolating a format string.
/// </summary>
/// <remarks>
/// Similar to StringBuilder.AppendFormat but with significant limitations:
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The various overloads of this method take up to four values for interpolation. The allowed argument types are:
/// - FixedString*N*Bytes
/// - string
/// - int
/// - float
/// - structs implementing INativeList&lt;byte&gt; and IUTF8Bytes
///
/// <seealso cref="FixedStringMethods.AppendFormat"/>
/// </remarks>
/// <param name="formatString">The format string.</param>
<#=TxDOCS#>
/// <#=ARGxDOCS#>
/// <returns>A new string produced by interpolating the format string.</returns>
<#=BCOMPAT#>
public static <#=RETURNTYPE#> Format<#=GENERICSPARAM#>(<#=RETURNTYPE#> formatString, <#=WithCommas(ARGS)#>)
<#=GENERICSCONSTRAINT#>
{
<#=RETURNTYPE#> result = default;
<#=CONVERSIONS#>
result.AppendFormat(formatString, <#=WithCommas(ARGNAMES)#>);
return result;
}
<#
}
#>
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 059659011adc4f67a43b9d9bcc5dfd01
timeCreated: 1593668361
@@ -0,0 +1,945 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// t4 Samples/Packages/com.unity.collections/Unity.Collections/FixedStringFormatMethods.tt
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using Unity.Collections.LowLevel.Unsafe;
namespace Unity.Collections
{
/// <summary>
/// Provides extension methods for FixedString*N*Bytes.
/// </summary>
public unsafe static partial class FixedStringMethods
{
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="T0">The type of value to interpolate into the format string.</typeparam>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <param name="arg0">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), typeof(FixedString128Bytes /*T0*/) })]
public static unsafe FormatError AppendFormat<T, U, T0>(ref this T dest, in U format, in T0 arg0)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
where T0 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
case 0: err = dest.Append(in arg0); break;
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="T0">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T1">The type of value to interpolate into the format string.</typeparam>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <param name="arg0">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg1">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), typeof(FixedString128Bytes /*T0*/), typeof(FixedString128Bytes /*T1*/) })]
public static unsafe FormatError AppendFormat<T, U, T0, T1>(ref this T dest, in U format, in T0 arg0, in T1 arg1)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
where T0 : unmanaged, INativeList<byte>, IUTF8Bytes
where T1 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
case 0: err = dest.Append(in arg0); break;
case 1: err = dest.Append(in arg1); break;
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="T0">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T1">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T2">The type of value to interpolate into the format string.</typeparam>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <param name="arg0">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg1">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg2">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), typeof(FixedString128Bytes /*T0*/), typeof(FixedString128Bytes /*T1*/), typeof(FixedString128Bytes /*T2*/) })]
public static unsafe FormatError AppendFormat<T, U, T0, T1, T2>(ref this T dest, in U format, in T0 arg0, in T1 arg1, in T2 arg2)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
where T0 : unmanaged, INativeList<byte>, IUTF8Bytes
where T1 : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
case 0: err = dest.Append(in arg0); break;
case 1: err = dest.Append(in arg1); break;
case 2: err = dest.Append(in arg2); break;
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="T0">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T1">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T2">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T3">The type of value to interpolate into the format string.</typeparam>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <param name="arg0">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg1">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg2">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg3">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), typeof(FixedString128Bytes /*T0*/), typeof(FixedString128Bytes /*T1*/), typeof(FixedString128Bytes /*T2*/), typeof(FixedString128Bytes /*T3*/) })]
public static unsafe FormatError AppendFormat<T, U, T0, T1, T2, T3>(ref this T dest, in U format, in T0 arg0, in T1 arg1, in T2 arg2, in T3 arg3)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
where T0 : unmanaged, INativeList<byte>, IUTF8Bytes
where T1 : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
where T3 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
case 0: err = dest.Append(in arg0); break;
case 1: err = dest.Append(in arg1); break;
case 2: err = dest.Append(in arg2); break;
case 3: err = dest.Append(in arg3); break;
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="T0">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T1">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T2">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T3">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T4">The type of value to interpolate into the format string.</typeparam>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <param name="arg0">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg1">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg2">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg3">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg4">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), typeof(FixedString128Bytes /*T0*/), typeof(FixedString128Bytes /*T1*/), typeof(FixedString128Bytes /*T2*/), typeof(FixedString128Bytes /*T3*/), typeof(FixedString128Bytes /*T4*/) })]
public static unsafe FormatError AppendFormat<T, U, T0, T1, T2, T3, T4>(ref this T dest, in U format, in T0 arg0, in T1 arg1, in T2 arg2, in T3 arg3, in T4 arg4)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
where T0 : unmanaged, INativeList<byte>, IUTF8Bytes
where T1 : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
where T3 : unmanaged, INativeList<byte>, IUTF8Bytes
where T4 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
case 0: err = dest.Append(in arg0); break;
case 1: err = dest.Append(in arg1); break;
case 2: err = dest.Append(in arg2); break;
case 3: err = dest.Append(in arg3); break;
case 4: err = dest.Append(in arg4); break;
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="T0">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T1">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T2">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T3">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T4">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T5">The type of value to interpolate into the format string.</typeparam>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <param name="arg0">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg1">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg2">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg3">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg4">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg5">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), typeof(FixedString128Bytes /*T0*/), typeof(FixedString128Bytes /*T1*/), typeof(FixedString128Bytes /*T2*/), typeof(FixedString128Bytes /*T3*/), typeof(FixedString128Bytes /*T4*/), typeof(FixedString128Bytes /*T5*/) })]
public static unsafe FormatError AppendFormat<T, U, T0, T1, T2, T3, T4, T5>(ref this T dest, in U format, in T0 arg0, in T1 arg1, in T2 arg2, in T3 arg3, in T4 arg4, in T5 arg5)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
where T0 : unmanaged, INativeList<byte>, IUTF8Bytes
where T1 : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
where T3 : unmanaged, INativeList<byte>, IUTF8Bytes
where T4 : unmanaged, INativeList<byte>, IUTF8Bytes
where T5 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
case 0: err = dest.Append(in arg0); break;
case 1: err = dest.Append(in arg1); break;
case 2: err = dest.Append(in arg2); break;
case 3: err = dest.Append(in arg3); break;
case 4: err = dest.Append(in arg4); break;
case 5: err = dest.Append(in arg5); break;
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="T0">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T1">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T2">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T3">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T4">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T5">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T6">The type of value to interpolate into the format string.</typeparam>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <param name="arg0">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg1">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg2">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg3">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg4">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg5">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg6">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), typeof(FixedString128Bytes /*T0*/), typeof(FixedString128Bytes /*T1*/), typeof(FixedString128Bytes /*T2*/), typeof(FixedString128Bytes /*T3*/), typeof(FixedString128Bytes /*T4*/), typeof(FixedString128Bytes /*T5*/), typeof(FixedString128Bytes /*T6*/) })]
public static unsafe FormatError AppendFormat<T, U, T0, T1, T2, T3, T4, T5, T6>(ref this T dest, in U format, in T0 arg0, in T1 arg1, in T2 arg2, in T3 arg3, in T4 arg4, in T5 arg5, in T6 arg6)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
where T0 : unmanaged, INativeList<byte>, IUTF8Bytes
where T1 : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
where T3 : unmanaged, INativeList<byte>, IUTF8Bytes
where T4 : unmanaged, INativeList<byte>, IUTF8Bytes
where T5 : unmanaged, INativeList<byte>, IUTF8Bytes
where T6 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
case 0: err = dest.Append(in arg0); break;
case 1: err = dest.Append(in arg1); break;
case 2: err = dest.Append(in arg2); break;
case 3: err = dest.Append(in arg3); break;
case 4: err = dest.Append(in arg4); break;
case 5: err = dest.Append(in arg5); break;
case 6: err = dest.Append(in arg6); break;
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="T0">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T1">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T2">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T3">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T4">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T5">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T6">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T7">The type of value to interpolate into the format string.</typeparam>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <param name="arg0">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg1">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg2">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg3">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg4">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg5">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg6">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg7">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), typeof(FixedString128Bytes /*T0*/), typeof(FixedString128Bytes /*T1*/), typeof(FixedString128Bytes /*T2*/), typeof(FixedString128Bytes /*T3*/), typeof(FixedString128Bytes /*T4*/), typeof(FixedString128Bytes /*T5*/), typeof(FixedString128Bytes /*T6*/), typeof(FixedString128Bytes /*T7*/) })]
public static unsafe FormatError AppendFormat<T, U, T0, T1, T2, T3, T4, T5, T6, T7>(ref this T dest, in U format, in T0 arg0, in T1 arg1, in T2 arg2, in T3 arg3, in T4 arg4, in T5 arg5, in T6 arg6, in T7 arg7)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
where T0 : unmanaged, INativeList<byte>, IUTF8Bytes
where T1 : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
where T3 : unmanaged, INativeList<byte>, IUTF8Bytes
where T4 : unmanaged, INativeList<byte>, IUTF8Bytes
where T5 : unmanaged, INativeList<byte>, IUTF8Bytes
where T6 : unmanaged, INativeList<byte>, IUTF8Bytes
where T7 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
case 0: err = dest.Append(in arg0); break;
case 1: err = dest.Append(in arg1); break;
case 2: err = dest.Append(in arg2); break;
case 3: err = dest.Append(in arg3); break;
case 4: err = dest.Append(in arg4); break;
case 5: err = dest.Append(in arg5); break;
case 6: err = dest.Append(in arg6); break;
case 7: err = dest.Append(in arg7); break;
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="T0">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T1">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T2">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T3">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T4">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T5">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T6">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T7">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T8">The type of value to interpolate into the format string.</typeparam>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <param name="arg0">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg1">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg2">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg3">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg4">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg5">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg6">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg7">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg8">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), typeof(FixedString128Bytes /*T0*/), typeof(FixedString128Bytes /*T1*/), typeof(FixedString128Bytes /*T2*/), typeof(FixedString128Bytes /*T3*/), typeof(FixedString128Bytes /*T4*/), typeof(FixedString128Bytes /*T5*/), typeof(FixedString128Bytes /*T6*/), typeof(FixedString128Bytes /*T7*/), typeof(FixedString128Bytes /*T8*/) })]
public static unsafe FormatError AppendFormat<T, U, T0, T1, T2, T3, T4, T5, T6, T7, T8>(ref this T dest, in U format, in T0 arg0, in T1 arg1, in T2 arg2, in T3 arg3, in T4 arg4, in T5 arg5, in T6 arg6, in T7 arg7, in T8 arg8)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
where T0 : unmanaged, INativeList<byte>, IUTF8Bytes
where T1 : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
where T3 : unmanaged, INativeList<byte>, IUTF8Bytes
where T4 : unmanaged, INativeList<byte>, IUTF8Bytes
where T5 : unmanaged, INativeList<byte>, IUTF8Bytes
where T6 : unmanaged, INativeList<byte>, IUTF8Bytes
where T7 : unmanaged, INativeList<byte>, IUTF8Bytes
where T8 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
case 0: err = dest.Append(in arg0); break;
case 1: err = dest.Append(in arg1); break;
case 2: err = dest.Append(in arg2); break;
case 3: err = dest.Append(in arg3); break;
case 4: err = dest.Append(in arg4); break;
case 5: err = dest.Append(in arg5); break;
case 6: err = dest.Append(in arg6); break;
case 7: err = dest.Append(in arg7); break;
case 8: err = dest.Append(in arg8); break;
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="T0">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T1">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T2">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T3">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T4">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T5">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T6">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T7">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T8">The type of value to interpolate into the format string.</typeparam>
/// <typeparam name="T9">The type of value to interpolate into the format string.</typeparam>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <param name="arg0">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg1">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg2">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg3">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg4">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg5">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg6">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg7">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg8">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <param name="arg9">A FixedString*N*Bytes to interpolate into the format string.</param>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), typeof(FixedString128Bytes /*T0*/), typeof(FixedString128Bytes /*T1*/), typeof(FixedString128Bytes /*T2*/), typeof(FixedString128Bytes /*T3*/), typeof(FixedString128Bytes /*T4*/), typeof(FixedString128Bytes /*T5*/), typeof(FixedString128Bytes /*T6*/), typeof(FixedString128Bytes /*T7*/), typeof(FixedString128Bytes /*T8*/), typeof(FixedString128Bytes /*T9*/) })]
public static unsafe FormatError AppendFormat<T, U, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9>(ref this T dest, in U format, in T0 arg0, in T1 arg1, in T2 arg2, in T3 arg3, in T4 arg4, in T5 arg5, in T6 arg6, in T7 arg7, in T8 arg8, in T9 arg9)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
where T0 : unmanaged, INativeList<byte>, IUTF8Bytes
where T1 : unmanaged, INativeList<byte>, IUTF8Bytes
where T2 : unmanaged, INativeList<byte>, IUTF8Bytes
where T3 : unmanaged, INativeList<byte>, IUTF8Bytes
where T4 : unmanaged, INativeList<byte>, IUTF8Bytes
where T5 : unmanaged, INativeList<byte>, IUTF8Bytes
where T6 : unmanaged, INativeList<byte>, IUTF8Bytes
where T7 : unmanaged, INativeList<byte>, IUTF8Bytes
where T8 : unmanaged, INativeList<byte>, IUTF8Bytes
where T9 : unmanaged, INativeList<byte>, IUTF8Bytes
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
case 0: err = dest.Append(in arg0); break;
case 1: err = dest.Append(in arg1); break;
case 2: err = dest.Append(in arg2); break;
case 3: err = dest.Append(in arg3); break;
case 4: err = dest.Append(in arg4); break;
case 5: err = dest.Append(in arg5); break;
case 6: err = dest.Append(in arg6); break;
case 7: err = dest.Append(in arg7); break;
case 8: err = dest.Append(in arg8); break;
case 9: err = dest.Append(in arg9); break;
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 89f65fb005504fceb04727480e65f16c
timeCreated: 1591061827
@@ -0,0 +1,125 @@
<#/*THIS IS A T4 FILE - see t4_text_templating.md for what it is and how to run codegen*/#>
<#@ template debug="True" #>
<#@ output extension=".gen.cs" encoding="utf-8" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// t4 Samples/Packages/com.unity.collections/Unity.Collections/FixedStringFormatMethods.tt
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using Unity.Collections.LowLevel.Unsafe;
namespace Unity.Collections
{
/// <summary>
/// Provides extension methods for FixedString*N*Bytes.
/// </summary>
public unsafe static partial class FixedStringMethods
{
<#
for (var ARGS = 1; ARGS <= 10; ++ARGS)
{
var TYPES = String.Join(", ", Enumerable.Range(0, ARGS).Select(n => $"T{n}"));
var PARAMS = String.Join(", ", Enumerable.Range(0, ARGS).Select(n => $"in T{n} arg{n}"));
var ARGNAMES = String.Join(", ", Enumerable.Range(0, ARGS).Select(n => $"arg{n}"));
var TxDOCS = String.Join("\r\n /// ", Enumerable.Range(0, ARGS).Select(n => $"<typeparam name=\"T{n}\">The type of value to interpolate into the format string.</typeparam>"));
var ARGxDOCS = String.Join("\r\n /// ", Enumerable.Range(0, ARGS).Select(n => $"<param name=\"arg{n}\">A FixedString*N*Bytes to interpolate into the format string.</param>"));
var BCOMPAT = String.Join(", ", Enumerable.Range(0, ARGS).Select(n => $"typeof(FixedString128Bytes /*T{n}*/)"));
#>
/// <summary>
/// Interpolates strings into a format string and appends the result to this string.
/// </summary>
/// <remarks>
/// Similar to `StringBuilder.AppendFormat` but with significant limitations:
/// - Only supports FixedString*N*Bytes arguments. To use other string types, convert them to FixedString*N*Bytes first.
/// - Only supports numeric format placeholders of the form `{0}` .. `{N}`.
/// - No format modifiers (*e.g.* `{0:x}`) are supported.
///
/// The overloads of this method take up to ten strings to interpolate into the format string.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <typeparam name="U">A FixedString*N*Bytes type.</typeparam>
/// <#=TxDOCS#>
/// <param name="dest">The string to append to.</param>d
/// <param name="format">A string to be interpolated and appended.</param>
/// <#=ARGxDOCS#>
/// <returns><see cref="FormatError.None"/> if successful. Otherwise returns the appropriate <see cref="FormatError"/>.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes /*T*/), typeof(FixedString128Bytes /*U*/), <#=BCOMPAT#> })]
public static unsafe FormatError AppendFormat<T, U, <#=TYPES#>>(ref this T dest, in U format, <#=PARAMS#>)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
where U : unmanaged, INativeList<byte>, IUTF8Bytes
<#
for (var a = 0; a < ARGS; ++a)
WriteLine(" where T{0} : unmanaged, INativeList<byte>, IUTF8Bytes", a);
#>
{
ref var formatRef = ref UnsafeUtilityExtensions.AsRef(in format);
int formatLength = formatRef.Length;
byte* formatBytes = formatRef.GetUnsafePtr();
int i = 0;
FormatError err = FormatError.None;
while (i < formatLength)
{
byte currByte = formatBytes[i++];
if (currByte == (byte)'{')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
return FormatError.BadFormatSpecifier;
if (currByte >= (byte)'0' && currByte <= (byte)'9' && i < formatLength && formatBytes[i++] == (byte)'}')
{
switch (currByte - (byte)'0')
{
<#
for(var a = 0; a < ARGS; ++a)
{
WriteLine($" case {a}: err = dest.Append(in arg{a}); break;");
}
#>
default: err = FormatError.BadFormatSpecifier; break;
}
}
else if (currByte == (byte)'{')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else if (currByte == (byte)'}')
{
if (i < formatLength)
currByte = formatBytes[i++];
else
err = FormatError.BadFormatSpecifier;
if (currByte == (byte)'}')
err = dest.AppendRawByte(currByte);
else
err = FormatError.BadFormatSpecifier;
}
else
err = dest.AppendRawByte(currByte);
if (err != FormatError.None)
return err;
}
return FormatError.None;
}
<#
}
#>
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0cdef7b1946241588e9a3b52426940e4
timeCreated: 1584994860
@@ -0,0 +1,158 @@
using System;
namespace Unity.Collections
{
[GenerateTestsForBurstCompatibility]
public unsafe static partial class FixedStringMethods
{
/// <summary>
/// Append two characters to this IUTF8Bytes. This is used as a helper for internal formatting.
/// </summary>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
internal static FormatError Append<T>(ref this T fs, char a, char b)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
FormatError err = FormatError.None;
err |= fs.Append((Unicode.Rune) a);
err |= fs.Append((Unicode.Rune) b);
if (err != FormatError.None)
return FormatError.Overflow;
return FormatError.None;
}
/// <summary>
/// Append three characters to this IUTF8Bytes. This is used as a helper for internal formatting.
/// </summary>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
internal static FormatError Append<T>(ref this T fs, char a, char b, char c)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
FormatError err = FormatError.None;
err |= fs.Append((Unicode.Rune) a);
err |= fs.Append((Unicode.Rune) b);
err |= fs.Append((Unicode.Rune) c);
if (err != FormatError.None)
return FormatError.Overflow;
return FormatError.None;
}
/// <summary>
/// Append 'I' 'n' 'f' 'i' 'n' 'i' 't' 'y' characters to this IUTF8Bytes. This is used as a helper for internal formatting.
/// </summary>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
internal static FormatError Append<T>(ref this T fs, char a, char b, char c, char d, char e, char f, char g, char h)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
FormatError err = FormatError.None;
err |= fs.Append((Unicode.Rune) a);
err |= fs.Append((Unicode.Rune) b);
err |= fs.Append((Unicode.Rune) c);
err |= fs.Append((Unicode.Rune) d);
err |= fs.Append((Unicode.Rune) e);
err |= fs.Append((Unicode.Rune) f);
err |= fs.Append((Unicode.Rune) g);
err |= fs.Append((Unicode.Rune) h);
if (err != FormatError.None)
return FormatError.Overflow;
return FormatError.None;
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
internal static FormatError AppendScientific<T>(ref this T fs, char *source, int sourceLength, int decimalExponent, char decimalSeparator = '.')
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
FormatError error;
if ((error = fs.Append(source[0])) != FormatError.None)
return error;
if (sourceLength > 1)
{
if ((error = fs.Append(decimalSeparator)) != FormatError.None)
return error;
for (var i = 1; i < sourceLength; ++i)
{
if ((error = fs.Append(source[i])) != FormatError.None)
return error;
}
}
if ((error = fs.Append('E')) != FormatError.None)
return error;
if (decimalExponent < 0)
{
if ((error = fs.Append('-')) != FormatError.None)
return error;
decimalExponent *= -1;
decimalExponent -= sourceLength - 1;
}
else
{
if ((error = fs.Append('+')) != FormatError.None)
return error;
decimalExponent += sourceLength - 1;
}
var ascii = stackalloc char[2];
const int decimalDigits = 2;
for (var i = 0; i < decimalDigits; ++i)
{
var decimalDigit = decimalExponent % 10;
ascii[1 - i] = (char)('0' + decimalDigit);
decimalExponent /= 10;
}
for (var i = 0; i < decimalDigits; ++i)
if ((error = fs.Append(ascii[i])) != FormatError.None)
return error;
return FormatError.None;
}
/// <summary>
/// Check if runes a, b, c are found at offset offset
/// </summary>
/// <param name="offset">The target offset</param>
/// <param name="a">rune a</param>
/// <param name="b">rune b</param>
/// <param name="c">rune c</param>
/// <returns></returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
internal static bool Found<T>(ref this T fs, ref int offset, char a, char b, char c)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
int old = offset;
if ((fs.Read(ref offset).value | 32) == a
&& (fs.Read(ref offset).value | 32) == b
&& (fs.Read(ref offset).value | 32) == c)
return true;
offset = old;
return false;
}
/// <summary>
///
/// </summary>
/// <param name="offset"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="d"></param>
/// <param name="e"></param>
/// <param name="f"></param>
/// <param name="g"></param>
/// <param name="h"></param>
/// <returns></returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
internal static bool Found<T>(ref this T fs, ref int offset, char a, char b, char c, char d, char e, char f, char g, char h)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
int old = offset;
if ((fs.Read(ref offset).value | 32) == a
&& (fs.Read(ref offset).value | 32) == b
&& (fs.Read(ref offset).value | 32) == c
&& (fs.Read(ref offset).value | 32) == d
&& (fs.Read(ref offset).value | 32) == e
&& (fs.Read(ref offset).value | 32) == f
&& (fs.Read(ref offset).value | 32) == g
&& (fs.Read(ref offset).value | 32) == h)
return true;
offset = old;
return false;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d1db1dc6fae245e9af37d2ab33aac17a
timeCreated: 1593671154
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: ff34e3b577f44d67b146cc64b598b67d
timeCreated: 1591136455
@@ -0,0 +1,229 @@
using System;
using System.Runtime.CompilerServices;
namespace Unity.Collections
{
/// <summary>
/// Provides methods for parsing numbers from FixedString*N*Bytes.
/// </summary>
[GenerateTestsForBurstCompatibility]
public unsafe static partial class FixedStringMethods
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
internal static bool ParseLongInternal<T>(ref T fs, ref int offset, out long value)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
int resetOffset = offset;
int sign = 1;
if (offset < fs.Length)
{
if (fs.Peek(offset).value == '+')
fs.Read(ref offset);
else if (fs.Peek(offset).value == '-')
{
sign = -1;
fs.Read(ref offset);
}
}
int digitOffset = offset;
value = 0;
while (offset < fs.Length && Unicode.Rune.IsDigit(fs.Peek(offset)))
{
value *= 10;
value += fs.Read(ref offset).value - '0';
}
value = sign * value;
// If there was no number parsed, revert the offset since it's a syntax error and we might
// have erroneously parsed a '-' or '+'
if (offset == digitOffset)
{
offset = resetOffset;
return false;
}
return true;
}
/// <summary>
/// Parses an int from this string starting at a byte offset.
/// </summary>
/// <remarks>
/// Stops parsing after the last number character. (Unlike parsing methods in other API's, this method does not expect to necessarily parse the entire string.)
///
/// The parsed value is bitwise-identical to the result of System.Int32.Parse.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <param name="fs">The string from which to parse.</param>
/// <param name="offset">A reference to an index of the byte at which to parse an int.</param>
/// <param name="output">Outputs the parsed int. Ignore if parsing fails.</param>
/// <returns>ParseError.None if successful. Otherwise returns ParseError.Overflow or ParseError.Syntax.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static ParseError Parse<T>(ref this T fs, ref int offset, ref int output)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
if (!ParseLongInternal(ref fs, ref offset, out long value))
return ParseError.Syntax;
if (value > int.MaxValue)
return ParseError.Overflow;
if (value < int.MinValue)
return ParseError.Overflow;
output = (int)value;
return ParseError.None;
}
/// <summary>
/// Parses an uint from this string starting at a byte offset.
/// </summary>
/// <remarks>
/// Stops parsing after the last number character. (Unlike parsing methods in other API's, this method does not expect to necessarily parse the entire string.)
///
/// The parsed value is bitwise-identical to the result of System.UInt32.Parse.
/// </remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <param name="fs">The string from which to parse.</param>
/// <param name="offset">A reference to an index of the byte at which to parse a uint.</param>
/// <param name="output">Outputs the parsed uint. Ignore if parsing fails.</param>
/// <returns>ParseError.None if successful. Otherwise returns ParseError.Overflow or ParseError.Syntax.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static ParseError Parse<T>(ref this T fs, ref int offset, ref uint output)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
if (!ParseLongInternal(ref fs, ref offset, out long value))
return ParseError.Syntax;
if (value > uint.MaxValue)
return ParseError.Overflow;
if (value < uint.MinValue)
return ParseError.Overflow;
output = (uint)value;
return ParseError.None;
}
/// <summary>
/// Parses a float from this string starting at a byte offset.
/// </summary>
/// Stops parsing after the last number character. (Unlike parsing methods in other API's, this method does not expect to necessarily parse the entire string.)
///
/// <remarks>The parsed value is bitwise-identical to the result of System.Single.Parse.</remarks>
/// <typeparam name="T">A FixedString*N*Bytes type.</typeparam>
/// <param name="fs">The string from which to parse.</param>
/// <param name="offset">Index of the byte at which to parse a float.</param>
/// <param name="output">Outputs the parsed float. Ignore if parsing fails.</param>
/// <param name="decimalSeparator">The character used to separate the integer part of the number from the fractional part. Defaults to '.' (period).</param>
/// <returns>ParseError.None if successful. Otherwise returns ParseError.Overflow, ParseError.Underflow, or ParseError.Syntax.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(FixedString128Bytes) })]
public static ParseError Parse<T>(ref this T fs, ref int offset, ref float output, char decimalSeparator = '.')
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
int resetOffset = offset;
int sign = 1;
if (offset < fs.Length)
{
if (fs.Peek(offset).value == '+')
fs.Read(ref offset);
else if (fs.Peek(offset).value == '-')
{
sign = -1;
fs.Read(ref offset);
}
}
if (fs.Found(ref offset, 'n', 'a', 'n'))
{
FixedStringUtils.UintFloatUnion ufu = new FixedStringUtils.UintFloatUnion();
ufu.uintValue = 4290772992U;
output = ufu.floatValue;
return ParseError.None;
}
if (fs.Found(ref offset, 'i', 'n', 'f', 'i', 'n', 'i', 't', 'y'))
{
output = (sign == 1) ? Single.PositiveInfinity : Single.NegativeInfinity;
return ParseError.None;
}
ulong decimalMantissa = 0;
int significantDigits = 0;
int digitsAfterDot = 0;
int mantissaDigits = 0;
while (offset < fs.Length && Unicode.Rune.IsDigit(fs.Peek(offset)))
{
++mantissaDigits;
if (significantDigits < 9)
{
var temp = decimalMantissa * 10 + (ulong)(fs.Peek(offset).value - '0');
if (temp > decimalMantissa)
++significantDigits;
decimalMantissa = temp;
}
else
--digitsAfterDot;
fs.Read(ref offset);
}
if (offset < fs.Length && fs.Peek(offset).value == decimalSeparator)
{
fs.Read(ref offset);
while (offset < fs.Length && Unicode.Rune.IsDigit(fs.Peek(offset)))
{
++mantissaDigits;
if (significantDigits < 9)
{
var temp = decimalMantissa * 10 + (ulong)(fs.Peek(offset).value - '0');
if (temp > decimalMantissa)
++significantDigits;
decimalMantissa = temp;
++digitsAfterDot;
}
fs.Read(ref offset);
}
}
if (mantissaDigits == 0)
{
// Reset offset in case '+' or '-' was erroneously parsed
offset = resetOffset;
return ParseError.Syntax;
}
int decimalExponent = 0;
int decimalExponentSign = 1;
if (offset < fs.Length && (fs.Peek(offset).value | 32) == 'e')
{
fs.Read(ref offset);
if (offset < fs.Length)
{
if (fs.Peek(offset).value == '+')
fs.Read(ref offset);
else if (fs.Peek(offset).value == '-')
{
decimalExponentSign = -1;
fs.Read(ref offset);
}
}
int digitOffset = offset;
while (offset < fs.Length && Unicode.Rune.IsDigit(fs.Peek(offset)))
{
decimalExponent = decimalExponent * 10 + (fs.Peek(offset).value - '0');
fs.Read(ref offset);
}
if (offset == digitOffset)
{
// Reset offset in case '+' or '-' was erroneously parsed
offset = resetOffset;
return ParseError.Syntax;
}
if (decimalExponent > 38)
{
if (decimalExponentSign == 1)
return ParseError.Overflow;
else
return ParseError.Underflow;
}
}
decimalExponent = decimalExponent * decimalExponentSign - digitsAfterDot;
var error = FixedStringUtils.Base10ToBase2(ref output, decimalMantissa, decimalExponent);
if (error != ParseError.None)
return error;
output *= sign;
return ParseError.None;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: af16c54541e443e59c1fdf0919c1b9ea
timeCreated: 1591061254
@@ -0,0 +1,145 @@
using System;
using System.Runtime.InteropServices;
using Unity.Collections.LowLevel.Unsafe;
using System.Diagnostics;
namespace Unity.Collections
{
/// <summary>
/// An interface for a sequence of UTF-8 encoded text.
/// </summary>
public interface IUTF8Bytes
{
/// <summary>
/// Whether this IUTF8Bytes is empty.
/// </summary>
/// <value>True if this IUTF8Bytes is empty.</value>
bool IsEmpty { get; }
/// <summary>
/// Returns a pointer to the content of this IUTF8Bytes.
/// </summary>
/// <remarks>The pointer may point to stack memory.</remarks>
/// <returns>A pointer to the content of this IUTF8Bytes.</returns>
unsafe byte* GetUnsafePtr();
/// <summary>
/// Attempt to set the length in bytes of this IUTF8Bytes's content buffer.
/// </summary>
/// <param name="newLength">The new length in bytes of the IUTF8Bytes's content buffer.</param>
/// <param name="clearOptions">Whether any bytes added should be zeroed out.</param>
/// <returns>True if the new length is valid.</returns>
bool TryResize(int newLength, NativeArrayOptions clearOptions = NativeArrayOptions.ClearMemory);
}
[GenerateTestsForBurstCompatibility]
internal unsafe static class FixedStringUtils
{
[StructLayout(LayoutKind.Explicit)]
internal struct UintFloatUnion
{
[FieldOffset(0)]
public uint uintValue;
[FieldOffset(0)]
public float floatValue;
}
internal static ParseError Base10ToBase2(ref float output, ulong mantissa10, int exponent10)
{
if (mantissa10 == 0)
{
output = 0.0f;
return ParseError.None;
}
if (exponent10 == 0)
{
output = mantissa10;
return ParseError.None;
}
var exponent2 = exponent10;
var mantissa2 = mantissa10;
while (exponent10 > 0)
{
while ((mantissa2 & 0xe000000000000000U) != 0)
{
mantissa2 >>= 1;
++exponent2;
}
mantissa2 *= 5;
--exponent10;
}
while (exponent10 < 0)
{
while ((mantissa2 & 0x8000000000000000U) == 0)
{
mantissa2 <<= 1;
--exponent2;
}
mantissa2 /= 5;
++exponent10;
}
// TODO: implement math.ldexpf (which presumably handles denormals (i don't))
UintFloatUnion ufu = new UintFloatUnion();
ufu.floatValue = mantissa2;
var e = (int)((ufu.uintValue >> 23) & 0xFFU) - 127;
e += exponent2;
if (e > 128)
return ParseError.Overflow;
if (e < -127)
return ParseError.Underflow;
ufu.uintValue = (ufu.uintValue & ~(0xFFU << 23)) | ((uint)(e + 127) << 23);
output = ufu.floatValue;
return ParseError.None;
}
internal static void Base2ToBase10(ref ulong mantissa10, ref int exponent10, float input)
{
UintFloatUnion ufu = new UintFloatUnion();
ufu.floatValue = input;
if (ufu.uintValue == 0)
{
mantissa10 = 0;
exponent10 = 0;
return;
}
var mantissa2 = (ufu.uintValue & ((1 << 23) - 1)) | (1 << 23);
var exponent2 = (int)(ufu.uintValue >> 23) - 127 - 23;
mantissa10 = mantissa2;
exponent10 = exponent2;
if (exponent2 > 0)
{
while (exponent2 > 0)
{
// denormalize mantissa10 as much as you can, to minimize loss when doing /5 below.
while (mantissa10 <= UInt64.MaxValue / 10)
{
mantissa10 *= 10;
--exponent10;
}
mantissa10 /= 5;
--exponent2;
}
}
if (exponent2 < 0)
{
while (exponent2 < 0)
{
// normalize mantissa10 just as much as you need, in order to make the *5 below not overflow.
while (mantissa10 > UInt64.MaxValue / 5)
{
mantissa10 /= 10;
++exponent10;
}
mantissa10 *= 5;
++exponent2;
}
}
// normalize mantissa10
while (mantissa10 > 9999999U || mantissa10 % 10 == 0)
{
mantissa10 = (mantissa10 + (mantissa10 < 100000000U ? 5u : 0u)) / 10;
++exponent10;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8172d9c91a2b64bca91bb78a3a3d4552
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,106 @@
using System;
namespace Unity.Collections
{
/// <summary>
///
/// </summary>
[Obsolete("Use GenerateTestsForBurstCompatibility (UnityUpgradable) -> GenerateTestsForBurstCompatibilityAttribute", true)]
public class BurstCompatibleAttribute : Attribute
{
}
/// <summary>
/// Documents and enforces (via generated tests) that the tagged method or property has to stay burst compatible.
/// </summary>
/// <remarks>This attribute cannot be used with private methods or properties.</remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, AllowMultiple = true)]
public class GenerateTestsForBurstCompatibilityAttribute : Attribute
{
/// <summary>
/// Burst compatible compile target.
/// </summary>
public enum BurstCompatibleCompileTarget
{
/// <summary>
/// Player.
/// </summary>
Player,
/// <summary>
/// Editor.
/// </summary>
Editor,
/// <summary>
/// Player and editor.
/// </summary>
PlayerAndEditor
}
/// <summary>
/// Types to be used for the declared generic type or method.
/// </summary>
/// <remarks>
/// The generic type arguments are tracked separately for types and methods. Say a generic type also contains
/// a generic method, like in the case of Foo&lt;T&gt;.Bar&lt;U&gt;(T baz, U blah). You must specify
/// GenericTypeArguments for Foo and also for Bar to establish the concrete types for T and U. When code
/// generation occurs for the Burst compatibility tests, any time T appears (in the definition of Foo)
/// it will be replaced with the generic type argument you specified for Foo and whenever U appears
/// (in method Bar's body) it will be replaced by whatever generic type argument you specified for the method
/// Bar.
/// </remarks>
public Type[] GenericTypeArguments { get; set; }
/// <summary>
/// Specifies the symbol that must be defined in order for the method to be tested for Burst compatibility.
/// </summary>
public string RequiredUnityDefine = null;
/// <summary>
/// Specifies whether code should be Burst compiled for the player, editor, or both.
/// </summary>
/// <remarks>
/// When set to BurstCompatibleCompileTarget.Editor, the generated Burst compatibility code will be
/// surrounded by #if UNITY_EDITOR to ensure that the Burst compatibility test will only be executed in the
/// editor. The code will be compiled with Burst function pointers. If you have a non-null RequiredUnityDefine,
/// an #if with the RequiredUnityDefine will also be emitted.<para/> <para/>
///
/// When set to BurstCompatibilityCompileTarget.Player, the generated Burst compatibility code will
/// only be surrounded by an #if containing the RequiredUnityDefine (or nothing if RequiredUnityDefine is null).
/// Instead of compiling with Burst function pointers, a player build is started where the Burst AOT compiler
/// will verify the Burst compatibility. This is done to speed up Burst compilation for the compatibility tests
/// since Burst function pointer compilation is not done in parallel.<para/> <para/>
///
/// When set to BurstCompatibilityCompileTarget.PlayerAndEditor, the generated Burst compatibility code will
/// only be surrounded by an #if containing the RequiredUnityDefine (or nothing if RequiredUnityDefine is null).
/// The code will be compiled both by the editor (using Burst function pointers) and with a player build (using
/// Burst AOT).<para/> <para/>
///
/// For best performance of the Burst compatibility tests, prefer to use BurstCompatibilityCompileTarget.Player
/// as much as possible.
/// </remarks>
public BurstCompatibleCompileTarget CompileTarget = BurstCompatibleCompileTarget.Player;
}
/// <summary>
/// Attribute to exclude a method from burst compatibility testing even though the containing type is.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor)]
public class ExcludeFromBurstCompatTestingAttribute : Attribute
{
/// <summary>
/// Reason for excluding a method from being included in generated Burst compilation tests
/// </summary>
public string Reason { get; set; }
/// <summary>
/// Create this attribute with the reason to exclude from burst compatibility testing.
/// </summary>
/// <param name="_reason">Reason target is not burst compatible.</param>
public ExcludeFromBurstCompatTestingAttribute(string _reason)
{
Reason = _reason;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cf57aae738013234baa585dee44cf5ac
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f778b3b3948af5542847d94f90157bd6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using Unity.Scripting.LifecycleManagement;
namespace Unity.Jobs
{
/// <summary>
/// Used by automatically generated code. Do not use in projects.
/// </summary>
public partial class EarlyInitHelpers
{
/// <summary>
/// Used by automatically generated code. Do not use in projects.
/// Delegate used for early initialization
/// </summary>
public delegate void EarlyInitFunction();
[AutoStaticsCleanup]
private static List<EarlyInitFunction> s_PendingDelegates;
[OnCodeLoaded]
static void Initialize()
{
FlushEarlyInits();
}
/// <summary>
/// Used by automatically generated code. Do not use in projects.
/// Calls all EarlyInit delegates and clears the invocation list
/// </summary>
public static void FlushEarlyInits()
{
while (s_PendingDelegates != null)
{
var oldList = s_PendingDelegates;
s_PendingDelegates = null;
for (int i = 0; i < oldList.Count; ++i)
{
try
{
oldList[i]();
}
catch (Exception ex)
{
Debug.LogException(ex);
}
}
}
}
/// <summary>
/// Used by automatically generated code. Do not use in projects.
/// Adds an EarlyInit helper function to invocation list.
/// </summary>
/// <param name="func">EarlyInitFunction add to early call list</param>
public static void AddEarlyInitFunction(EarlyInitFunction func)
{
if (s_PendingDelegates == null)
s_PendingDelegates = new List<EarlyInitFunction>();
s_PendingDelegates.Add(func);
}
/// <summary>
/// Used by automatically generated code. Do not use in projects.
/// This methods is called when JobReflectionData cannot be created during EarlyInit.
/// </summary>
/// <param name="ex">Exception type to throw</param>
public static void JobReflectionDataCreationFailed(Exception ex)
{
Debug.LogError($"Failed to create job reflection data. Please refer to callstack of exception for information on which job could not produce its reflection data.");
Debug.LogException(ex);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 05a99ad2800ad2f49b22ab35d999bfc7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,341 @@
using System;
using Unity.Jobs.LowLevel.Unsafe;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using System.Diagnostics;
using Unity.Burst;
using Unity.Mathematics;
namespace Unity.Jobs
{
/// <summary>
/// **Obsolete.** Use <see cref="IJobFilterExtensions"/> instead.
/// </summary>
[Obsolete("'JobParallelIndexListExtensions' has been deprecated; Use 'IJobFilterExtensions' instead.", false)]
public static class JobParallelIndexListExtensions
{
/// <summary>
/// **Obsolete.**
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jobData"></param>
/// <param name="indices"></param>
/// <param name="arrayLength"></param>
/// <param name="innerloopBatchCount"></param>
/// <param name="dependsOn"></param>
/// <returns></returns>
[Obsolete("The signature for 'ScheduleAppend' has changed. 'innerloopBatchCount' is no longer part of this API.", false)]
public static unsafe JobHandle ScheduleAppend<T>(this T jobData, NativeList<int> indices, int arrayLength, int innerloopBatchCount, JobHandle dependsOn = new JobHandle()) where T : struct, IJobFilter
=> jobData.ScheduleAppend(indices, arrayLength, dependsOn);
/// <summary>
/// **Obsolete.**
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jobData"></param>
/// <param name="indices"></param>
/// <param name="innerloopBatchCount"></param>
/// <param name="dependsOn"></param>
/// <returns></returns>
[Obsolete("The signature for 'ScheduleFilter' has changed. 'innerloopBatchCount' is no longer part of this API.")]
public static unsafe JobHandle ScheduleFilter<T>(this T jobData, NativeList<int> indices, int innerloopBatchCount, JobHandle dependsOn = new JobHandle()) where T : struct, IJobFilter
=> jobData.ScheduleFilter(indices, dependsOn);
}
/// <summary>
/// **Obsolete.** Use <see cref="IJobFilter"/> instead.
/// </summary>
[Obsolete("'IJobParallelForFilter' has been deprecated; use 'IJobFilter' instead. (UnityUpgradable) -> IJobFilter")]
public interface IJobParallelForFilter
{
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
bool Execute(int index);
}
/// <summary>
/// Filters a list of indices.
/// </summary>
/// <remarks>
/// IJobFilter allows for custom jobs to implement a bool Execute(int index) job function used to filter a list of indices.
/// For a provided list and index range, the list will be modified to append all indices for which Execute returns true or to exclude all indices for which Execute returns false
/// depending on if ScheduleAppend or Schedule is used, respectfully, for enqueuing the job with the job system.
/// </remarks>
[JobProducerType(typeof(IJobFilterExtensions.JobFilterProducer<>))]
public interface IJobFilter
{
/// <summary>
/// Filter function. A list of indices is provided when scheduling this job type. The
/// Execute function will be called once for each index returning true or false if the job data at
/// the passed in index should be filtered or not.
/// </summary>
/// <param name="index">Index to use when reading job data for the purpose of filtering</param>
/// <returns>Returns true for data at index</returns>
bool Execute(int index);
}
/// <summary>
/// Extension class for the IJobFilter job type providing custom overloads for scheduling and running.
/// </summary>
public static class IJobFilterExtensions
{
internal struct JobFilterProducer<T> where T : struct, IJobFilter
{
public struct JobWrapper
{
[NativeDisableParallelForRestriction]
public NativeList<int> outputIndices;
public int appendCount;
public T JobData;
}
internal static readonly SharedStatic<IntPtr> jobReflectionData = SharedStatic<IntPtr>.GetOrCreate<JobFilterProducer<T>>();
[BurstDiscard]
internal static void Initialize()
{
if (jobReflectionData.Data == IntPtr.Zero)
jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(JobWrapper), typeof(T), (ExecuteJobFunction)Execute);
}
public delegate void ExecuteJobFunction(ref JobWrapper jobWrapper, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex);
/// <summary>
/// Job Producer method invoked by the Job System when running an IJobFilter Job.
/// </summary>
/// <param name="jobWrapper">IJobFilter wrapper type</param>
/// <param name="additionalPtr">unused</param>
/// <param name="bufferRangePatchData">Buffer data JobRanges</param>
/// <param name="ranges">unused</param>
/// <param name="jobIndex">unused</param>
public static void Execute(ref JobWrapper jobWrapper, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex)
{
if (jobWrapper.appendCount == -1)
ExecuteFilter(ref jobWrapper, bufferRangePatchData);
else
ExecuteAppend(ref jobWrapper, bufferRangePatchData);
}
public static unsafe void ExecuteAppend(ref JobWrapper jobWrapper, System.IntPtr bufferRangePatchData)
{
int oldLength = jobWrapper.outputIndices.Length;
jobWrapper.outputIndices.Capacity = math.max(jobWrapper.appendCount + oldLength, jobWrapper.outputIndices.Capacity);
int* outputPtr = (int*)jobWrapper.outputIndices.GetUnsafePtr();
int outputIndex = oldLength;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobWrapper),
0, jobWrapper.appendCount);
#endif
for (int i = 0; i != jobWrapper.appendCount; i++)
{
if (jobWrapper.JobData.Execute(i))
{
outputPtr[outputIndex] = i;
outputIndex++;
}
}
jobWrapper.outputIndices.ResizeUninitialized(outputIndex);
}
public static unsafe void ExecuteFilter(ref JobWrapper jobWrapper, System.IntPtr bufferRangePatchData)
{
int* outputPtr = (int*)jobWrapper.outputIndices.GetUnsafePtr();
int inputLength = jobWrapper.outputIndices.Length;
int outputCount = 0;
for (int i = 0; i != inputLength; i++)
{
int inputIndex = outputPtr[i];
#if ENABLE_UNITY_COLLECTIONS_CHECKS
JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobWrapper), inputIndex, 1);
#endif
if (jobWrapper.JobData.Execute(inputIndex))
{
outputPtr[outputCount] = inputIndex;
outputCount++;
}
}
jobWrapper.outputIndices.ResizeUninitialized(outputCount);
}
}
/// <summary>
/// Gathers and caches reflection data for the internal job system's managed bindings. Unity is responsible for calling this method - don't call it yourself.
/// </summary>
/// <typeparam name="T">Job type</typeparam>
/// <remarks>
/// When the Collections package is included in the project, Unity generates code to call EarlyJobInit at startup. This allows Burst compiled code to schedule jobs because the reflection part of initialization, which is not compatible with burst compiler constraints, has already happened in EarlyJobInit.
///
/// __Note__: While the Jobs package code generator handles this automatically for all closed job types, you must register those with generic arguments (like IJobFilter&amp;lt;MyJobType&amp;lt;T&amp;gt;&amp;gt;) manually for each specialization with [[Unity.Jobs.RegisterGenericJobTypeAttribute]].
/// </remarks>
public static void EarlyJobInit<T>()
where T : struct, IJobFilter
{
JobFilterProducer<T>.Initialize();
}
static IntPtr GetReflectionData<T>()
where T : struct, IJobFilter
{
JobFilterProducer<T>.Initialize();
var reflectionData = JobFilterProducer<T>.jobReflectionData.Data;
CollectionHelper.CheckReflectionDataCorrect<T>(reflectionData);
return reflectionData;
}
/// <summary>
/// Schedules a job that will execute the filter job for all integers in indices from index 0 until arrayLength. Each integer which passes the filter (i.e. true is returned from Execute()) will be appended to the indices list.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="indices">List of indices to be filtered. Filtered results will be appended to this list.</param>
/// <param name="arrayLength">Number of indices to filter starting from index 0.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
public static unsafe JobHandle ScheduleAppend<T>(this T jobData, NativeList<int> indices, int arrayLength, JobHandle dependsOn = new JobHandle())
where T : struct, IJobFilter
{
return jobData.ScheduleAppendByRef(indices, arrayLength, dependsOn);
}
/// <summary>
/// Schedules a job that will execute the filter job for all integers in indices from index 0 until arrayLength. Each integer which passes the filter (i.e. true is returned from Execute()) will be used to repopulate the indices list.
/// This has the effect of excluding all integer values that do not pass the filter.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="indices">List of indices to be filtered. Filtered results will be stored in this list.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
public static unsafe JobHandle ScheduleFilter<T>(this T jobData, NativeList<int> indices, JobHandle dependsOn = new JobHandle())
where T : struct, IJobFilter
{
return jobData.ScheduleFilterByRef(indices, dependsOn);
}
/// <summary>
/// Executes the appending filter job, on the main thread. See IJobFilterExtensions.ScheduleAppend for more information on how appending is performed.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="indices">List of indices to be filtered and appended to.</param>
/// <param name="arrayLength">Length of array the filter job will append to.</param>
/// <typeparam name="T">Job type</typeparam>
public static unsafe void RunAppend<T>(this T jobData, NativeList<int> indices, int arrayLength)
where T : struct, IJobFilter
{
jobData.RunAppendByRef(indices, arrayLength);
}
/// <summary>
/// Executes the filter job, on the main thread. See IJobFilterExtensions.Schedule for more information on how appending is performed.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="indices">List of indices to be filtered. Filtered results will be stored in this list.</param>
/// <typeparam name="T">Job type</typeparam>
public static unsafe void RunFilter<T>(this T jobData, NativeList<int> indices)
where T : struct, IJobFilter
{
jobData.RunFilterByRef(indices);
}
/// <summary>
/// Schedules a job that will execute the filter job for all integers in indices from index 0 until arrayLength. Each integer which passes the filter (i.e. true is returned from Execute()) will be appended to the indices list.
/// </summary>
/// <param name="jobData">The job and data to schedule. In this variant, the jobData is
/// passed by reference, which may be necessary for unusually large job structs.</param>
/// <param name="indices">List of indices to be filtered. Filtered results will be appended to this list.</param>
/// <param name="arrayLength">Number of indices to filter starting from index 0.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
public static unsafe JobHandle ScheduleAppendByRef<T>(ref this T jobData, NativeList<int> indices, int arrayLength, JobHandle dependsOn = new JobHandle())
where T : struct, IJobFilter
{
JobFilterProducer<T>.JobWrapper jobWrapper = new JobFilterProducer<T>.JobWrapper()
{
JobData = jobData,
outputIndices = indices,
appendCount = arrayLength
};
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobWrapper), GetReflectionData<T>(), dependsOn, ScheduleMode.Single);
return JobsUtility.Schedule(ref scheduleParams);
}
/// <summary>
/// Schedules a job that will execute the filter job for all integers in indices from index 0 until arrayLength. Each integer which passes the filter (i.e. true is returned from Execute()) will be used to repopulate the indices list.
/// This has the effect of excluding all integer values that do not pass the filter.
/// </summary>
/// <param name="jobData">The job and data to schedule. In this variant, the jobData is
/// passed by reference, which may be necessary for unusually large job structs.</param>
/// <param name="indices">List of indices to be filtered. Filtered results will be stored in this list.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
public static unsafe JobHandle ScheduleFilterByRef<T>(ref this T jobData, NativeList<int> indices, JobHandle dependsOn = new JobHandle())
where T : struct, IJobFilter
{
JobFilterProducer<T>.JobWrapper jobWrapper = new JobFilterProducer<T>.JobWrapper()
{
JobData = jobData,
outputIndices = indices,
appendCount = -1
};
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobWrapper), GetReflectionData<T>(), dependsOn, ScheduleMode.Single);
return JobsUtility.Schedule(ref scheduleParams);
}
/// <summary>
/// Executes the appending filter job, on the main thread. See IJobFilterExtensions.ScheduleAppend for more information on how appending is performed.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="indices">List of indices to be filtered. Filtered results will be appended to this list.</param>
/// <param name="arrayLength">Number of indices to filter starting from index 0.</param>
/// <typeparam name="T">Job type</typeparam>
public static unsafe void RunAppendByRef<T>(ref this T jobData, NativeList<int> indices, int arrayLength)
where T : struct, IJobFilter
{
JobFilterProducer<T>.JobWrapper jobWrapper = new JobFilterProducer<T>.JobWrapper()
{
JobData = jobData,
outputIndices = indices,
appendCount = arrayLength
};
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobWrapper), GetReflectionData<T>(), new JobHandle(), ScheduleMode.Run);
JobsUtility.Schedule(ref scheduleParams);
}
/// <summary>
/// Executes the filter job, on the main thread. See IJobFilterExtensions.Schedule for more information on how appending is performed.
/// </summary>
/// <param name="jobData">The job and data to schedule. In this variant, the jobData is
/// passed by reference, which may be necessary for unusually large job structs.</param>
/// <param name="indices">List of indices to be filtered. Filtered results will be stored in this list.</param>
/// <typeparam name="T">Job type</typeparam>
public static unsafe void RunFilterByRef<T>(ref this T jobData, NativeList<int> indices)
where T : struct, IJobFilter
{
JobFilterProducer<T>.JobWrapper jobWrapper = new JobFilterProducer<T>.JobWrapper()
{
JobData = jobData,
outputIndices = indices,
appendCount = -1
};
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobWrapper), GetReflectionData<T>(), new JobHandle(), ScheduleMode.Run);
JobsUtility.Schedule(ref scheduleParams);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c3f9809ba4de01446ae82a0e4f3da278
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,252 @@
using System;
using Unity.Jobs.LowLevel.Unsafe;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Collections;
using System.Diagnostics;
using Unity.Burst;
namespace Unity.Jobs
{
/// <summary>
/// Job type allowing for data to be operated on in parallel batches.
/// </summary>
/// <remarks>
/// When scheduling an IJobParallelForBatch job the number of elements to work on is specified along with a batch size. Jobs will then run in parallel
/// invoking Execute at a particular 'startIndex' of your working set and for a specified 'count' number of elements.
/// </remarks>
[JobProducerType(typeof(IJobParallelForBatchExtensions.JobParallelForBatchProducer<>))]
public interface IJobParallelForBatch
{
/// <summary>
/// Function operation on a "batch" of data contained within the job.
/// </summary>
/// <param name="startIndex">Starting index of job data to safely access.</param>
/// <param name="count">Number of elements to operate on in the batch.</param>
void Execute(int startIndex, int count);
}
/// <summary>
/// Extension class for the IJobParallelForBatch job type providing custom overloads for scheduling and running.
/// </summary>
public static class IJobParallelForBatchExtensions
{
internal struct JobParallelForBatchProducer<T> where T : struct, IJobParallelForBatch
{
internal static readonly SharedStatic<IntPtr> jobReflectionData = SharedStatic<IntPtr>.GetOrCreate<JobParallelForBatchProducer<T>>();
[BurstDiscard]
internal static void Initialize()
{
if (jobReflectionData.Data == IntPtr.Zero)
jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), (ExecuteJobFunction)Execute);
}
internal delegate void ExecuteJobFunction(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex);
public unsafe static void Execute(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex)
{
while (true)
{
if (!JobsUtility.GetWorkStealingRange(
ref ranges,
jobIndex, out int begin, out int end))
return;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), begin, end - begin);
#endif
jobData.Execute(begin, end - begin);
}
}
}
/// <summary>
/// Gathers and caches reflection data for the internal job system's managed bindings. Unity is responsible for calling this method - don't call it yourself.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <remarks>
/// When the Jobs package is included in the project, Unity generates code to call EarlyJobInit at startup. This allows Burst compiled code to schedule jobs because the reflection part of initialization, which is not compatible with burst compiler constraints, has already happened in EarlyJobInit.
///
/// __Note__: While the Jobs package code generator handles this automatically for all closed job types, you must register those with generic arguments (like IJobParallelForBatch&amp;lt;MyJobType&amp;lt;T&amp;gt;&amp;gt;) manually for each specialization with [[Unity.Jobs.RegisterGenericJobTypeAttribute]].
/// </remarks>
public static void EarlyJobInit<T>()
where T : struct, IJobParallelForBatch
{
JobParallelForBatchProducer<T>.Initialize();
}
static IntPtr GetReflectionData<T>()
where T : struct, IJobParallelForBatch
{
JobParallelForBatchProducer<T>.Initialize();
var reflectionData = JobParallelForBatchProducer<T>.jobReflectionData.Data;
CollectionHelper.CheckReflectionDataCorrect<T>(reflectionData);
return reflectionData;
}
/// <summary>
/// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
/// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
/// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="arrayLength">Total number of elements to consider when batching.</param>
/// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
public static unsafe JobHandle Schedule<T>(this T jobData, int arrayLength, int indicesPerJobCount,
JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
{
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Single);
return JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, indicesPerJobCount);
}
/// <summary>
/// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
/// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
/// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
/// </summary>
/// <param name="jobData">The job and data to schedule. In this variant, the jobData is
/// passed by reference, which may be necessary for unusually large job structs.</param>
/// <param name="arrayLength">Total number of elements to consider when batching.</param>
/// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
public static unsafe JobHandle ScheduleByRef<T>(this ref T jobData, int arrayLength, int indicesPerJobCount,
JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
{
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Single);
return JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, indicesPerJobCount);
}
/// <summary>
/// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
/// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
/// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="arrayLength">Total number of elements to consider when batching.</param>
/// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
public static unsafe JobHandle ScheduleParallel<T>(this T jobData, int arrayLength, int indicesPerJobCount,
JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
{
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Parallel);
return JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, indicesPerJobCount);
}
/// <summary>
/// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
/// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
/// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
/// </summary>
/// <param name="jobData">The job and data to schedule. In this variant, the jobData is
/// passed by reference, which may be necessary for unusually large job structs.</param>
/// <param name="arrayLength">Total number of elements to consider when batching.</param>
/// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
public static unsafe JobHandle ScheduleParallelByRef<T>(this ref T jobData, int arrayLength, int indicesPerJobCount,
JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
{
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Parallel);
return JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, indicesPerJobCount);
}
/// <summary>
/// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
/// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
/// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="arrayLength">Total number of elements to consider when batching.</param>
/// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
public static unsafe JobHandle ScheduleBatch<T>(this T jobData, int arrayLength, int indicesPerJobCount,
JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
{
return ScheduleParallel(jobData, arrayLength, indicesPerJobCount, dependsOn);
}
/// <summary>
/// Schedules a job that will execute the parallel batch job for all `arrayLength` elements in batches of `indicesPerJobCount`.
/// The Execute() method for Job T will be provided the start index and number of elements to safely operate on.
/// In cases where `indicesPerJobCount` is not a multiple of `arrayLength`, the `count` provided to the Execute method of Job T will be smaller than the `indicesPerJobCount` specified here.
/// </summary>
/// <param name="jobData">The job and data to schedule. In this variant, the jobData is
/// passed by reference, which may be necessary for unusually large job structs.</param>
/// <param name="arrayLength">Total number of elements to consider when batching.</param>
/// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
public static unsafe JobHandle ScheduleBatchByRef<T>(this ref T jobData, int arrayLength, int indicesPerJobCount,
JobHandle dependsOn = new JobHandle()) where T : struct, IJobParallelForBatch
{
return ScheduleParallelByRef(ref jobData, arrayLength, indicesPerJobCount, dependsOn);
}
/// <summary>
/// Executes the parallel batch job but on the main thread. See IJobParallelForBatchExtensions.Schedule for more information on how appending is performed.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="arrayLength">Total number of elements to consider when batching.</param>
/// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch. This argument is ignored when using .Run()</param>
/// <typeparam name="T">Job type</typeparam>
/// <remarks>
/// Unlike Schedule, since the job is running on the main thread no parallelization occurs and thus no `indicesPerJobCount` batch size is required to be specified.
/// </remarks>
public static unsafe void Run<T>(this T jobData, int arrayLength, int indicesPerJobCount) where T : struct, IJobParallelForBatch
{
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), new JobHandle(), ScheduleMode.Run);
JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, arrayLength);
}
/// <summary>
/// Executes the parallel batch job but on the main thread. See IJobParallelForBatchExtensions.Schedule for more information on how appending is performed.
/// </summary>
/// <param name="jobData">The job and data to schedule. In this variant, the jobData is
/// passed by reference, which may be necessary for unusually large job structs.</param>
/// <param name="arrayLength">Total number of elements to consider when batching.</param>
/// <param name="indicesPerJobCount">Number of elements to consider in a single parallel batch. This argument is ignored when using .RunByRef()</param>
/// <typeparam name="T">Job type</typeparam>
public static unsafe void RunByRef<T>(this ref T jobData, int arrayLength, int indicesPerJobCount) where T : struct, IJobParallelForBatch
{
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), new JobHandle(), ScheduleMode.Run);
JobsUtility.ScheduleParallelFor(ref scheduleParams, arrayLength, arrayLength);
}
/// <summary>
/// Executes the parallel batch job but on the main thread. See IJobParallelForBatchExtensions.ScheduleBatch for more information on how appending is performed.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="arrayLength">Total number of elements to consider when batching.</param>
/// <typeparam name="T">Job type</typeparam>
/// <remarks>
/// Unlike ScheduleBatch, since the job is running on the main thread no parallelization occurs and thus no `indicesPerJobCount` batch size is required to be specified.
/// </remarks>
public static unsafe void RunBatch<T>(this T jobData, int arrayLength) where T : struct, IJobParallelForBatch
{
Run(jobData, arrayLength, arrayLength);
}
/// <summary>
/// Executes the parallel batch job but on the main thread. See IJobParallelForBatchExtensions.ScheduleBatch for more information on how appending is performed.
/// </summary>
/// <param name="jobData">The job and data to schedule. In this variant, the jobData is
/// passed by reference, which may be necessary for unusually large job structs.</param>
/// <param name="arrayLength">Total number of elements to consider when batching.</param>
/// <typeparam name="T">Job type</typeparam>
public static unsafe void RunBatchByRef<T>(this ref T jobData, int arrayLength) where T : struct, IJobParallelForBatch
{
RunByRef(ref jobData, arrayLength, arrayLength);
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 73fbfe0d21bc34441843483c0c2406f0
timeCreated: 1504270347
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,214 @@
using System;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs.LowLevel.Unsafe;
using System.Diagnostics;
using Unity.Burst;
namespace Unity.Jobs
{
/// <summary>
/// Calculates the number of iterations to perform in a job that must execute before an IJobParallelForDefer job.
/// </summary>
/// <remarks>
/// A replacement for IJobParallelFor when the number of work items is not known at Schedule time.
///
/// When Scheduling the job's Execute(int index) method will be invoked on multiple worker threads in
/// parallel to each other.
///
/// Execute(int index) will be executed once for each index from 0 to the provided length. Each iteration
/// must be independent from other iterations and the safety system enforces this rule for you. The indices
/// have no guaranteed order and are executed on multiple cores in parallel.
///
/// Unity automatically splits the work into chunks of no less than the provided batchSize, and schedules
/// an appropriate number of jobs based on the number of worker threads, the length of the array and the batch size.
///
/// Choose a batch size sbased on the amount of work performed in the job. A simple job,
/// for example adding a couple of float3 to each other could have a batch size of 32 to 128. However,
/// if the work performed is very expensive then it's best to use a small batch size, such as a batch
/// size of 1. IJobParallelFor performs work stealing using atomic operations. Batch sizes can be
/// small but they aren't free.
///
/// The returned JobHandle can be used to ensure that the job has completed. Or it can be passed to other jobs as
/// a dependency, ensuring that the jobs are executed one after another on the worker threads.
/// </remarks>
[JobProducerType(typeof(IJobParallelForDeferExtensions.JobParallelForDeferProducer<>))]
public interface IJobParallelForDefer
{
/// <summary>
/// Implement this method to perform work against a specific iteration index.
/// </summary>
/// <param name="index">The index of the Parallel for loop at which to perform work.</param>
void Execute(int index);
}
/// <summary>
/// Extension class for the IJobParallelForDefer job type providing custom overloads for scheduling and running.
/// </summary>
public static class IJobParallelForDeferExtensions
{
internal struct JobParallelForDeferProducer<T> where T : struct, IJobParallelForDefer
{
internal static readonly SharedStatic<IntPtr> jobReflectionData = SharedStatic<IntPtr>.GetOrCreate<JobParallelForDeferProducer<T>>();
[BurstDiscard]
internal static void Initialize()
{
if (jobReflectionData.Data == IntPtr.Zero)
jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), (ExecuteJobFunction)Execute);
}
public delegate void ExecuteJobFunction(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex);
public unsafe static void Execute(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex)
{
while (true)
{
if (!JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out int begin, out int end))
break;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
JobsUtility.PatchBufferMinMaxRanges(bufferRangePatchData, UnsafeUtility.AddressOf(ref jobData), begin, end - begin);
#endif
// Cache the end value to make it super obvious to the
// compiler that `end` will never change during the loops
// iteration.
var endThatCompilerCanSeeWillNeverChange = end;
for (var i = begin; i < endThatCompilerCanSeeWillNeverChange; ++i)
jobData.Execute(i);
}
}
}
/// <summary>
/// Gathers and caches reflection data for the internal job system's managed bindings. Unity is responsible for calling this method - don't call it yourself.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <remarks>
/// When the Jobs package is included in the project, Unity generates code to call EarlyJobInit at startup. This allows Burst compiled code to schedule jobs because the reflection part of initialization, which is not compatible with burst compiler constraints, has already happened in EarlyJobInit.
///
/// __Note__: While the Jobs package code generator handles this automatically for all closed job types, you must register those with generic arguments (like IJobParallelForDefer&amp;lt;MyJobType&amp;lt;T&amp;gt;&amp;gt;) manually for each specialization with [[Unity.Jobs.RegisterGenericJobTypeAttribute]].
/// </remarks>
public static void EarlyJobInit<T>()
where T : struct, IJobParallelForDefer
{
JobParallelForDeferProducer<T>.Initialize();
}
/// <summary>
/// Schedule the job for execution on worker threads.
/// list.Length is used as the iteration count.
/// Note that it is required to embed the list on the job struct as well.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="list">list.Length is used as the iteration count.</param>
/// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
/// <typeparam name="U">List element type</typeparam>
public static unsafe JobHandle Schedule<T, U>(this T jobData, NativeList<U> list, int innerloopBatchCount,
JobHandle dependsOn = new JobHandle())
where T : struct, IJobParallelForDefer
where U : unmanaged
{
void* atomicSafetyHandlePtr = null;
// Calculate the deferred atomic safety handle before constructing JobScheduleParameters so
// DOTS Runtime can validate the deferred list statically similar to the reflection based
// validation in Big Unity.
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var safety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref list);
atomicSafetyHandlePtr = UnsafeUtility.AddressOf(ref safety);
#endif
return ScheduleInternal(ref jobData, innerloopBatchCount,
list.GetUnsafeList(),
atomicSafetyHandlePtr, dependsOn);
}
/// <summary>
/// Schedule the job for execution on worker threads.
/// list.Length is used as the iteration count.
/// Note that it is required to embed the list on the job struct as well.
/// </summary>
/// <param name="jobData">The job and data to schedule. In this variant, the jobData is
/// passed by reference, which may be necessary for unusually large job structs.</param>
/// <param name="list">list.Length is used as the iteration count.</param>
/// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
/// <typeparam name="U">List element type</typeparam>
public static unsafe JobHandle ScheduleByRef<T, U>(this ref T jobData, NativeList<U> list, int innerloopBatchCount,
JobHandle dependsOn = new JobHandle())
where T : struct, IJobParallelForDefer
where U : unmanaged
{
void* atomicSafetyHandlePtr = null;
// Calculate the deferred atomic safety handle before constructing JobScheduleParameters so
// DOTS Runtime can validate the deferred list statically similar to the reflection based
// validation in Big Unity.
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var safety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref list);
atomicSafetyHandlePtr = UnsafeUtility.AddressOf(ref safety);
#endif
return ScheduleInternal(ref jobData, innerloopBatchCount,
list.GetUnsafeList(),
atomicSafetyHandlePtr, dependsOn);
}
/// <summary>
/// Schedule the job for execution on worker threads.
/// forEachCount is a pointer to the number of iterations, when dependsOn has completed.
/// This API is unsafe, it is recommended to use the NativeList based Schedule method instead.
/// </summary>
/// <param name="jobData">The job and data to schedule.</param>
/// <param name="forEachCount">*forEachCount is used as the iteration count.</param>
/// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T">Job type</typeparam>
/// <returns></returns>
public static unsafe JobHandle Schedule<T>(this T jobData, int* forEachCount, int innerloopBatchCount,
JobHandle dependsOn = new JobHandle())
where T : struct, IJobParallelForDefer
{
var forEachListPtr = (byte*)forEachCount - sizeof(void*);
return ScheduleInternal(ref jobData, innerloopBatchCount, forEachListPtr, null, dependsOn);
}
/// <summary>
/// Schedule the job for execution on worker threads.
/// forEachCount is a pointer to the number of iterations, when dependsOn has completed.
/// This API is unsafe, it is recommended to use the NativeList based Schedule method instead.
/// </summary>
/// <param name="jobData">The job and data to schedule. In this variant, the jobData is
/// passed by reference, which may be necessary for unusually large job structs.</param>
/// <param name="forEachCount">*forEachCount is used as the iteration count.</param>
/// <param name="innerloopBatchCount">Granularity in which workstealing is performed. A value of 32, means the job queue will steal 32 iterations and then perform them in an efficient inner loop.</param>
/// <param name="dependsOn">Dependencies are used to ensure that a job executes on workerthreads after the dependency has completed execution. Making sure that two jobs reading or writing to same data do not run in parallel.</param>
/// <returns>JobHandle The handle identifying the scheduled job. Can be used as a dependency for a later job or ensure completion on the main thread.</returns>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static unsafe JobHandle ScheduleByRef<T>(this ref T jobData, int* forEachCount, int innerloopBatchCount,
JobHandle dependsOn = new JobHandle())
where T : struct, IJobParallelForDefer
{
var forEachListPtr = (byte*)forEachCount - sizeof(void*);
return ScheduleInternal(ref jobData, innerloopBatchCount, forEachListPtr, null, dependsOn);
}
private static unsafe JobHandle ScheduleInternal<T>(ref T jobData,
int innerloopBatchCount,
void* forEachListPtr,
void *atomicSafetyHandlePtr,
JobHandle dependsOn) where T : struct, IJobParallelForDefer
{
JobParallelForDeferProducer<T>.Initialize();
var reflectionData = JobParallelForDeferProducer<T>.jobReflectionData.Data;
CollectionHelper.CheckReflectionDataCorrect<T>(reflectionData);
var scheduleParams = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), reflectionData, dependsOn, ScheduleMode.Parallel);
return JobsUtility.ScheduleParallelForDeferArraySize(ref scheduleParams, innerloopBatchCount, forEachListPtr, atomicSafetyHandlePtr);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ad8b28c0bd73eb94cbbaffc184e68af1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,34 @@
using System;
using UnityEngine.Scripting.APIUpdating;
namespace Unity.Jobs
{
/// <summary>
/// When added as an assembly-level attribute, allows creating job reflection data for instances of generic jobs.
/// </summary>
/// <remarks>
/// This attribute allows specific instances of generic jobs to be registered for reflection data generation.
/// </remarks>
[MovedFrom(true, "Unity.Entities", "Unity.Entities")]
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
public class RegisterGenericJobTypeAttribute : Attribute
{
/// <summary>
/// Fully closed generic job type to register with the job system
/// </summary>
public Type ConcreteType;
/// <summary>
/// Registers a fully closed generic job type with the job system
/// </summary>
/// <param name="type"></param>
public RegisterGenericJobTypeAttribute(Type type)
{
ConcreteType = type;
}
}
[AttributeUsage(AttributeTargets.Class)]
internal class DOTSCompilerGeneratedAttribute : Attribute
{}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: dad573b7a5d91e84bab5aada3f2f0530
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
namespace Unity.Collections
{
/// <summary>
/// Extension methods for lists.
/// </summary>
public static class ListExtensions
{
/// <summary>
/// Finds and removes the first occurrence of a particular value in the list.
/// </summary>
/// <remarks>
/// If found, the first occurrence of the value is overwritten by the last element of the list, and the list's length is decremented by one.
/// </remarks>
/// <typeparam name="T">The type of elements in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <param name="value">The value to locate and remove.</param>
/// <returns>Returns true if an element was removed.</returns>
public static bool RemoveSwapBack<T>(this List<T> list, T value)
{
int index = list.IndexOf(value);
if (index < 0)
return false;
RemoveAtSwapBack(list, index);
return true;
}
/// <summary>
/// Finds and removes the first value which satisfies a predicate.
/// </summary>
/// <remarks>
/// The first value satisfying the predicate is overwritten by the last element of the list, and the list's length is decremented by one.
/// </remarks>
/// <typeparam name="T">The type of elements in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <param name="matcher">The predicate for testing the elements of the list.</param>
/// <returns>Returns true if an element was removed.</returns>
public static bool RemoveSwapBack<T>(this List<T> list, Predicate<T> matcher)
{
int index = list.FindIndex(matcher);
if (index < 0)
return false;
RemoveAtSwapBack(list, index);
return true;
}
/// <summary>
/// Removes the value at an index.
/// </summary>
/// <remarks>
/// The value at the index is overwritten by the last element of the list, and the list's length is decremented by one.
/// </remarks>
/// <typeparam name="T">The type of elements in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <param name="index">The index at which to remove an element from the list.</param>
public static void RemoveAtSwapBack<T>(this List<T> list, int index)
{
int lastIndex = list.Count - 1;
list[index] = list[lastIndex];
list.RemoveAt(lastIndex);
}
/// <summary>
/// Returns a copy of this list.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
/// <param name="list">The list to copy.</param>
/// <param name="allocator">The allocator to use.</param>
/// <returns>A copy of this list.</returns>
public static NativeList<T> ToNativeList<T>(this List<T> list, AllocatorManager.AllocatorHandle allocator) where T : unmanaged
{
var container = new NativeList<T>(list.Count, allocator);
for (int i = 0; i < list.Count; i++)
{
container.AddNoResize(list[i]);
}
return container;
}
/// <summary>
/// Returns an array that is a copy of this list.
/// </summary>
/// <typeparam name="T">The type of elements in the list.</typeparam>
/// <param name="list">The list to copy.</param>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array that is a copy of this list.</returns>
public unsafe static NativeArray<T> ToNativeArray<T>(this List<T> list, AllocatorManager.AllocatorHandle allocator) where T : unmanaged
{
var container = CollectionHelper.CreateNativeArray<T>(list.Count, allocator, NativeArrayOptions.UninitializedMemory);
for (int i = 0; i < list.Count; i++)
{
container[i] = list[i];
}
return container;
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 7a3be0dd158385f4081ab23532efbc6c
timeCreated: 1497958388
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,231 @@
using System;
using System.Diagnostics;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
using Unity.Jobs.LowLevel.Unsafe;
namespace Unity.Collections
{
[GenerateTestsForBurstCompatibility]
unsafe internal struct Memory
{
internal const long k_MaximumRamSizeInBytes = 1L << 40; // a terabyte
[GenerateTestsForBurstCompatibility]
internal struct Unmanaged
{
internal static void* Allocate(long size, int align, AllocatorManager.AllocatorHandle allocator)
{
return Array.Resize(null, 0, 1, allocator, size, align);
}
internal static void* Allocate(long size, int align, MemoryLabel label)
{
return Array.Resize(null, 0, 1, label, size, align);
}
internal static void Free(void* pointer, AllocatorManager.AllocatorHandle allocator)
{
if (pointer == null)
return;
Array.Resize(pointer, 1, 0, allocator, 1, 1);
}
internal static void Free(void* pointer, MemoryLabel label)
{
if (pointer == null)
return;
Array.Resize(pointer, 1, 0, label, 1, 1);
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static T* Allocate<T>(AllocatorManager.AllocatorHandle allocator) where T : unmanaged
{
return Array.Resize<T>(null, 0, 1, allocator);
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static T* Allocate<T>(MemoryLabel label) where T : unmanaged
{
return Array.Resize<T>(null, 0, 1, label);
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static void Free<T>(T* pointer, AllocatorManager.AllocatorHandle allocator) where T : unmanaged
{
if (pointer == null)
return;
Array.Resize(pointer, 1, 0, allocator);
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static void Free<T>(T* pointer, MemoryLabel label) where T : unmanaged
{
if (pointer == null)
return;
Array.Resize(pointer, 1, 0, label);
}
[GenerateTestsForBurstCompatibility]
internal struct Array
{
static bool IsCustom(AllocatorManager.AllocatorHandle allocator)
{
return (int) allocator.Index >= AllocatorManager.FirstUserIndex;
}
static void* CustomResize(void* oldPointer, long oldCount, long newCount, AllocatorManager.AllocatorHandle allocator, long size, int align)
{
AllocatorManager.Block block = default;
block.Range.Allocator = allocator;
block.Range.Items = (int)newCount;
block.Range.Pointer = (IntPtr)oldPointer;
block.BytesPerItem = (int)size;
block.Alignment = align;
block.AllocatedItems = (int)oldCount;
var error = AllocatorManager.Try(ref block);
AllocatorManager.CheckFailedToAllocate(error);
return (void*)block.Range.Pointer;
}
internal static void* Resize(void* oldPointer, long oldCount, long newCount, AllocatorManager.AllocatorHandle allocator,
long size, int align)
{
return Resize(oldPointer, oldCount, newCount, allocator, default, size, align);
}
internal static void* Resize(void* oldPointer, long oldCount, long newCount, MemoryLabel label,
long size, int align)
{
return Resize(oldPointer, oldCount, newCount, default, label, size, align);
}
static void* Resize(void* oldPointer, long oldCount, long newCount, AllocatorManager.AllocatorHandle allocator, MemoryLabel label, long size, int align)
{
// Make the alignment multiple of cacheline size
var alignment = math.max(JobsUtility.CacheLineSize, align);
if (IsCustom(allocator != default ? allocator : label.allocator))
return CustomResize(oldPointer, oldCount, newCount, allocator != default ? allocator : label.allocator, size, alignment);
void* newPointer = default;
if (newCount > 0)
{
long bytesToAllocate = newCount * size;
CheckByteCountIsReasonable(bytesToAllocate);
newPointer = allocator != default ? UnsafeUtility.MallocTracked(bytesToAllocate, alignment, allocator.ToAllocator, 0) : UnsafeUtility.MallocTracked(bytesToAllocate, alignment, label, 0);
if (oldCount > 0)
{
long count = math.min(oldCount, newCount);
long bytesToCopy = count * size;
CheckByteCountIsReasonable(bytesToCopy);
UnsafeUtility.MemCpy(newPointer, oldPointer, bytesToCopy);
}
}
if (oldCount > 0)
{
if (allocator != default)
UnsafeUtility.FreeTracked(oldPointer, allocator.ToAllocator);
else
UnsafeUtility.FreeTracked(oldPointer, label);
}
return newPointer;
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static T* Resize<T>(T* oldPointer, long oldCount, long newCount, AllocatorManager.AllocatorHandle allocator) where T : unmanaged
{
return (T*)Resize((byte*)oldPointer, oldCount, newCount, allocator, sizeof(T), UnsafeUtility.AlignOf<T>());
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static T* Resize<T>(T* oldPointer, long oldCount, long newCount, MemoryLabel label) where T : unmanaged
{
return (T*)Resize((byte*)oldPointer, oldCount, newCount, label, sizeof(T), UnsafeUtility.AlignOf<T>());
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static T* Allocate<T>(long count, AllocatorManager.AllocatorHandle allocator)
where T : unmanaged
{
return Resize<T>(null, 0, count, allocator);
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static T* Allocate<T>(long count, MemoryLabel label)
where T : unmanaged
{
return Resize<T>(null, 0, count, label);
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static void Free<T>(T* pointer, long count, AllocatorManager.AllocatorHandle allocator)
where T : unmanaged
{
if (pointer == null)
return;
Resize(pointer, count, 0, allocator);
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static void Free<T>(T* pointer, long count, MemoryLabel label)
where T : unmanaged
{
if (pointer == null)
return;
Resize(pointer, count, 0, label);
}
}
}
[GenerateTestsForBurstCompatibility]
internal struct Array
{
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static void Set<T>(T* pointer, long count, T t = default) where T : unmanaged
{
long bytesToSet = count * sizeof(T);
CheckByteCountIsReasonable(bytesToSet);
for (var i = 0; i < count; ++i)
pointer[i] = t;
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static void Clear<T>(T* pointer, long count) where T : unmanaged
{
long bytesToClear = count * sizeof(T);
CheckByteCountIsReasonable(bytesToClear);
UnsafeUtility.MemClear(pointer, bytesToClear);
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
internal static void Copy<T>(T* dest, T* src, long count) where T : unmanaged
{
long bytesToCopy = count * sizeof(T);
CheckByteCountIsReasonable(bytesToCopy);
UnsafeUtility.MemCpy(dest, src, bytesToCopy);
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
internal static void CheckByteCountIsReasonable(long size)
{
if (size < 0)
throw new InvalidOperationException($"Attempted to operate on {size} bytes of memory: negative size");
if (size > k_MaximumRamSizeInBytes)
throw new InvalidOperationException($"Attempted to operate on {size} bytes of memory: size too big");
}
[GenerateTestsForBurstCompatibility]
internal static MemoryLabel CreateLabel(FixedString32Bytes category, FixedString64Bytes name, Allocator allocator = Allocator.Persistent)
{
return new MemoryLabel(
category.GetUnsafePtr(), category.Length,
name.GetUnsafePtr(), name.Length,
allocator);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: babbfc241a32b8241bf31319e1447eb2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,354 @@
using System;
using System.Diagnostics;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Burst;
using static Unity.Collections.AllocatorManager;
namespace Unity.Collections
{
/// <summary>
/// Extension methods for NativeArray.
/// </summary>
[GenerateTestsForBurstCompatibility]
public unsafe static class NativeArrayExtensions
{
/// <summary>
/// Provides a Burst compatible id for NativeArray<typeparamref name="T"/> types. Used by the Job Safety System.
/// </summary>
/// <typeparam name="T"></typeparam>
public struct NativeArrayStaticId<T>
where T : unmanaged
{
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeArray<T>>();
}
/// <summary>
/// Returns true if a particular value is present in this container.
/// </summary>
/// <typeparam name="T">The type of elements in this container.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="container">The container to search.</param>
/// <param name="value">The value to locate.</param>
/// <returns>True if the value is present in this container.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public static bool Contains<T, U>(this NativeArray<T> container, U value) where T : unmanaged, IEquatable<U> => IndexOf(container.AsReadOnlySpan(), value) != -1;
/// <summary>
/// Finds the index of the first occurrence of a particular value in this container.
/// </summary>
/// <typeparam name="T">The type of elements in this container.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="container">The container to search.</param>
/// <param name="value">The value to locate.</param>
/// <returns>The index of the first occurrence of the value in this container. Returns -1 if no occurrence is found.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public static int IndexOf<T, U>(this NativeArray<T> container, U value) where T : unmanaged, IEquatable<U> => IndexOf(container.AsReadOnlySpan(), value);
/// <summary>
/// Returns true if a particular value is present in this container.
/// </summary>
/// <typeparam name="T">The type of elements in this container.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="container">The container to search.</param>
/// <param name="value">The value to locate.</param>
/// <returns>True if the value is present in this container.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public static bool Contains<T, U>(this NativeArray<T>.ReadOnly container, U value) where T : unmanaged, IEquatable<U> => IndexOf(container.AsReadOnlySpan(), value) != -1;
/// <summary>
/// Finds the index of the first occurrence of a particular value in this container.
/// </summary>
/// <typeparam name="T">The type of elements in this container.</typeparam>
/// <typeparam name="U">The type of value to locate.</typeparam>
/// <param name="container">The container to search.</param>
/// <param name="value">The value to locate.</param>
/// <returns>The index of the first occurrence of the value in this container. Returns -1 if no occurrence is found.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public static int IndexOf<T, U>(this NativeArray<T>.ReadOnly container, U value) where T : unmanaged, IEquatable<U> => IndexOf(container.AsReadOnlySpan(), value);
/// <summary>
/// Returns true if a particular value is present in this container.
/// </summary>
/// <typeparam name="T">The type of elements in this container.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="container">The container to search.</param>
/// <param name="value">The value to locate.</param>
/// <returns>True if the value is present in this container.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public static bool Contains<T, U>(this NativeList<T> container, U value) where T : unmanaged, IEquatable<U> => IndexOf(container.AsReadOnlySpan(), value) != -1;
/// <summary>
/// Finds the index of the first occurrence of a particular value in this container.
/// </summary>
/// <typeparam name="T">The type of elements in this container.</typeparam>
/// <typeparam name="U">The type of value to locate.</typeparam>
/// <param name="container">The container to search.</param>
/// <param name="value">The value to locate.</param>
/// <returns>The index of the first occurrence of the value in this container. Returns -1 if no occurrence is found.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public static int IndexOf<T, U>(this NativeList<T> container, U value) where T : unmanaged, IEquatable<U> => IndexOf(container.AsReadOnlySpan(), value);
/// <summary>
/// Returns true if a particular value is present in a buffer.
/// </summary>
/// <typeparam name="T">The type of elements in the buffer.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="ptr">The buffer.</param>
/// <param name="length">Number of elements in the buffer.</param>
/// <param name="value">The value to locate.</param>
/// <returns>True if the value is present in the buffer.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public static bool Contains<T, U>(T* ptr, int length, U value) where T : unmanaged, IEquatable<U> => IndexOf(ptr, length, value) != -1;
/// <summary>
/// Finds the index of the first occurrence of a particular value in a buffer.
/// </summary>
/// <typeparam name="T">The type of elements in the buffer.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="ptr">A buffer.</param>
/// <param name="length">Number of elements in the buffer.</param>
/// <param name="value">The value to locate.</param>
/// <returns>The index of the first occurrence of the value in the buffer. Returns -1 if no occurrence is found.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public static int IndexOf<T, U>(T* ptr, int length, U value) where T : unmanaged, IEquatable<U> => IndexOf(new ReadOnlySpan<T>(ptr, length), value);
/// <summary>
/// Finds the index of the first occurrence of a particular value in a buffer.
/// </summary>
/// <typeparam name="T">The type of elements in the buffer.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="roSpan">A ReadOnlySpan.</param>
/// <param name="value">The value to locate.</param>
/// <returns>The index of the first occurrence of the value in the buffer. Returns -1 if no occurrence is found.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public static int IndexOf<T, U>(ReadOnlySpan<T> roSpan, U value)
where T : unmanaged, IEquatable<U>
{
var count = roSpan.Length;
if (count > 0)
{
fixed (T* ptr = &roSpan[0])
{
for (int i = 0; i != count; i++)
{
if (UnsafeUtility.ReadArrayElement<T>(ptr, i).Equals(value))
return i;
}
}
}
return -1;
}
/// <summary>
/// Returns true if a particular value is present in this container.
/// </summary>
/// <typeparam name="T">The type of elements in this container.</typeparam>
/// <typeparam name="U">The value type.</typeparam>
/// <param name="roSpan">A ReadOnlySpan.</param>
/// <param name="value">The value to locate.</param>
/// <returns>True if the value is present in this container.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public static bool Contains<T, U>(this ReadOnlySpan<T> roSpan, U value) where T : unmanaged, IEquatable<U> => IndexOf(roSpan, value) != -1;
/// <summary>
/// Copies all elements of specified container to array.
/// </summary>
/// <typeparam name="T">The type of elements in this container.</typeparam>
/// <param name="container">Container to copy to.</param>
/// <param name="other">An container to copy into this array.</param>
/// <exception cref="ArgumentException">Thrown if the array and container have unequal length.</exception>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public static void CopyFrom<T>(this ref NativeArray<T> container, NativeList<T> other)
where T : unmanaged, IEquatable<T>
{
container.CopyFrom(other.AsArray());
}
/// <summary>
/// Copies all elements of specified container to array.
/// </summary>
/// <typeparam name="T">The type of elements in this container.</typeparam>
/// <param name="container">Container to copy to.</param>
/// <param name="other">An container to copy into this array.</param>
/// <exception cref="ArgumentException">Thrown if the array and container have unequal length.</exception>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public static void CopyFrom<T>(this ref NativeArray<T> container, in NativeHashSet<T> other)
where T : unmanaged, IEquatable<T>
{
using (var array = other.ToNativeArray(Allocator.TempJob))
{
container.CopyFrom(array);
}
}
/// <summary>
/// Copies all elements of specified container to array.
/// </summary>
/// <typeparam name="T">The type of elements in this container.</typeparam>
/// <param name="container">Container to copy to.</param>
/// <param name="other">An container to copy into this array.</param>
/// <exception cref="ArgumentException">Thrown if the array and container have unequal length.</exception>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public static void CopyFrom<T>(this ref NativeArray<T> container, in UnsafeHashSet<T> other)
where T : unmanaged, IEquatable<T>
{
using (var array = other.ToNativeArray(Allocator.TempJob))
{
container.CopyFrom(array);
}
}
/// <summary>
/// Returns the reinterpretation of this array into another kind of NativeArray.
/// See [Array reinterpretation](https://docs.unity3d.com/Packages/com.unity.collections@latest?subfolder=/manual/allocation.html#array-reinterpretation).
/// </summary>
/// <param name="array">The array to reinterpret.</param>
/// <typeparam name="T">Type of elements in the array.</typeparam>
/// <typeparam name="U">Type of elements in the reinterpreted array.</typeparam>
/// <returns>The reinterpretation of this array into another kind of NativeArray.</returns>
/// <exception cref="InvalidOperationException">Thrown if this array's capacity cannot be evenly divided by `sizeof(U)`.</exception>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public static NativeArray<U> Reinterpret<T, U>(this NativeArray<T> array)
where U : unmanaged
where T : unmanaged
{
var tSize = sizeof(T);
var uSize = UnsafeUtility.SizeOf<U>();
var byteLen = ((long)array.Length) * tSize;
var uLen = byteLen / uSize;
CheckReinterpretSize<T, U>(ref array);
var ptr = NativeArrayUnsafeUtility.GetUnsafeBufferPointerWithoutChecks(array);
var result = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<U>(ptr, (int)uLen, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var handle = NativeArrayUnsafeUtility.GetAtomicSafetyHandle(array);
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref result, handle);
#endif
return result;
}
/// <summary>
/// Returns true if this array and another have equal length and content.
/// </summary>
/// <typeparam name="T">The type of the source array's elements.</typeparam>
/// <param name="container">The array to compare for equality.</param>
/// <param name="other">The other array to compare for equality.</param>
/// <returns>True if the arrays have equal length and content.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public static bool ArraysEqual<T>(this NativeArray<T> container, NativeArray<T> other)
where T : unmanaged, IEquatable<T>
{
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;
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void CheckReinterpretSize<T, U>(ref NativeArray<T> array)
where U : unmanaged
where T : unmanaged
{
var tSize = sizeof(T);
var uSize = UnsafeUtility.SizeOf<U>();
var byteLen = ((long)array.Length) * tSize;
var uLen = byteLen / uSize;
if (uLen * uSize != byteLen)
{
throw new InvalidOperationException($"Types {typeof(T)} (array length {array.Length}) and {typeof(U)} cannot be aliased due to size constraints. The size of the types and lengths involved must line up.");
}
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
internal static void Initialize<T>(ref this NativeArray<T> array,
int length,
AllocatorManager.AllocatorHandle allocator,
NativeArrayOptions options = NativeArrayOptions.ClearMemory)
where T : unmanaged
{
AllocatorHandle handle = allocator;
array = default;
array.m_Buffer = handle.AllocateStruct(default(T), length);
array.m_Length = length;
array.m_AllocatorLabel = allocator.IsAutoDispose ? Allocator.None : allocator.ToAllocator;
if (options == NativeArrayOptions.ClearMemory)
{
UnsafeUtility.MemClear(array.m_Buffer, (long)array.m_Length * sizeof(T));
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
array.m_MinIndex = 0;
array.m_MaxIndex = length - 1;
array.m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
CollectionHelper.SetStaticSafetyId<NativeArray<T>>(ref array.m_Safety, ref NativeArrayStaticId<T>.s_staticSafetyId.Data);
handle.AddSafetyHandle(array.m_Safety);
#endif
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(AllocatorManager.AllocatorHandle) })]
internal static void Initialize<T, U>(ref this NativeArray<T> array,
int length,
ref U allocator,
NativeArrayOptions options = NativeArrayOptions.ClearMemory)
where T : unmanaged
where U : unmanaged, AllocatorManager.IAllocator
{
array = default;
array.m_Buffer = allocator.AllocateStruct(default(T), length);
array.m_Length = length;
array.m_AllocatorLabel = allocator.IsAutoDispose ? Allocator.None : allocator.ToAllocator;
if (options == NativeArrayOptions.ClearMemory)
{
UnsafeUtility.MemClear(array.m_Buffer, (long)array.m_Length * sizeof(T));
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
array.m_MinIndex = 0;
array.m_MaxIndex = length - 1;
array.m_Safety = CollectionHelper.CreateSafetyHandle(allocator.ToAllocator);
CollectionHelper.SetStaticSafetyId<NativeArray<T>>(ref array.m_Safety, ref NativeArrayStaticId<T>.s_staticSafetyId.Data);
allocator.Handle.AddSafetyHandle(array.m_Safety);
#endif
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
internal static void DisposeCheckAllocator<T>(ref this NativeArray<T> array)
where T : unmanaged
{
if (array.m_Buffer == null)
{
throw new ObjectDisposedException("The NativeArray is already disposed.");
}
if (!AllocatorManager.IsCustomAllocator(array.m_AllocatorLabel))
{
array.Dispose();
}
else
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.DisposeHandle(ref array.m_Safety);
#endif
AllocatorManager.Free(array.m_AllocatorLabel, array.m_Buffer);
array.m_AllocatorLabel = Allocator.Invalid;
array.m_Buffer = null;
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 41cc650015014737ae58d20e77323080
timeCreated: 1515914094
@@ -0,0 +1,714 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using static Unity.Collections.AllocatorManager;
namespace Unity.Collections
{
/// <summary>
/// An arbitrarily-sized array of bits.
/// </summary>
/// <remarks>
/// The number of allocated bytes is always a multiple of 8. For example, a 65-bit array could fit in 9 bytes, but its allocation is actually 16 bytes.
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
[NativeContainer]
[DebuggerDisplay("Length = {Length}, IsCreated = {IsCreated}")]
[GenerateTestsForBurstCompatibility]
public unsafe struct NativeBitArray
: INativeDisposable
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeBitArray>();
#endif
[NativeDisableUnsafePtrRestriction]
internal UnsafeBitArray* m_BitArray;
internal AllocatorHandle m_Allocator;
/// <summary>
/// Initializes and returns an instance of NativeBitArray.
/// </summary>
/// <param name="numBits">The number of bits.</param>
/// <param name="allocator">The allocator to use.</param>
/// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
public NativeBitArray(int numBits, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
{
CollectionHelper.CheckAllocator(allocator);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
CollectionHelper.SetStaticSafetyId(ref m_Safety, ref s_staticSafetyId.Data, "Unity.Collections.NativeBitArray");
#endif
m_BitArray = UnsafeBitArray.Alloc(allocator);
m_Allocator = allocator;
* m_BitArray = new UnsafeBitArray(numBits, allocator, options);
}
/// <summary>
/// Whether this array has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this array has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated => m_BitArray != null && m_BitArray->IsCreated;
/// <summary>
/// Whether the container is empty.
/// </summary>
/// <value>True if the container is empty or the container has not been constructed.</value>
public readonly bool IsEmpty => !IsCreated || Length == 0;
/// <summary>
/// Sets the length, expanding the capacity if necessary.
/// </summary>
/// <param name="numBits">The new length in bits.</param>
/// <param name="options">Whether newly allocated data should be zeroed out.</param>
public void Resize(int numBits, NativeArrayOptions options = NativeArrayOptions.UninitializedMemory)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
m_BitArray->Resize(numBits, options);
}
/// <summary>
/// Sets the capacity.
/// </summary>
/// <param name="capacityInBits">The new capacity.</param>
public void SetCapacity(int capacityInBits)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
m_BitArray->SetCapacity(capacityInBits);
}
/// <summary>
/// Sets the capacity to match what it would be if it had been originally initialized with all its entries.
/// </summary>
public void TrimExcess()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
m_BitArray->TrimExcess();
}
/// <summary>
/// Releases all resources (memory and safety handles).
/// </summary>
public void Dispose()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.DisposeSafetyHandle(ref m_Safety);
#endif
UnsafeBitArray.Free(m_BitArray, m_Allocator);
m_BitArray = null;
m_Allocator = Invalid;
}
/// <summary>
/// Creates and schedules a job that will dispose this array.
/// </summary>
/// <param name="inputDeps">The handle of a job which the new job will depend upon.</param>
/// <returns>The handle of a new job that will dispose this array. The new job depends upon inputDeps.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return inputDeps;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var jobHandle = new NativeBitArrayDisposeJob { Data = new NativeBitArrayDispose { m_BitArrayData = m_BitArray, m_Allocator = m_Allocator, m_Safety = m_Safety } }.Schedule(inputDeps);
AtomicSafetyHandle.Release(m_Safety);
#else
var jobHandle = new NativeBitArrayDisposeJob { Data = new NativeBitArrayDispose { m_BitArrayData = m_BitArray, m_Allocator = m_Allocator } }.Schedule(inputDeps);
#endif
m_BitArray = null;
m_Allocator = Invalid;
return jobHandle;
}
/// <summary>
/// Returns the number of bits.
/// </summary>
/// <value>The number of bits.</value>
public readonly int Length
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return CollectionHelper.AssumePositive(m_BitArray->Length);
}
}
/// <summary>
/// Returns the capacity number of bits.
/// </summary>
/// <value>The capacity number of bits.</value>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return CollectionHelper.AssumePositive(m_BitArray->Capacity);
}
}
/// <summary>
/// The maximum number of elements this type of container can hold.
/// </summary>
public const int MaxCapacity = UnsafeBitArray.MaxCapacity;
/// <summary>
/// Sets all the bits to 0.
/// </summary>
public void Clear()
{
CheckWrite();
m_BitArray->Clear();
}
/// <summary>
/// Returns a native array that aliases the content of this array.
/// </summary>
/// <typeparam name="T">The type of elements in the aliased array.</typeparam>
/// <exception cref="InvalidOperationException">Thrown if the number of bits in this array
/// is not evenly divisible by the size of T in bits (`sizeof(T) * 8`).</exception>
/// <returns>A native array that aliases the content of this array.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public NativeArray<T> AsNativeArray<T>() where T : unmanaged
{
CheckReadBounds<T>();
var bitsPerElement = sizeof(T) * 8;
var length = m_BitArray->Length / bitsPerElement;
var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(m_BitArray->Ptr, length, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.UseSecondaryVersion(ref m_Safety);
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, m_Safety);
#endif
return array;
}
/// <summary>
/// Sets the bit at an index to 0 or 1.
/// </summary>
/// <param name="pos">Index of the bit to set.</param>
/// <param name="value">True for 1, false for 0.</param>
public void Set(int pos, bool value)
{
CheckWrite();
m_BitArray->Set(pos, value);
}
/// <summary>
/// Sets a range of bits to 0 or 1.
/// </summary>
/// <remarks>
/// The range runs from index `pos` up to (but not including) `pos + numBits`.
/// No exception is thrown if `pos + numBits` exceeds the length.
/// </remarks>
/// <param name="pos">Index of the first bit to set.</param>
/// <param name="value">True for 1, false for 0.</param>
/// <param name="numBits">Number of bits to set.</param>
/// <exception cref="ArgumentException">Thrown if pos is out of bounds or if numBits is less than 1.</exception>
public void SetBits(int pos, bool value, int numBits)
{
CheckWrite();
m_BitArray->SetBits(pos, value, numBits);
}
/// <summary>
/// Copies bits of a ulong to bits in this array.
/// </summary>
/// <remarks>
/// The destination bits in this array run from index pos up to (but not including) `pos + numBits`.
/// No exception is thrown if `pos + numBits` exceeds the length.
///
/// The lowest bit of the ulong is copied to the first destination bit; the second-lowest bit of the ulong is
/// copied to the second destination bit; and so forth.
/// </remarks>
/// <param name="pos">Index of the first bit to set.</param>
/// <param name="value">Unsigned long from which to copy bits.</param>
/// <param name="numBits">Number of bits to set (must be between 1 and 64).</param>
/// <exception cref="ArgumentException">Thrown if pos is out of bounds or if numBits is not between 1 and 64.</exception>
public void SetBits(int pos, ulong value, int numBits = 1)
{
CheckWrite();
m_BitArray->SetBits(pos, value, numBits);
}
/// <summary>
/// Returns a ulong which has bits copied from this array.
/// </summary>
/// <remarks>
/// The source bits in this array run from index pos up to (but not including) `pos + numBits`.
/// No exception is thrown if `pos + numBits` exceeds the length.
///
/// The first source bit is copied to the lowest bit of the ulong; the second source bit is copied to the second-lowest bit of the ulong; and so forth. Any remaining bits in the ulong will be 0.
/// </remarks>
/// <param name="pos">Index of the first bit to get.</param>
/// <param name="numBits">Number of bits to get (must be between 1 and 64).</param>
/// <exception cref="ArgumentException">Thrown if pos is out of bounds or if numBits is not between 1 and 64.</exception>
/// <returns>A ulong which has bits copied from this array.</returns>
public ulong GetBits(int pos, int numBits = 1)
{
CheckRead();
return m_BitArray->GetBits(pos, numBits);
}
/// <summary>
/// Returns true if the bit at an index is 1.
/// </summary>
/// <param name="pos">Index of the bit to test.</param>
/// <returns>True if the bit at the index is 1.</returns>
/// <exception cref="ArgumentException">Thrown if `pos` is out of bounds.</exception>
public bool IsSet(int pos)
{
CheckRead();
return m_BitArray->IsSet(pos);
}
/// <summary>
/// Copies a range of bits from this array to another range in this array.
/// </summary>
/// <remarks>
/// The bits to copy run from index `srcPos` up to (but not including) `srcPos + numBits`.
/// The bits to set run from index `dstPos` up to (but not including) `dstPos + numBits`.
///
/// The ranges may overlap, but the result in the overlapping region is undefined.
/// </remarks>
/// <param name="dstPos">Index of the first bit to set.</param>
/// <param name="srcPos">Index of the first bit to copy.</param>
/// <param name="numBits">Number of bits to copy.</param>
/// <exception cref="ArgumentException">Thrown if either `dstPos + numBits` or `srcPos + numBits` exceed the length of this array.</exception>
public void Copy(int dstPos, int srcPos, int numBits)
{
CheckWrite();
m_BitArray->Copy(dstPos, srcPos, numBits);
}
/// <summary>
/// Copies a range of bits from an array to a range of bits in this array.
/// </summary>
/// <remarks>
/// The bits to copy in the source array run from index srcPos up to (but not including) `srcPos + numBits`.
/// The bits to set in the destination array run from index dstPos up to (but not including) `dstPos + numBits`.
///
/// When the source and destination are the same array, the ranges may still overlap, but the result in the overlapping region is undefined.
/// </remarks>
/// <param name="dstPos">Index of the first bit to set.</param>
/// <param name="srcBitArray">The source array.</param>
/// <param name="srcPos">Index of the first bit to copy.</param>
/// <param name="numBits">The number of bits to copy.</param>
/// <exception cref="ArgumentException">Thrown if either `dstPos + numBits` or `srcBitArray + numBits` exceed the length of this array.</exception>
public void Copy(int dstPos, ref NativeBitArray srcBitArray, int srcPos, int numBits)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(srcBitArray.m_Safety);
#endif
CheckWrite();
m_BitArray->Copy(dstPos, ref *srcBitArray.m_BitArray, srcPos, numBits);
}
/// <summary>
/// Find a sequence of N contiguous 0 bits in a bit array. To achieve higher performance, it is not guaranteed that the found index is necessarily the first occurrence of such a sequence.
/// </summary>
/// <remarks>The search does not guarantee the earliest occurrence in the array.</remarks>
/// <param name="pos">Index at which to start searching.</param>
/// <param name="numBits">Number of contiguous 0 bits to look for.</param>
/// <returns>The index in this array where the sequence is found. The index will be greater than or equal to `pos`.
/// Returns -1 if no occurrence is found.</returns>
public int Find(int pos, int numBits)
{
CheckRead();
return m_BitArray->Find(pos, numBits);
}
/// <summary>
/// Find a sequence of N contiguous 0 bits in a bit array. To achieve higher performance, it is not guaranteed that the found index is necessarily the first occurrence of such a sequence.
/// </summary>
/// <remarks>The search does not guarantee the earliest occurrence in the array.</remarks>
/// <param name="pos">Index at which to start searching.</param>
/// <param name="numBits">Number of contiguous 0 bits to look for.</param>
/// <param name="count">Number of bits to search.</param>
/// <returns>The index in this array where the sequence is found. The index will be greater than or equal to `pos` but less than `pos + count`.
/// Returns -1 if no occurrence is found.</returns>
public int Find(int pos, int count, int numBits)
{
CheckRead();
return m_BitArray->Find(pos, count, numBits);
}
/// <summary>
/// Returns true if none of the bits in a range are 1 (*i.e.* all bits in the range are 0).
/// </summary>
/// <param name="pos">Index of the bit at which to start searching.</param>
/// <param name="numBits">Number of bits to test. Defaults to 1.</param>
/// <returns>Returns true if none of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
/// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
public bool TestNone(int pos, int numBits = 1)
{
CheckRead();
return m_BitArray->TestNone(pos, numBits);
}
/// <summary>
/// Returns true if at least one of the bits in a range is 1.
/// </summary>
/// <param name="pos">Index of the bit at which to start searching.</param>
/// <param name="numBits">Number of bits to test. Defaults to 1.</param>
/// <returns>True if one ore more of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
/// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
public bool TestAny(int pos, int numBits = 1)
{
CheckRead();
return m_BitArray->TestAny(pos, numBits);
}
/// <summary>
/// Returns true if all of the bits in a range are 1.
/// </summary>
/// <param name="pos">Index of the bit at which to start searching.</param>
/// <param name="numBits">Number of bits to test. Defaults to 1.</param>
/// <returns>True if all of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
/// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
public bool TestAll(int pos, int numBits = 1)
{
CheckRead();
return m_BitArray->TestAll(pos, numBits);
}
/// <summary>
/// Returns the number of bits in a range that are 1.
/// </summary>
/// <param name="pos">Index of the bit at which to start searching.</param>
/// <param name="numBits">Number of bits to test. Defaults to 1.</param>
/// <returns>The number of bits in a range of bits that are 1.</returns>
/// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
public int CountBits(int pos, int numBits = 1)
{
CheckRead();
return m_BitArray->CountBits(pos, numBits);
}
/// <summary>
/// Returns a readonly version of this NativeBitArray instance.
/// </summary>
/// <remarks>ReadOnly containers point to the same underlying data as the NativeBitArray it is made from.</remarks>
/// <returns>ReadOnly instance for this.</returns>
public ReadOnly AsReadOnly()
{
return new ReadOnly(ref this);
}
/// <summary>
/// A read-only alias for the value of a UnsafeBitArray. Does not have its own allocated storage.
/// </summary>
[NativeContainer]
[NativeContainerIsReadOnly]
public struct ReadOnly
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
#endif
[NativeDisableUnsafePtrRestriction]
internal UnsafeBitArray.ReadOnly m_BitArray;
/// <summary>
/// Whether this array has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this array has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated => m_BitArray.IsCreated;
/// <summary>
/// Whether the container is empty.
/// </summary>
/// <value>True if the container is empty or the container has not been constructed.</value>
public readonly bool IsEmpty => m_BitArray.IsEmpty;
internal ReadOnly(ref NativeBitArray data)
{
m_BitArray = data.m_BitArray->AsReadOnly();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = data.m_Safety;
CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
#endif
}
/// <summary>
/// Returns the number of bits.
/// </summary>
/// <value>The number of bits.</value>
public readonly int Length
{
get
{
CheckRead();
return CollectionHelper.AssumePositive(m_BitArray.Length);
}
}
/// <summary>
/// Returns a ulong which has bits copied from this array.
/// </summary>
/// <remarks>
/// The source bits in this array run from index pos up to (but not including) `pos + numBits`.
/// No exception is thrown if `pos + numBits` exceeds the length.
///
/// The first source bit is copied to the lowest bit of the ulong; the second source bit is copied to the second-lowest bit of the ulong; and so forth. Any remaining bits in the ulong will be 0.
/// </remarks>
/// <param name="pos">Index of the first bit to get.</param>
/// <param name="numBits">Number of bits to get (must be between 1 and 64).</param>
/// <exception cref="ArgumentException">Thrown if pos is out of bounds or if numBits is not between 1 and 64.</exception>
/// <returns>A ulong which has bits copied from this array.</returns>
public readonly ulong GetBits(int pos, int numBits = 1)
{
CheckRead();
return m_BitArray.GetBits(pos, numBits);
}
/// <summary>
/// Returns true if the bit at an index is 1.
/// </summary>
/// <param name="pos">Index of the bit to test.</param>
/// <returns>True if the bit at the index is 1.</returns>
/// <exception cref="ArgumentException">Thrown if `pos` is out of bounds.</exception>
public readonly bool IsSet(int pos)
{
CheckRead();
return m_BitArray.IsSet(pos);
}
/// <summary>
/// Finds the first length-*N* contiguous sequence of 0 bits in this bit array.
/// </summary>
/// <param name="pos">Index at which to start searching.</param>
/// <param name="numBits">Number of contiguous 0 bits to look for.</param>
/// <returns>The index in this array where the sequence is found. The index will be greater than or equal to `pos`.
/// Returns -1 if no occurrence is found.</returns>
public readonly int Find(int pos, int numBits)
{
CheckRead();
return m_BitArray.Find(pos, numBits);
}
/// <summary>
/// Finds the first length-*N* contiguous sequence of 0 bits in this bit array. Searches only a subsection.
/// </summary>
/// <param name="pos">Index at which to start searching.</param>
/// <param name="numBits">Number of contiguous 0 bits to look for.</param>
/// <param name="count">Number of bits to search.</param>
/// <returns>The index in this array where the sequence is found. The index will be greater than or equal to `pos` but less than `pos + count`.
/// Returns -1 if no occurrence is found.</returns>
public readonly int Find(int pos, int count, int numBits)
{
CheckRead();
return m_BitArray.Find(pos, count, numBits);
}
/// <summary>
/// Returns true if none of the bits in a range are 1 (*i.e.* all bits in the range are 0).
/// </summary>
/// <param name="pos">Index of the bit at which to start searching.</param>
/// <param name="numBits">Number of bits to test. Defaults to 1.</param>
/// <returns>Returns true if none of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
/// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
public readonly bool TestNone(int pos, int numBits = 1)
{
CheckRead();
return m_BitArray.TestNone(pos, numBits);
}
/// <summary>
/// Returns true if at least one of the bits in a range is 1.
/// </summary>
/// <param name="pos">Index of the bit at which to start searching.</param>
/// <param name="numBits">Number of bits to test. Defaults to 1.</param>
/// <returns>True if one ore more of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
/// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
public readonly bool TestAny(int pos, int numBits = 1)
{
CheckRead();
return m_BitArray.TestAny(pos, numBits);
}
/// <summary>
/// Returns true if all of the bits in a range are 1.
/// </summary>
/// <param name="pos">Index of the bit at which to start searching.</param>
/// <param name="numBits">Number of bits to test. Defaults to 1.</param>
/// <returns>True if all of the bits in range `pos` up to (but not including) `pos + numBits` are 1.</returns>
/// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
public readonly bool TestAll(int pos, int numBits = 1)
{
CheckRead();
return m_BitArray.TestAll(pos, numBits);
}
/// <summary>
/// Returns the number of bits in a range that are 1.
/// </summary>
/// <param name="pos">Index of the bit at which to start searching.</param>
/// <param name="numBits">Number of bits to test. Defaults to 1.</param>
/// <returns>The number of bits in a range of bits that are 1.</returns>
/// <exception cref="ArgumentException">Thrown if `pos` is out of bounds or `numBits` is less than 1.</exception>
public readonly int CountBits(int pos, int numBits = 1)
{
CheckRead();
return m_BitArray.CountBits(pos, numBits);
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckReadBounds<T>() where T : unmanaged
{
CheckRead();
var bitsPerElement = sizeof(T) * 8;
var length = m_BitArray->Length / bitsPerElement;
if (length == 0)
{
throw new InvalidOperationException($"Number of bits in the NativeBitArray {m_BitArray->Length} is not sufficient to cast to NativeArray<T> {sizeof(T) * 8}.");
}
else if (m_BitArray->Length != bitsPerElement* length)
{
throw new InvalidOperationException($"Number of bits in the NativeBitArray {m_BitArray->Length} couldn't hold multiple of T {sizeof(T)}. Output array would be truncated.");
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
void CheckWrite()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
}
}
[NativeContainer]
[GenerateTestsForBurstCompatibility]
internal unsafe struct NativeBitArrayDispose
{
[NativeDisableUnsafePtrRestriction]
public UnsafeBitArray* m_BitArrayData;
public AllocatorHandle m_Allocator;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
public AtomicSafetyHandle m_Safety;
#endif
public void Dispose()
{
UnsafeBitArray.Free(m_BitArrayData, m_Allocator);
}
}
[BurstCompile]
internal unsafe struct NativeBitArrayDisposeJob : IJob
{
public NativeBitArrayDispose Data;
public void Execute()
{
Data.Dispose();
}
}
}
namespace Unity.Collections.LowLevel.Unsafe
{
/// <summary>
/// Unsafe helper methods for NativeBitArray.
/// </summary>
[GenerateTestsForBurstCompatibility]
public static class NativeBitArrayUnsafeUtility
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
/// <summary>
/// Returns an array's atomic safety handle.
/// </summary>
/// <param name="container">Array from which to get an AtomicSafetyHandle.</param>
/// <returns>This array's atomic safety handle.</returns>
[GenerateTestsForBurstCompatibility(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS", CompileTarget = GenerateTestsForBurstCompatibilityAttribute.BurstCompatibleCompileTarget.Editor)]
public static AtomicSafetyHandle GetAtomicSafetyHandle(in NativeBitArray container)
{
return container.m_Safety;
}
/// <summary>
/// Sets an array's atomic safety handle.
/// </summary>
/// <param name="container">Array which the AtomicSafetyHandle is for.</param>
/// <param name="safety">Atomic safety handle for this array.</param>
[GenerateTestsForBurstCompatibility(RequiredUnityDefine = "ENABLE_UNITY_COLLECTIONS_CHECKS", CompileTarget = GenerateTestsForBurstCompatibilityAttribute.BurstCompatibleCompileTarget.Editor)]
public static void SetAtomicSafetyHandle(ref NativeBitArray container, AtomicSafetyHandle safety)
{
container.m_Safety = safety;
}
#endif
/// <summary>
/// Returns a bit array with content aliasing a buffer.
/// </summary>
/// <param name="ptr">A buffer.</param>
/// <param name="sizeInBytes">Size of the buffer in bytes. Must be a multiple of 8.</param>
/// <param name="allocator">The allocator that was used to create the buffer.</param>
/// <returns>A bit array with content aliasing a buffer.</returns>
public static unsafe NativeBitArray ConvertExistingDataToNativeBitArray(void* ptr, int sizeInBytes, AllocatorManager.AllocatorHandle allocator)
{
var bitArray = UnsafeBitArray.Alloc(Allocator.Persistent);
*bitArray = new UnsafeBitArray(ptr, sizeInBytes, allocator);
return new NativeBitArray
{
m_BitArray = bitArray,
m_Allocator = Allocator.Persistent,
};
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e4640e45632730349a32c5a1365847e6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,865 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
namespace Unity.Collections
{
[NativeContainer]
[GenerateTestsForBurstCompatibility]
internal unsafe struct NativeHashMapDispose
{
[NativeDisableUnsafePtrRestriction]
internal UnsafeHashMap<int, int>* m_HashMapData;
internal AllocatorManager.AllocatorHandle m_Allocator;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
#endif
internal void Dispose()
{
var hashMapData = (HashMapHelper<int>*)m_HashMapData;
HashMapHelper<int>.Free(hashMapData);
}
}
[BurstCompile]
internal unsafe struct NativeHashMapDisposeJob : IJob
{
internal NativeHashMapDispose Data;
public void Execute()
{
Data.Dispose();
}
}
/// <summary>
/// A key-value pair.
/// </summary>
/// <remarks>Used for enumerators.</remarks>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
[DebuggerDisplay("Key = {Key}, Value = {Value}")]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public unsafe struct KVPair<TKey, TValue>
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
{
internal HashMapHelper<TKey>* m_Data;
internal int m_Index;
internal int m_Next;
/// <summary>
/// An invalid KeyValue.
/// </summary>
/// <value>In a hash map enumerator's initial state, its <see cref="UnsafeHashMap{TKey,TValue}.Enumerator.Current"/> value is Null.</value>
public static KVPair<TKey, TValue> Null => new KVPair<TKey, TValue> { m_Index = -1 };
/// <summary>
/// The key.
/// </summary>
/// <value>The key. If this KeyValue is Null, returns the default of TKey.</value>
public TKey Key
{
get
{
if (m_Index != -1)
{
return m_Data->Keys[m_Index];
}
return default;
}
}
/// <summary>
/// Value of key/value pair.
/// </summary>
public ref TValue Value
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
if (m_Index == -1)
throw new ArgumentException("must be valid");
#endif
return ref UnsafeUtility.AsRef<TValue>(m_Data->Ptr + sizeof(TValue) * m_Index);
}
}
/// <summary>
/// Gets the key and the value.
/// </summary>
/// <param name="key">Outputs the key. If this KeyValue is Null, outputs the default of TKey.</param>
/// <param name="value">Outputs the value. If this KeyValue is Null, outputs the default of TValue.</param>
/// <returns>True if the key-value pair is valid.</returns>
public bool GetKeyValue(out TKey key, out TValue value)
{
if (m_Index != -1)
{
key = m_Data->Keys[m_Index];
value = UnsafeUtility.ReadArrayElement<TValue>(m_Data->Ptr, m_Index);
return true;
}
key = default;
value = default;
return false;
}
}
/// <summary>
/// An unordered, expandable associative array.
/// </summary>
/// <remarks>
/// Not suitable for parallel write access. Use <see cref="NativeParallelHashMap{TKey, TValue}"/> instead.
/// </remarks>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
[StructLayout(LayoutKind.Sequential)]
[NativeContainer]
[DebuggerTypeProxy(typeof(NativeHashMapDebuggerTypeProxy<,>))]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public unsafe struct NativeHashMap<TKey, TValue>
: INativeDisposable
, IEnumerable<KVPair<TKey, TValue>> // Used by collection initializers.
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
{
[NativeDisableUnsafePtrRestriction]
internal HashMapHelper<TKey>* m_Data;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeHashMap<TKey, TValue>>();
#endif
/// <summary>
/// Initializes and returns an instance of UnsafeHashMap.
/// </summary>
/// <param name="initialCapacity">The number of key-value pairs that should fit in the initial allocation.</param>
/// <param name="allocator">The allocator to use.</param>
public NativeHashMap(int initialCapacity, AllocatorManager.AllocatorHandle allocator)
{
m_Data = HashMapHelper<TKey>.Alloc(initialCapacity, sizeof(TValue), HashMapHelper<TKey>.kMinCapacity, allocator);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
if (UnsafeUtility.IsNativeContainerType<TKey>() || UnsafeUtility.IsNativeContainerType<TValue>())
AtomicSafetyHandle.SetNestedContainer(m_Safety, true);
CollectionHelper.SetStaticSafetyId<NativeHashMap<TKey, TValue>>(ref m_Safety, ref s_staticSafetyId.Data);
AtomicSafetyHandle.SetBumpSecondaryVersionOnScheduleWrite(m_Safety, true);
#endif
}
/// <summary>
/// Releases all resources (memory).
/// </summary>
public void Dispose()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.DisposeSafetyHandle(ref m_Safety);
#endif
HashMapHelper<TKey>.Free(m_Data);
m_Data = null;
}
/// <summary>
/// Creates and schedules a job that will dispose this hash map.
/// </summary>
/// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
/// <returns>The handle of a new job that will dispose this hash map.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return inputDeps;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var jobHandle = new NativeHashMapDisposeJob { Data = new NativeHashMapDispose { m_HashMapData = (UnsafeHashMap<int, int>*)m_Data, m_Safety = m_Safety } }.Schedule(inputDeps);
AtomicSafetyHandle.Release(m_Safety);
#else
var jobHandle = new NativeHashMapDisposeJob { Data = new NativeHashMapDispose { m_HashMapData = (UnsafeHashMap<int, int>*)m_Data } }.Schedule(inputDeps);
#endif
m_Data = null;
return jobHandle;
}
/// <summary>
/// Whether this hash map has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this hash map has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Data != null && m_Data->IsCreated;
}
/// <summary>
/// Whether this hash map is empty.
/// </summary>
/// <value>True if this hash map is empty or if the map has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (!IsCreated)
{
return true;
}
CheckRead();
return m_Data->IsEmpty;
}
}
/// <summary>
/// The current number of key-value pairs in this hash map.
/// </summary>
/// <returns>The current number of key-value pairs in this hash map.</returns>
public readonly int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return m_Data->Count;
}
}
/// <summary>
/// The number of key-value pairs that fit in the current allocation.
/// </summary>
/// <value>The number of key-value pairs that fit in the current allocation.</value>
/// <param name="value">A new capacity. Must be larger than the current capacity.</param>
public int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get
{
CheckRead();
return m_Data->Capacity;
}
set
{
CheckWrite();
m_Data->Resize(value);
}
}
/// <summary>
/// The maximum number of elements this type of container can hold.
/// </summary>
public const int MaxCapacity = HashMapHelper<TKey>.kMaxCapacity;
/// <summary>
/// Removes all key-value pairs.
/// </summary>
/// <remarks>Does not change the capacity.</remarks>
public void Clear()
{
CheckWrite();
m_Data->Clear();
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>If the key is already present, this method returns false without modifying the hash map.</remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <returns>True if the key-value pair was added.</returns>
public bool TryAdd(TKey key, TValue item)
{
CheckWrite();
var idx = m_Data->TryAdd(key);
if (-1 != idx)
{
UnsafeUtility.WriteArrayElement(m_Data->Ptr, idx, item);
return true;
}
return false;
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>If the key is already present, this method throws without modifying the hash map.</remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <exception cref="ArgumentException">Thrown if the key was already present.</exception>
/// <exception cref="InvalidOperationException">Thrown if there is not enough Capacity to contain the added element, and the container can't be resized.</exception>
public void Add(TKey key, TValue item)
{
CheckWrite();
var idx = m_Data->TryAdd(key);
if (-1 != idx)
{
UnsafeUtility.WriteArrayElement(m_Data->Ptr, idx, item);
return;
}
if (Capacity == MaxCapacity)
{
ThrowAtMaxCapacity();
return;
}
ThrowKeyAlreadyAdded(key);
}
/// <summary>
/// Removes a key-value pair.
/// </summary>
/// <param name="key">The key to remove.</param>
/// <returns>True if a key-value pair was removed.</returns>
public bool Remove(TKey key)
{
CheckWrite();
return -1 != m_Data->TryRemove(key);
}
/// <summary>
/// Returns the value associated with a key.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <param name="item">Outputs the value associated with the key. Outputs default if the key was not present.</param>
/// <returns>True if the key was present.</returns>
public bool TryGetValue(TKey key, out TValue item)
{
CheckRead();
return m_Data->TryGetValue(key, out item);
}
/// <summary>
/// Returns true if a given key is present in this hash map.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <returns>True if the key was present.</returns>
public bool ContainsKey(TKey key)
{
CheckRead();
return -1 != m_Data->Find(key);
}
/// <summary>
/// Sets the capacity to match what it would be if it had been originally initialized with all its entries.
/// </summary>
public void TrimExcess()
{
CheckWrite();
m_Data->TrimExcess();
}
/// <summary>
/// Gets and sets values by key.
/// </summary>
/// <remarks>Getting a key that is not present will throw. Setting a key that is not already present will add the key.</remarks>
/// <param name="key">The key to look up.</param>
/// <value>The value associated with the key.</value>
/// <exception cref="ArgumentException">For getting, thrown if the key was not present.</exception>
public TValue this[TKey key]
{
get
{
CheckRead();
TValue result;
if (!m_Data->TryGetValue(key, out result))
{
ThrowKeyNotPresent(key);
}
return result;
}
set
{
CheckWrite();
var idx = m_Data->Find(key);
if (-1 == idx)
{
TryAdd(key, value);
return;
}
UnsafeUtility.WriteArrayElement(m_Data->Ptr, idx, value);
}
}
/// <summary>
/// Returns an array with a copy of all this hash map's keys (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash map's keys (in no particular order).</returns>
public NativeArray<TKey> GetKeyArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_Data->GetKeyArray(allocator);
}
/// <summary>
/// Returns an array with a copy of all this hash map's values (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash map's values (in no particular order).</returns>
public NativeArray<TValue> GetValueArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_Data->GetValueArray<TValue>(allocator);
}
/// <summary>
/// Returns a NativeKeyValueArrays with a copy of all this hash map's keys and values.
/// </summary>
/// <remarks>The key-value pairs are copied in no particular order. For all `i`, `Values[i]` will be the value associated with `Keys[i]`.</remarks>
/// <param name="allocator">The allocator to use.</param>
/// <returns>A NativeKeyValueArrays with a copy of all this hash map's keys and values.</returns>
public NativeKeyValueArrays<TKey, TValue> GetKeyValueArrays(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_Data->GetKeyValueArrays<TValue>(allocator);
}
/// <summary>
/// Returns an enumerator over the key-value pairs of this hash map.
/// </summary>
/// <returns>An enumerator over the key-value pairs of this hash map.</returns>
public Enumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
var ash = m_Safety;
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new Enumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = new HashMapHelper<TKey>.Enumerator(m_Data),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<KVPair<TKey, TValue>> IEnumerable<KVPair<TKey, TValue>>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// An enumerator over the key-value pairs of a container.
/// </summary>
/// <remarks>
/// In an enumerator's initial state, <see cref="Current"/> is not valid to read.
/// From this state, the first <see cref="MoveNext"/> call advances the enumerator to the first key-value pair.
/// </remarks>
[NativeContainer]
[NativeContainerIsReadOnly]
public struct Enumerator : IEnumerator<KVPair<TKey, TValue>>
{
[NativeDisableUnsafePtrRestriction]
internal HashMapHelper<TKey>.Enumerator m_Enumerator;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
#endif
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose() { }
/// <summary>
/// Advances the enumerator to the next key-value pair.
/// </summary>
/// <returns>True if <see cref="Current"/> is valid to read after the call.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Enumerator.MoveNext();
}
/// <summary>
/// Resets the enumerator to its initial state.
/// </summary>
public void Reset()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
m_Enumerator.Reset();
}
/// <summary>
/// The current key-value pair.
/// </summary>
/// <value>The current key-value pair.</value>
public KVPair<TKey, TValue> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Enumerator.GetCurrent<TValue>();
}
/// <summary>
/// Gets the element at the current position of the enumerator in the container.
/// </summary>
object IEnumerator.Current => Current;
}
/// <summary>
/// Returns a readonly version of this NativeHashMap instance.
/// </summary>
/// <remarks>ReadOnly containers point to the same underlying data as the NativeHashMap it is made from.</remarks>
/// <returns>ReadOnly instance for this.</returns>
public ReadOnly AsReadOnly()
{
return new ReadOnly(ref this);
}
/// <summary>
/// A read-only alias for the value of a NativeHashMap. Does not have its own allocated storage.
/// </summary>
[NativeContainer]
[NativeContainerIsReadOnly]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public struct ReadOnly
: IEnumerable<KVPair<TKey, TValue>>
{
[NativeDisableUnsafePtrRestriction]
internal HashMapHelper<TKey>* m_Data;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
#endif
internal ReadOnly(ref NativeHashMap<TKey, TValue> data)
{
m_Data = data.m_Data;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = data.m_Safety;
CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
#endif
}
/// <summary>
/// Whether this hash map has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this hash map has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Data != null && m_Data->IsCreated;
}
/// <summary>
/// Whether this hash map is empty.
/// </summary>
/// <value>True if this hash map is empty or if the map has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (!IsCreated)
{
return true;
}
CheckRead();
return m_Data->IsEmpty;
}
}
/// <summary>
/// The current number of key-value pairs in this hash map.
/// </summary>
/// <returns>The current number of key-value pairs in this hash map.</returns>
public readonly int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return m_Data->Count;
}
}
/// <summary>
/// The number of key-value pairs that fit in the current allocation.
/// </summary>
/// <value>The number of key-value pairs that fit in the current allocation.</value>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return m_Data->Capacity;
}
}
/// <summary>
/// Returns the value associated with a key.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <param name="item">Outputs the value associated with the key. Outputs default if the key was not present.</param>
/// <returns>True if the key was present.</returns>
public readonly bool TryGetValue(TKey key, out TValue item)
{
CheckRead();
return m_Data->TryGetValue(key, out item);
}
/// <summary>
/// Returns true if a given key is present in this hash map.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <returns>True if the key was present.</returns>
public readonly bool ContainsKey(TKey key)
{
CheckRead();
return -1 != m_Data->Find(key);
}
/// <summary>
/// Gets values by key.
/// </summary>
/// <remarks>Getting a key that is not present will throw.</remarks>
/// <param name="key">The key to look up.</param>
/// <value>The value associated with the key.</value>
/// <exception cref="ArgumentException">For getting, thrown if the key was not present.</exception>
public readonly TValue this[TKey key]
{
get
{
CheckRead();
TValue result;
if (!m_Data->TryGetValue(key, out result))
{
ThrowKeyNotPresent(key);
}
return result;
}
}
/// <summary>
/// Returns an array with a copy of all this hash map's keys (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash map's keys (in no particular order).</returns>
public readonly NativeArray<TKey> GetKeyArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_Data->GetKeyArray(allocator);
}
/// <summary>
/// Returns an array with a copy of all this hash map's values (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash map's values (in no particular order).</returns>
public readonly NativeArray<TValue> GetValueArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_Data->GetValueArray<TValue>(allocator);
}
/// <summary>
/// Returns a NativeKeyValueArrays with a copy of all this hash map's keys and values.
/// </summary>
/// <remarks>The key-value pairs are copied in no particular order. For all `i`, `Values[i]` will be the value associated with `Keys[i]`.</remarks>
/// <param name="allocator">The allocator to use.</param>
/// <returns>A NativeKeyValueArrays with a copy of all this hash map's keys and values.</returns>
public readonly NativeKeyValueArrays<TKey, TValue> GetKeyValueArrays(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_Data->GetKeyValueArrays<TValue>(allocator);
}
/// <summary>
/// Returns an enumerator over the key-value pairs of this hash map.
/// </summary>
/// <returns>An enumerator over the key-value pairs of this hash map.</returns>
public readonly Enumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
var ash = m_Safety;
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new Enumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = new HashMapHelper<TKey>.Enumerator(m_Data),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<KVPair<TKey, TValue>> IEnumerable<KVPair<TKey, TValue>>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
readonly void ThrowKeyNotPresent(TKey key)
{
throw new ArgumentException($"Key: {key} is not present.");
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void CheckWrite()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void ThrowKeyNotPresent(TKey key)
{
throw new ArgumentException($"Key: {key} is not present.");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void ThrowKeyAlreadyAdded(TKey key)
{
throw new ArgumentException($"An item with the same key has already been added: {key}");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void ThrowAtMaxCapacity()
{
throw new InvalidOperationException($"Capacity is insufficient, and resize would fail (Capacity {Capacity} / {MaxCapacity}, Count {Count})!");
}
}
internal unsafe sealed class NativeHashMapDebuggerTypeProxy<TKey, TValue>
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
{
HashMapHelper<TKey>* Data;
public NativeHashMapDebuggerTypeProxy(NativeHashMap<TKey, TValue> target)
{
Data = target.m_Data;
}
public NativeHashMapDebuggerTypeProxy(NativeHashMap<TKey, TValue>.ReadOnly target)
{
Data = target.m_Data;
}
public List<Pair<TKey, TValue>> Items
{
get
{
if (Data == null)
{
return default;
}
var result = new List<Pair<TKey, TValue>>();
using (var kva = Data->GetKeyValueArrays<TValue>(Allocator.Temp))
{
for (var i = 0; i < kva.Length; ++i)
{
result.Add(new Pair<TKey, TValue>(kva.Keys[i], kva.Values[i]));
}
}
return result;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0e9b36beea84b894ca71b7dcd8883525
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,582 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Burst;
using System.Runtime.CompilerServices;
namespace Unity.Collections
{
/// <summary>
/// An unordered, expandable set of unique values.
/// </summary>
/// <remarks>
/// Not suitable for parallel write access. Use <see cref="NativeParallelHashSet{T}"/> instead.
/// </remarks>
/// <typeparam name="T">The type of the values.</typeparam>
[StructLayout(LayoutKind.Sequential)]
[NativeContainer]
[DebuggerTypeProxy(typeof(NativeHashSetDebuggerTypeProxy<>))]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public unsafe struct NativeHashSet<T>
: INativeDisposable
, IEnumerable<T> // Used by collection initializers.
where T : unmanaged, IEquatable<T>
{
[NativeDisableUnsafePtrRestriction]
internal HashMapHelper<T>* m_Data;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeHashSet<T>>();
#endif
/// <summary>
/// Initializes and returns an instance of NativeParallelHashSet.
/// </summary>
/// <param name="initialCapacity">The number of values that should fit in the initial allocation.</param>
/// <param name="allocator">The allocator to use.</param>
public NativeHashSet(int initialCapacity, AllocatorManager.AllocatorHandle allocator)
{
m_Data = HashMapHelper<T>.Alloc(initialCapacity, 0, HashMapHelper<T>.kMinCapacity, allocator);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
if (UnsafeUtility.IsNativeContainerType<T>())
AtomicSafetyHandle.SetNestedContainer(m_Safety, true);
CollectionHelper.SetStaticSafetyId<NativeHashSet<T>>(ref m_Safety, ref s_staticSafetyId.Data);
AtomicSafetyHandle.SetBumpSecondaryVersionOnScheduleWrite(m_Safety, true);
#endif
}
/// <summary>
/// Whether this set is empty.
/// </summary>
/// <value>True if this set is empty or if the set has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (!IsCreated)
{
return true;
}
CheckRead();
return m_Data->IsEmpty;
}
}
/// <summary>
/// Returns the current number of values in this set.
/// </summary>
/// <returns>The current number of values in this set.</returns>
public readonly int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return m_Data->Count;
}
}
/// <summary>
/// The number of values that fit in the current allocation.
/// </summary>
/// <value>The number of values that fit in the current allocation.</value>
/// <param name="value">A new capacity. Must be larger than current capacity.</param>
public int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get
{
CheckRead();
return m_Data->Capacity;
}
set
{
CheckWrite();
m_Data->Resize(value);
}
}
/// <summary>
/// The maximum number of elements this type of container can hold.
/// </summary>
public const int MaxCapacity = HashMapHelper<T>.kMaxCapacity;
/// <summary>
/// Whether this set has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this set has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Data != null && m_Data->IsCreated;
}
/// <summary>
/// Releases all resources (memory and safety handles).
/// </summary>
public void Dispose()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.DisposeSafetyHandle(ref m_Safety);
#endif
HashMapHelper<T>.Free(m_Data);
m_Data = null;
}
/// <summary>
/// Creates and schedules a job that will dispose this set.
/// </summary>
/// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
/// <returns>The handle of a new job that will dispose this set.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return inputDeps;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var jobHandle = new NativeHashMapDisposeJob { Data = new NativeHashMapDispose { m_HashMapData = (UnsafeHashMap<int, int>*)m_Data, m_Safety = m_Safety } }.Schedule(inputDeps);
AtomicSafetyHandle.Release(m_Safety);
#else
var jobHandle = new NativeHashMapDisposeJob { Data = new NativeHashMapDispose { m_HashMapData = (UnsafeHashMap<int, int>*)m_Data } }.Schedule(inputDeps);
#endif
m_Data = null;
return jobHandle;
}
/// <summary>
/// Removes all values.
/// </summary>
/// <remarks>Does not change the capacity.</remarks>
public void Clear()
{
CheckWrite();
m_Data->Clear();
}
/// <summary>
/// Adds a new value.
/// If the value is already present in the collection, this method <b>should</b> throw, but currently does not!
/// Instead, it returns false without replacing said item.
/// </summary>
/// <remarks>
/// Prefer <see cref="TryAdd(T)"/> if your intent is to allow graceful failure, as this API will eventually become more strict (and begin to throw).
/// </remarks>
/// <param name="item">The value to add.</param>
/// <returns>True if the value was not already present.</returns>
public bool Add(T item)
{
CheckWrite();
return -1 != m_Data->TryAdd(item);
}
/// <summary>
/// Attempts to add a new item. Only succeeds if the item was not present.
/// </summary>
/// <param name="item">The value to add.</param>
/// <returns>True if the value was not already present (thus was successfully added).</returns>
public bool TryAdd(T item)
{
CheckWrite();
return -1 != m_Data->TryAdd(item);
}
/// <summary>
/// Removes a particular value.
/// </summary>
/// <param name="item">The value to remove.</param>
/// <returns>True if the value was present.</returns>
public bool Remove(T item)
{
CheckWrite();
return -1 != m_Data->TryRemove(item);
}
/// <summary>
/// Returns true if a particular value is present.
/// </summary>
/// <param name="item">The item to look up.</param>
/// <returns>True if the value was present.</returns>
public bool Contains(T item)
{
CheckRead();
return -1 != m_Data->Find(item);
}
/// <summary>
/// Sets the capacity to match what it would be if it had been originally initialized with all its entries.
/// </summary>
public void TrimExcess()
{
CheckWrite();
m_Data->TrimExcess();
}
/// <summary>
/// Returns an array with a copy of this set's values (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of the set's values.</returns>
public NativeArray<T> ToNativeArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_Data->GetKeyArray(allocator);
}
/// <summary>
/// Returns an enumerator over the values of this set.
/// </summary>
/// <returns>An enumerator over the values of this set.</returns>
public Enumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
var ash = m_Safety;
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new Enumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = new HashMapHelper<T>.Enumerator(m_Data),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// An enumerator over the values of a set.
/// </summary>
/// <remarks>
/// In an enumerator's initial state, <see cref="Current"/> is invalid.
/// The first <see cref="MoveNext"/> call advances the enumerator to the first value.
/// </remarks>
[NativeContainer]
[NativeContainerIsReadOnly]
public struct Enumerator : IEnumerator<T>
{
[NativeDisableUnsafePtrRestriction]
internal HashMapHelper<T>.Enumerator m_Enumerator;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
#endif
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose() { }
/// <summary>
/// Advances the enumerator to the next value.
/// </summary>
/// <returns>True if `Current` is valid to read after the call.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Enumerator.MoveNext();
}
/// <summary>
/// Resets the enumerator to its initial state.
/// </summary>
public void Reset()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
m_Enumerator.Reset();
}
/// <summary>
/// The current value.
/// </summary>
/// <value>The current value.</value>
public T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Enumerator.GetCurrentKey();
}
}
/// <summary>
/// Gets the element at the current position of the enumerator in the container.
/// </summary>
object IEnumerator.Current => Current;
}
/// <summary>
/// Returns a readonly version of this NativeHashSet instance.
/// </summary>
/// <remarks>ReadOnly containers point to the same underlying data as the NativeHashSet it is made from.</remarks>
/// <returns>ReadOnly instance for this.</returns>
public ReadOnly AsReadOnly()
{
return new ReadOnly(ref this);
}
/// <summary>
/// A read-only alias for the value of a NativeHashSet. Does not have its own allocated storage.
/// </summary>
[NativeContainer]
[NativeContainerIsReadOnly]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public struct ReadOnly
: IEnumerable<T>
{
[NativeDisableUnsafePtrRestriction]
internal HashMapHelper<T>* m_Data;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
#endif
internal ReadOnly(ref NativeHashSet<T> data)
{
m_Data = data.m_Data;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = data.m_Safety;
CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
#endif
}
/// <summary>
/// Whether this hash set has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this hash set has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Data != null && m_Data->IsCreated;
}
/// <summary>
/// Whether this hash set is empty.
/// </summary>
/// <value>True if this hash set is empty or if the map has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (!IsCreated)
{
return true;
}
CheckRead();
return m_Data->IsEmpty;
}
}
/// <summary>
/// The current number of items in this hash set.
/// </summary>
/// <returns>The current number of items in this hash set.</returns>
public readonly int Count
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return m_Data->Count;
}
}
/// <summary>
/// The number of items that fit in the current allocation.
/// </summary>
/// <value>The number of items that fit in the current allocation.</value>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return m_Data->Capacity;
}
}
/// <summary>
/// Returns true if a given item is present in this hash set.
/// </summary>
/// <param name="item">The item to look up.</param>
/// <returns>True if the item was present.</returns>
public readonly bool Contains(T item)
{
CheckRead();
return -1 != m_Data->Find(item);
}
/// <summary>
/// Returns an array with a copy of all this hash set's items (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash set's items (in no particular order).</returns>
public readonly NativeArray<T> ToNativeArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_Data->GetKeyArray(allocator);
}
/// <summary>
/// Returns an enumerator over the items of this hash set.
/// </summary>
/// <returns>An enumerator over the items of this hash set.</returns>
public readonly Enumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
var ash = m_Safety;
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new Enumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = new HashMapHelper<T>.Enumerator(m_Data),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void CheckWrite()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
}
}
sealed internal unsafe class NativeHashSetDebuggerTypeProxy<T>
where T : unmanaged, IEquatable<T>
{
HashMapHelper<T>* Data;
public NativeHashSetDebuggerTypeProxy(NativeHashSet<T> data)
{
Data = data.m_Data;
}
public List<T> Items
{
get
{
if (Data == null)
{
return default;
}
var result = new List<T>();
using (var items = Data->GetKeyArray(Allocator.Temp))
{
for (var k = 0; k < items.Length; ++k)
{
result.Add(items[k]);
}
}
return result;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5823667af4bd5fd489bc1a1c24cad9d6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 0ddd82532ba0b41c7af9888fdbc562e1
timeCreated: 1485127823
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,74 @@
//#define USE_NOT_BURST_COMPATIBLE_EXTENSIONS
using System;
using Unity.Collections.LowLevel.Unsafe;
namespace Unity.Collections.NotBurstCompatible
{
/// <summary>
/// Provides some extension methods for various collections.
/// </summary>
public static class Extensions
{
/// <summary>
/// Returns a new managed array with all the elements copied from a set.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <param name="set">The set whose elements are copied to the array.</param>
/// <returns>A new managed array with all the elements copied from a set.</returns>
[ExcludeFromBurstCompatTesting("Returns managed array")]
public static T[] ToArray<T>(this NativeHashSet<T> set)
where T : unmanaged, IEquatable<T>
{
var array = set.ToNativeArray(Allocator.TempJob);
var managed = array.ToArray();
array.Dispose();
return managed;
}
/// <summary>
/// Returns a new managed array with all the elements copied from a set.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <param name="set">The set whose elements are copied to the array.</param>
/// <returns>A new managed array with all the elements copied from a set.</returns>
[ExcludeFromBurstCompatTesting("Returns managed array")]
public static T[] ToArray<T>(this NativeParallelHashSet<T> set)
where T : unmanaged, IEquatable<T>
{
var array = set.ToNativeArray(Allocator.TempJob);
var managed = array.ToArray();
array.Dispose();
return managed;
}
/// <summary>
/// Returns a new managed array which is a copy of this list.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <param name="list">The list to copy.</param>
/// <returns>A new managed array which is a copy of this list.</returns>
[ExcludeFromBurstCompatTesting("Returns managed array")]
public static T[] ToArrayNBC<T>(this NativeList<T> list)
where T : unmanaged
{
return list.AsArray().ToArray();
}
/// <summary>
/// Clears this list and then copies all the elements of an array to this list.
/// </summary>
/// <typeparam name="T">The type of elements.</typeparam>
/// <param name="list">This list.</param>
/// <param name="array">The managed array to copy from.</param>
[ExcludeFromBurstCompatTesting("Takes managed array")]
public static void CopyFromNBC<T>(this NativeList<T> list, T[] array)
where T : unmanaged
{
list.Clear();
list.Resize(array.Length, NativeArrayOptions.UninitializedMemory);
NativeArray<T> na = list.AsArray();
na.CopyFrom(array);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b029fb97ffda0ec4aaa9d76de93a0608
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,914 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using UnityEngine.Assertions;
namespace Unity.Collections
{
/// <summary>
/// The keys and values of a hash map copied into two parallel arrays.
/// </summary>
/// <remarks>For each key-value pair copied from the hash map, the key is stored in `Keys[i]` while the value is stored in `Values[i]` (for the same `i`).
///
/// NativeKeyValueArrays is not actually itself a native collection: it contains a NativeArray for the keys and a NativeArray for the values,
/// but a NativeKeyValueArrays does not have its own safety handles.</remarks>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public struct NativeKeyValueArrays<TKey, TValue>
: INativeDisposable
where TKey : unmanaged
where TValue : unmanaged
{
/// <summary>
/// The keys.
/// </summary>
/// <value>The keys. The key at `Keys[i]` is paired with the value at `Values[i]`.</value>
public NativeArray<TKey> Keys;
/// <summary>
/// The values.
/// </summary>
/// <value>The values. The value at `Values[i]` is paired with the key at `Keys[i]`.</value>
public NativeArray<TValue> Values;
/// <summary>
/// The number of key-value pairs.
/// </summary>
/// <value>The number of key-value pairs.</value>
public int Length => Keys.Length;
/// <summary>
/// Initializes and returns an instance of NativeKeyValueArrays.
/// </summary>
/// <param name="length">The number of keys-value pairs.</param>
/// <param name="allocator">The allocator to use.</param>
/// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
public NativeKeyValueArrays(int length, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options)
{
Keys = CollectionHelper.CreateNativeArray<TKey>(length, allocator, options);
Values = CollectionHelper.CreateNativeArray<TValue>(length, allocator, options);
}
/// <summary>
/// Releases all resources (memory and safety handles).
/// </summary>
public void Dispose()
{
Keys.Dispose();
Values.Dispose();
}
/// <summary>
/// Creates and schedules a job that will dispose this collection's key and value arrays.
/// </summary>
/// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
/// <returns>The handle of a new job that will dispose this collection's key and value arrays.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
return Keys.Dispose(Values.Dispose(inputDeps));
}
}
/// <summary>
/// An unordered, expandable associative array.
/// </summary>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
[StructLayout(LayoutKind.Sequential)]
[NativeContainer]
[DebuggerDisplay("Count = {m_HashMapData.Count()}, Capacity = {m_HashMapData.Capacity}, IsCreated = {m_HashMapData.IsCreated}, IsEmpty = {IsEmpty}")]
[DebuggerTypeProxy(typeof(NativeParallelHashMapDebuggerTypeProxy<,>))]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public unsafe struct NativeParallelHashMap<TKey, TValue>
: INativeDisposable
, IEnumerable<KeyValue<TKey, TValue>> // Used by collection initializers.
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
{
internal UnsafeParallelHashMap<TKey, TValue> m_HashMapData;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeParallelHashMap<TKey, TValue>>();
#endif
/// <summary>
/// Initializes and returns an instance of NativeParallelHashMap.
/// </summary>
/// <param name="capacity">The number of key-value pairs that should fit in the initial allocation.</param>
/// <param name="allocator">The allocator to use.</param>
public NativeParallelHashMap(int capacity, AllocatorManager.AllocatorHandle allocator)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
if (UnsafeUtility.IsNativeContainerType<TKey>() || UnsafeUtility.IsNativeContainerType<TValue>())
AtomicSafetyHandle.SetNestedContainer(m_Safety, true);
CollectionHelper.SetStaticSafetyId<NativeParallelHashMap<TKey, TValue>>(ref m_Safety, ref s_staticSafetyId.Data);
AtomicSafetyHandle.SetBumpSecondaryVersionOnScheduleWrite(m_Safety, true);
#endif
m_HashMapData = new UnsafeParallelHashMap<TKey, TValue>(capacity, allocator);
}
/// <summary>
/// Whether this hash map is empty.
/// </summary>
/// <value>True if this hash map is empty or if the map has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (!IsCreated)
{
return true;
}
CheckRead();
return m_HashMapData.IsEmpty;
}
}
/// <summary>
/// The current number of key-value pairs in this hash map.
/// </summary>
/// <returns>The current number of key-value pairs in this hash map.</returns>
public int Count()
{
CheckRead();
return m_HashMapData.Count();
}
/// <summary>
/// The number of key-value pairs that fit in the current allocation.
/// </summary>
/// <value>The number of key-value pairs that fit in the current allocation.</value>
/// <param name="value">A new capacity. Must be larger than the current capacity.</param>
/// <exception cref="InvalidOperationException">Thrown if `value` is less than the current capacity.</exception>
public int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get
{
CheckRead();
return m_HashMapData.Capacity;
}
set
{
CheckWrite();
m_HashMapData.Capacity = value;
}
}
/// <summary>
/// The maximum number of elements this type of container can hold.
/// </summary>
public const int MaxCapacity = UnsafeParallelHashMap<TKey, TValue>.MaxCapacity;
/// <summary>
/// Removes all key-value pairs.
/// </summary>
/// <remarks>Does not change the capacity.</remarks>
public void Clear()
{
CheckWrite();
m_HashMapData.Clear();
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>If the key is already present, this method returns false without modifying the hash map.</remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <returns>True if the key-value pair was added.</returns>
public bool TryAdd(TKey key, TValue item)
{
CheckWrite();
return UnsafeParallelHashMapBase<TKey, TValue>.TryAdd(m_HashMapData.m_Buffer, key, item, false, m_HashMapData.m_AllocatorLabel);
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>If the key is already present, this method throws without modifying the hash map.</remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <exception cref="ArgumentException">Thrown if the key was already present.</exception>
/// <exception cref="InvalidOperationException">Thrown if there is not enough Capacity to contain the added element, and the container can't be resized.</exception>
public void Add(TKey key, TValue item)
{
CheckWrite();
var added = UnsafeParallelHashMapBase<TKey, TValue>.TryAdd(m_HashMapData.m_Buffer, key, item, false, m_HashMapData.m_AllocatorLabel);
if (!added)
{
if (m_HashMapData.m_Buffer->keyCapacity == UnsafeParallelHashMapData.kMaxCapacity)
{
ThrowAtMaxCapacity();
return;
}
ThrowKeyAlreadyAdded(key);
}
}
/// <summary>
/// Removes a key-value pair.
/// </summary>
/// <param name="key">The key to remove.</param>
/// <returns>True if a key-value pair was removed.</returns>
public bool Remove(TKey key)
{
CheckWrite();
return m_HashMapData.Remove(key);
}
/// <summary>
/// Returns the value associated with a key.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <param name="item">Outputs the value associated with the key. Outputs default if the key was not present.</param>
/// <returns>True if the key was present.</returns>
public bool TryGetValue(TKey key, out TValue item)
{
CheckRead();
return m_HashMapData.TryGetValue(key, out item);
}
/// <summary>
/// Returns true if a given key is present in this hash map.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <returns>True if the key was present.</returns>
public bool ContainsKey(TKey key)
{
CheckRead();
return m_HashMapData.ContainsKey(key);
}
/// <summary>
/// Gets and sets values by key.
/// </summary>
/// <remarks>Getting a key that is not present will throw. Setting a key that is not already present will add the key.</remarks>
/// <param name="key">The key to look up.</param>
/// <value>The value associated with the key.</value>
/// <exception cref="ArgumentException">For getting, thrown if the key was not present.</exception>
public TValue this[TKey key]
{
get
{
CheckRead();
TValue res;
if (m_HashMapData.TryGetValue(key, out res))
{
return res;
}
ThrowKeyNotPresent(key);
return default;
}
set
{
CheckWrite();
m_HashMapData[key] = value;
}
}
/// <summary>
/// Whether this hash map has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this hash map has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated => m_HashMapData.IsCreated;
/// <summary>
/// Releases all resources (memory and safety handles).
/// </summary>
public void Dispose()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.DisposeSafetyHandle(ref m_Safety);
#endif
m_HashMapData.Dispose();
}
/// <summary>
/// Creates and schedules a job that will dispose this hash map.
/// </summary>
/// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
/// <returns>The handle of a new job that will dispose this hash map.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return inputDeps;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var jobHandle = new UnsafeParallelHashMapDataDisposeJob { Data = new UnsafeParallelHashMapDataDispose { m_Buffer = m_HashMapData.m_Buffer, m_AllocatorLabel = m_HashMapData.m_AllocatorLabel, m_Safety = m_Safety } }.Schedule(inputDeps);
AtomicSafetyHandle.Release(m_Safety);
#else
var jobHandle = new UnsafeParallelHashMapDataDisposeJob { Data = new UnsafeParallelHashMapDataDispose { m_Buffer = m_HashMapData.m_Buffer, m_AllocatorLabel = m_HashMapData.m_AllocatorLabel } }.Schedule(inputDeps);
#endif
m_HashMapData.m_Buffer = null;
return jobHandle;
}
/// <summary>
/// Returns an array with a copy of all this hash map's keys (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash map's keys (in no particular order).</returns>
public NativeArray<TKey> GetKeyArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_HashMapData.GetKeyArray(allocator);
}
/// <summary>
/// Returns an array with a copy of all this hash map's values (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash map's values (in no particular order).</returns>
public NativeArray<TValue> GetValueArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_HashMapData.GetValueArray(allocator);
}
/// <summary>
/// Returns a NativeKeyValueArrays with a copy of all this hash map's keys and values.
/// </summary>
/// <remarks>The key-value pairs are copied in no particular order. For all `i`, `Values[i]` will be the value associated with `Keys[i]`.</remarks>
/// <param name="allocator">The allocator to use.</param>
/// <returns>A NativeKeyValueArrays with a copy of all this hash map's keys and values.</returns>
public NativeKeyValueArrays<TKey, TValue> GetKeyValueArrays(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_HashMapData.GetKeyValueArrays(allocator);
}
/// <summary>
/// Returns a parallel writer for this hash map.
/// </summary>
/// <returns>A parallel writer for this hash map.</returns>
public ParallelWriter AsParallelWriter()
{
ParallelWriter writer;
writer.m_Writer = m_HashMapData.AsParallelWriter();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
writer.m_Safety = m_Safety;
CollectionHelper.SetStaticSafetyId<ParallelWriter>(ref writer.m_Safety, ref ParallelWriter.s_staticSafetyId.Data);
#endif
return writer;
}
/// <summary>
/// Returns a readonly version of this NativeParallelHashMap instance.
/// </summary>
/// <remarks>ReadOnly containers point to the same underlying data as the NativeParallelHashMap it is made from.</remarks>
/// <returns>ReadOnly instance for this.</returns>
public ReadOnly AsReadOnly()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var ash = m_Safety;
return new ReadOnly(m_HashMapData, ash);
#else
return new ReadOnly(m_HashMapData);
#endif
}
/// <summary>
/// A read-only alias for the value of a NativeParallelHashMap. Does not have its own allocated storage.
/// </summary>
[NativeContainer]
[NativeContainerIsReadOnly]
[DebuggerTypeProxy(typeof(NativeParallelHashMapDebuggerTypeProxy<,>))]
[DebuggerDisplay("Count = {m_HashMapData.Count()}, Capacity = {m_HashMapData.Capacity}, IsCreated = {m_HashMapData.IsCreated}, IsEmpty = {IsEmpty}")]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public struct ReadOnly
: IEnumerable<KeyValue<TKey, TValue>>
{
internal UnsafeParallelHashMap<TKey, TValue> m_HashMapData;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
[GenerateTestsForBurstCompatibility(CompileTarget = GenerateTestsForBurstCompatibilityAttribute.BurstCompatibleCompileTarget.Editor)]
internal ReadOnly(UnsafeParallelHashMap<TKey, TValue> hashMapData, AtomicSafetyHandle safety)
{
m_HashMapData = hashMapData;
m_Safety = safety;
CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
}
#else
internal ReadOnly(UnsafeParallelHashMap<TKey, TValue> hashMapData)
{
m_HashMapData = hashMapData;
}
#endif
/// <summary>
/// Whether this hash map has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this hash map has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_HashMapData.IsCreated;
}
/// <summary>
/// Whether this hash map is empty.
/// </summary>
/// <value>True if this hash map is empty or if the map has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (!IsCreated)
{
return true;
}
CheckRead();
return m_HashMapData.IsEmpty;
}
}
/// <summary>
/// The current number of key-value pairs in this hash map.
/// </summary>
/// <returns>The current number of key-value pairs in this hash map.</returns>
public readonly int Count()
{
CheckRead();
return m_HashMapData.Count();
}
/// <summary>
/// The number of key-value pairs that fit in the current allocation.
/// </summary>
/// <value>The number of key-value pairs that fit in the current allocation.</value>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return m_HashMapData.Capacity;
}
}
/// <summary>
/// Returns the value associated with a key.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <param name="item">Outputs the value associated with the key. Outputs default if the key was not present.</param>
/// <returns>True if the key was present.</returns>
public readonly bool TryGetValue(TKey key, out TValue item)
{
CheckRead();
return m_HashMapData.TryGetValue(key, out item);
}
/// <summary>
/// Returns true if a given key is present in this hash map.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <returns>True if the key was present.</returns>
public readonly bool ContainsKey(TKey key)
{
CheckRead();
return m_HashMapData.ContainsKey(key);
}
/// <summary>
/// Gets values by key.
/// </summary>
/// <remarks>Getting a key that is not present will throw.</remarks>
/// <param name="key">The key to look up.</param>
/// <value>The value associated with the key.</value>
/// <exception cref="ArgumentException">For getting, thrown if the key was not present.</exception>
public readonly TValue this[TKey key]
{
get
{
CheckRead();
TValue res;
if (m_HashMapData.TryGetValue(key, out res))
{
return res;
}
ThrowKeyNotPresent(key);
return default;
}
}
/// <summary>
/// Returns an array with a copy of all this hash map's keys (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash map's keys (in no particular order).</returns>
public readonly NativeArray<TKey> GetKeyArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_HashMapData.GetKeyArray(allocator);
}
/// <summary>
/// Returns an array with a copy of all this hash map's values (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash map's values (in no particular order).</returns>
public readonly NativeArray<TValue> GetValueArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_HashMapData.GetValueArray(allocator);
}
/// <summary>
/// Returns a NativeKeyValueArrays with a copy of all this hash map's keys and values.
/// </summary>
/// <remarks>The key-value pairs are copied in no particular order. For all `i`, `Values[i]` will be the value associated with `Keys[i]`.</remarks>
/// <param name="allocator">The allocator to use.</param>
/// <returns>A NativeKeyValueArrays with a copy of all this hash map's keys and values.</returns>
public readonly NativeKeyValueArrays<TKey, TValue> GetKeyValueArrays(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_HashMapData.GetKeyValueArrays(allocator);
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
readonly void ThrowKeyNotPresent(TKey key)
{
throw new ArgumentException($"Key: {key} is not present in the NativeParallelHashMap.");
}
/// <summary>
/// Returns an enumerator over the key-value pairs of this hash map.
/// </summary>
/// <returns>An enumerator over the key-value pairs of this hash map.</returns>
public readonly Enumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
var ash = m_Safety;
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new Enumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = new UnsafeParallelHashMapDataEnumerator(m_HashMapData.m_Buffer),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<KeyValue<TKey, TValue>> IEnumerable<KeyValue<TKey, TValue>>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
/// <summary>
/// A parallel writer for a NativeParallelHashMap.
/// </summary>
/// <remarks>
/// Use <see cref="AsParallelWriter"/> to create a parallel writer for a NativeParallelHashMap.
/// </remarks>
[NativeContainer]
[NativeContainerIsAtomicWriteOnly]
[DebuggerDisplay("Capacity = {m_Writer.Capacity}")]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public unsafe struct ParallelWriter
{
internal UnsafeParallelHashMap<TKey, TValue>.ParallelWriter m_Writer;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ParallelWriter>();
#endif
/// <summary>
/// Returns the index of the current thread.
/// </summary>
/// <remarks>In a job, each thread gets its own copy of the ParallelWriter struct, and the job system assigns
/// each copy the index of its thread.</remarks>
/// <value>The index of the current thread.</value>
public int ThreadIndex => m_Writer.m_ThreadIndex;
/// <summary> **Obsolete. Use <see cref="ThreadIndex"/> instead.</summary>
[Obsolete("'m_ThreadIndex' has been deprecated; use 'ThreadIndex' instead. (UnityUpgradable) -> ThreadIndex")]
public int m_ThreadIndex => m_Writer.m_ThreadIndex;
/// <summary>
/// The number of key-value pairs that fit in the current allocation.
/// </summary>
/// <value>The number of key-value pairs that fit in the current allocation.</value>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Writer.Capacity;
}
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>If the key is already present, this method returns false without modifying this hash map.</remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <returns>True if the key-value pair was added.</returns>
public bool TryAdd(TKey key, TValue item)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
return m_Writer.TryAdd(key, item);
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>If the key is already present, this method returns false without modifying this hash map.</remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <param name="threadIndexOverride">The thread index which must be set by a field from a job struct with the <see cref="NativeSetThreadIndexAttribute"/> attribute.</param>
/// <returns>True if the key-value pair was added.</returns>
public bool TryAdd(TKey key, TValue item, int threadIndexOverride)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
return m_Writer.TryAdd(key, item, threadIndexOverride);
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>If the key is already present, this method throws without modifying the hash map.</remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <exception cref="ArgumentException">Thrown if the key was already present.</exception>
/// <exception cref="InvalidOperationException">If the underlying collection is full (as it cannot be resized within a parallel writer).</exception>
public void Add(TKey key, TValue item)
{
bool result = TryAdd(key, item);
if (!result)
ThrowKeyAlreadyAdded(key);
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>If the key is already present, this method throws without modifying the hash map.</remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <param name="threadIndexOverride">The thread index which must be set by a field from a job struct with the <see cref="NativeSetThreadIndexAttribute"/> attribute.</param>
/// <exception cref="ArgumentException">Thrown if the key was already present.</exception>
/// <exception cref="InvalidOperationException">If the underlying collection is full (as it cannot be resized within a parallel writer).</exception>
public void Add(TKey key, TValue item, int threadIndexOverride)
{
bool result = TryAdd(key, item, threadIndexOverride);
if (!result)
ThrowKeyAlreadyAdded(key);
}
}
/// <summary>
/// Returns an enumerator over the key-value pairs of this hash map.
/// </summary>
/// <returns>An enumerator over the key-value pairs of this hash map.</returns>
public Enumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
var ash = m_Safety;
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new Enumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = new UnsafeParallelHashMapDataEnumerator(m_HashMapData.m_Buffer),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<KeyValue<TKey, TValue>> IEnumerable<KeyValue<TKey, TValue>>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// An enumerator over the key-value pairs of a hash map.
/// </summary>
/// <remarks>
/// In an enumerator's initial state, <see cref="Current"/> is not valid to read.
/// From this state, the first <see cref="MoveNext"/> call advances the enumerator to the first key-value pair.
/// </remarks>
[NativeContainer]
[NativeContainerIsReadOnly]
public struct Enumerator : IEnumerator<KeyValue<TKey, TValue>>
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
#endif
internal UnsafeParallelHashMapDataEnumerator m_Enumerator;
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose() { }
/// <summary>
/// Advances the enumerator to the next key-value pair.
/// </summary>
/// <returns>True if <see cref="Current"/> is valid to read after the call.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Enumerator.MoveNext();
}
/// <summary>
/// Resets the enumerator to its initial state.
/// </summary>
public void Reset()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
m_Enumerator.Reset();
}
/// <summary>
/// The current key-value pair.
/// </summary>
/// <value>The current key-value pair.</value>
public KeyValue<TKey, TValue> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Enumerator.GetCurrent<TKey, TValue>();
}
object IEnumerator.Current => Current;
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void CheckWrite()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void ThrowKeyNotPresent(TKey key)
{
throw new ArgumentException($"Key: {key} is not present in the NativeParallelHashMap.");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void ThrowKeyAlreadyAdded(TKey key)
{
throw new ArgumentException("An item with the same key has already been added", nameof(key));
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void ThrowAtMaxCapacity()
{
throw new InvalidOperationException($"Capacity is insufficient, and resize would fail (Capacity {Capacity} / {MaxCapacity}, Count {Count()})!");
}
}
internal sealed class NativeParallelHashMapDebuggerTypeProxy<TKey, TValue>
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
{
UnsafeParallelHashMap<TKey, TValue> m_Target;
public NativeParallelHashMapDebuggerTypeProxy(NativeParallelHashMap<TKey, TValue> target)
{
m_Target = target.m_HashMapData;
}
internal NativeParallelHashMapDebuggerTypeProxy(NativeParallelHashMap<TKey, TValue>.ReadOnly target)
{
m_Target = target.m_HashMapData;
}
public List<Pair<TKey, TValue>> Items
{
get
{
var result = new List<Pair<TKey, TValue>>();
using (var kva = m_Target.GetKeyValueArrays(Allocator.Temp))
{
for (var i = 0; i < kva.Length; ++i)
{
result.Add(new Pair<TKey, TValue>(kva.Keys[i], kva.Values[i]));
}
}
return result;
}
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 1f49bcab900e54c498a852d067a7636c
timeCreated: 1485127823
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,151 @@
using System;
using Unity.Collections.LowLevel.Unsafe;
namespace Unity.Collections
{
/// <summary>
/// Provides extension methods for hash maps.
/// </summary>
[GenerateTestsForBurstCompatibility]
public static class NativeParallelHashMapExtensions
{
/// <summary>
/// Removes duplicate values from this sorted array and returns the number of values remaining.
/// </summary>
/// <remarks>
/// Uses `Equals` to determine whether values are duplicates.
///
/// Expects the array to already be sorted.
///
/// The remaining elements will be tightly packed at the front of the array.
/// </remarks>
/// <typeparam name="T">The type of values in the array.</typeparam>
/// <param name="array">The array from which to remove duplicates.</param>
/// <returns>The number of unique elements in this array.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public static int Unique<T>(this NativeArray<T> array)
where T : unmanaged, IEquatable<T>
{
if (array.Length == 0)
{
return 0;
}
int first = 0;
int last = array.Length;
var result = first;
while (++first != last)
{
if (!array[result].Equals(array[first]))
{
array[++result] = array[first];
}
}
return ++result;
}
/// <summary>
/// Returns an array populated with the unique keys from this multi hash map.
/// </summary>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <param name="container">The multi hash map.</param>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array populated with the unique keys from this multi hash map.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public static (NativeArray<TKey>, int) GetUniqueKeyArray<TKey, TValue>(this UnsafeParallelMultiHashMap<TKey, TValue> container, AllocatorManager.AllocatorHandle allocator)
where TKey : unmanaged, IEquatable<TKey>, IComparable<TKey>
where TValue : unmanaged
{
var result = container.GetKeyArray(allocator);
result.Sort();
int uniques = result.Unique();
return (result, uniques);
}
/// <summary>
/// Returns an array populated with the unique keys from this multi hash map.
/// </summary>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <param name="container">The multi hash map.</param>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array populated with the unique keys from this multi hash map.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public static (NativeArray<TKey>, int) GetUniqueKeyArray<TKey, TValue>(this NativeParallelMultiHashMap<TKey, TValue> container, AllocatorManager.AllocatorHandle allocator)
where TKey : unmanaged, IEquatable<TKey>, IComparable<TKey>
where TValue : unmanaged
{
var result = container.GetKeyArray(allocator);
result.Sort();
int uniques = result.Unique();
return (result, uniques);
}
/// <summary>
/// Returns a "bucket" view of this hash map.
/// </summary>
/// <remarks>
/// Internally, the elements of a hash map are split into buckets of type <see cref="UnsafeParallelHashMapBucketData"/>.
///
/// With buckets, a job can safely access the elements of a hash map concurrently as long as each individual bucket is accessed
/// only from an individual thread. Effectively, it is not safe to read elements of an individual bucket concurrently,
/// but it is safe to read elements of separate buckets concurrently.
/// </remarks>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <param name="container">The hash map.</param>
/// <returns>A "bucket" view of this hash map.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public static unsafe UnsafeParallelHashMapBucketData GetUnsafeBucketData<TKey, TValue>(this NativeParallelHashMap<TKey, TValue> container)
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
{
return container.m_HashMapData.m_Buffer->GetBucketData();
}
/// <summary>
/// Returns a "bucket" view of this multi hash map.
/// </summary>
/// <remarks>
/// Internally, the elements of a hash map are split into buckets of type <see cref="UnsafeParallelHashMapBucketData"/>.
///
/// With buckets, a job can safely access the elements of a hash map concurrently as long as each individual bucket is accessed
/// only from an individual thread. Effectively, it is not safe to read elements of an individual bucket concurrently,
/// but it is safe to read elements of separate buckets concurrently.
/// </remarks>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <param name="container">The multi hash map.</param>
/// <returns>A "bucket" view of this multi hash map.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public static unsafe UnsafeParallelHashMapBucketData GetUnsafeBucketData<TKey, TValue>(this NativeParallelMultiHashMap<TKey, TValue> container)
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
{
return container.m_MultiHashMapData.m_Buffer->GetBucketData();
}
/// <summary>
/// Removes all occurrences of a particular key-value pair.
/// </summary>
/// <remarks>Removes all key-value pairs which have a particular key and which *also have* a particular value.
/// In other words: (key *AND* value) rather than (key *OR* value).</remarks>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <param name="container">The multi hash map.</param>
/// <param name="key">The key of the key-value pairs to remove.</param>
/// <param name="value">The value of the key-value pairs to remove.</param>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public static void Remove<TKey, TValue>(this NativeParallelMultiHashMap<TKey, TValue> container, TKey key, TValue value)
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged, IEquatable<TValue>
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(container.m_Safety);
#endif
container.m_MultiHashMapData.Remove(key, value);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 859b8b7a1710f0b4396876700dda6319
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,527 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using UnityEngine.Internal;
using Unity.Burst;
using System.Runtime.CompilerServices;
namespace Unity.Collections
{
/// <summary>
/// An unordered, expandable set of unique values.
/// </summary>
/// <typeparam name="T">The type of the values.</typeparam>
[StructLayout(LayoutKind.Sequential)]
[DebuggerTypeProxy(typeof(NativeParallelHashSetDebuggerTypeProxy<>))]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public unsafe struct NativeParallelHashSet<T>
: INativeDisposable
, IEnumerable<T> // Used by collection initializers.
where T : unmanaged, IEquatable<T>
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeParallelHashSet<T>>();
#endif
internal NativeParallelHashMap<T, bool> m_Data;
/// <summary>
/// Initializes and returns an instance of NativeParallelHashSet.
/// </summary>
/// <param name="capacity">The number of values that should fit in the initial allocation.</param>
/// <param name="allocator">The allocator to use.</param>
public NativeParallelHashSet(int capacity, AllocatorManager.AllocatorHandle allocator)
{
m_Data = new NativeParallelHashMap<T, bool>(capacity, allocator);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.SetStaticSafetyId<NativeParallelHashSet<T>>(ref m_Data.m_Safety, ref s_staticSafetyId.Data);
#endif
}
/// <summary>
/// Whether this set is empty.
/// </summary>
/// <value>True if this set is empty or if the set has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Data.IsEmpty;
}
/// <summary>
/// Returns the current number of values in this set.
/// </summary>
/// <returns>The current number of values in this set.</returns>
public int Count() => m_Data.Count();
/// <summary>
/// The number of values that fit in the current allocation.
/// </summary>
/// <value>The number of values that fit in the current allocation.</value>
/// <param name="value">A new capacity. Must be larger than current capacity.</param>
/// <exception cref="InvalidOperationException">Thrown if `value` is less than the current capacity.</exception>
public int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get => m_Data.Capacity;
set => m_Data.Capacity = value;
}
/// <summary>
/// The maximum number of elements this type of container can hold.
/// </summary>
public const int MaxCapacity = NativeParallelHashMap<T, bool>.MaxCapacity;
/// <summary>
/// Whether this set has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this set has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Data.IsCreated;
}
/// <summary>
/// Releases all resources (memory and safety handles).
/// </summary>
public void Dispose() => m_Data.Dispose();
/// <summary>
/// Creates and schedules a job that will dispose this set.
/// </summary>
/// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
/// <returns>The handle of a new job that will dispose this set.</returns>
public JobHandle Dispose(JobHandle inputDeps) => m_Data.Dispose(inputDeps);
/// <summary>
/// Removes all values.
/// </summary>
/// <remarks>Does not change the capacity.</remarks>
public void Clear() => m_Data.Clear();
/// <summary>
/// Adds a new item.
/// If the item is already present in the collection, this method <b>should</b> throw, but currently does not!
/// Instead, it returns false without replacing said item.
/// </summary>
/// <remarks>
/// Prefer <see cref="TryAdd(T)"/> if your intent is to allow graceful failure, as this API will eventually become more strict (and begin to throw).
/// </remarks>
/// <param name="item">The value to add.</param>
/// <returns>True if the value was not already present.</returns>
public bool Add(T item) => m_Data.TryAdd(item, false);
/// <summary>
/// Attempts to add a new item. Only succeeds if the item was not present.
/// </summary>
/// <param name="item">The value to add.</param>
/// <returns>True if the value was not already present (thus was successfully added).</returns>
public bool TryAdd(T item) => m_Data.TryAdd(item, false);
/// <summary>
/// Removes a particular value.
/// </summary>
/// <param name="item">The value to remove.</param>
/// <returns>True if the value was present.</returns>
public bool Remove(T item) => m_Data.Remove(item);
/// <summary>
/// Returns true if a particular value is present.
/// </summary>
/// <param name="item">The value to check for.</param>
/// <returns>True if the value was present.</returns>
public bool Contains(T item) => m_Data.ContainsKey(item);
/// <summary>
/// Returns an array with a copy of this set's values (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of the set's values.</returns>
public NativeArray<T> ToNativeArray(AllocatorManager.AllocatorHandle allocator) => m_Data.GetKeyArray(allocator);
/// <summary>
/// Returns a parallel writer.
/// </summary>
/// <returns>A parallel writer.</returns>
public ParallelWriter AsParallelWriter()
{
ParallelWriter writer;
writer.m_Data = m_Data.AsParallelWriter();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.SetStaticSafetyId<ParallelWriter>(ref writer.m_Data.m_Safety, ref ParallelWriter.s_staticSafetyId.Data);
#endif
return writer;
}
/// <summary>
/// A parallel writer for a NativeParallelHashSet.
/// </summary>
/// <remarks>
/// Use <see cref="AsParallelWriter"/> to create a parallel writer for a set.
/// </remarks>
[NativeContainerIsAtomicWriteOnly]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public struct ParallelWriter
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ParallelWriter>();
#endif
internal NativeParallelHashMap<T, bool>.ParallelWriter m_Data;
/// <summary>
/// The number of values that fit in the current allocation.
/// </summary>
/// <value>The number of values that fit in the current allocation.</value>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Data.Capacity;
}
/// <summary>
/// Adds a new item.
/// If the item is already present in the collection, this method <b>should</b> throw, but currently does not!
/// Instead, it returns false without replacing said item.
/// </summary>
/// <remarks>
/// Prefer <see cref="TryAdd(T)"/> if your intent is to allow graceful failure, as this API will eventually become more strict (and begin to throw).
/// </remarks>
/// <param name="item">The value to add.</param>
/// <returns>True if the value is not already present.</returns>
/// <exception cref="InvalidOperationException">If the underlying collection is full (as it cannot be resized within a parallel writer).</exception>
public bool Add(T item) => m_Data.TryAdd(item, false);
/// <summary>
/// Adds a new item.
/// If the item is already present in the collection, this method <b>should</b> throw, but currently does not!
/// Instead, it returns false without replacing said item.
/// </summary>
/// <remarks>
/// Prefer <see cref="TryAdd(T)"/> if your intent is to allow graceful failure, as this API will eventually become more strict (and begin to throw).
/// </remarks>
/// <param name="item">The value to add.</param>
/// <param name="threadIndexOverride">The thread index which must be set by a field from a job struct with the <see cref="NativeSetThreadIndexAttribute"/> attribute.</param>
/// <returns>True if the value is not already present.</returns>
/// <exception cref="InvalidOperationException">If the underlying collection is full (as it cannot be resized within a parallel writer).</exception>
public bool Add(T item, int threadIndexOverride) => m_Data.TryAdd(item, false, threadIndexOverride);
/// <summary>
/// Adds a new value.
/// If the item is already present, this method returns false without replacing said item.
/// </summary>
/// <param name="item">The value to add.</param>
/// <returns>True if the value is not already present.</returns>
/// <exception cref="InvalidOperationException">If the underlying collection is full (as it cannot be resized within a parallel writer).</exception>
public bool TryAdd(T item) => m_Data.TryAdd(item, false);
/// <summary>
/// Adds a new value.
/// If the item is already present, this method returns false without replacing said item.
/// </summary>
/// <param name="item">The value to add.</param>
/// <param name="threadIndexOverride">The thread index which must be set by a field from a job struct with the <see cref="NativeSetThreadIndexAttribute"/> attribute.</param>
/// <returns>True if the value is not already present.</returns>
/// <exception cref="InvalidOperationException">If the underlying collection is full (as it cannot be resized within a parallel writer).</exception>
public bool TryAdd(T item, int threadIndexOverride) => m_Data.TryAdd(item, false, threadIndexOverride);
}
/// <summary>
/// Returns an enumerator over the values of this set.
/// </summary>
/// <returns>An enumerator over the values of this set.</returns>
public Enumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Data.m_Safety);
var ash = m_Data.m_Safety;
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new Enumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = new UnsafeParallelHashMapDataEnumerator(m_Data.m_HashMapData.m_Buffer),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// An enumerator over the values of a set.
/// </summary>
/// <remarks>
/// In an enumerator's initial state, <see cref="Current"/> is invalid.
/// The first <see cref="MoveNext"/> call advances the enumerator to the first value.
/// </remarks>
[NativeContainer]
[NativeContainerIsReadOnly]
public struct Enumerator : IEnumerator<T>
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
#endif
internal UnsafeParallelHashMapDataEnumerator m_Enumerator;
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose() { }
/// <summary>
/// Advances the enumerator to the next value.
/// </summary>
/// <returns>True if `Current` is valid to read after the call.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Enumerator.MoveNext();
}
/// <summary>
/// Resets the enumerator to its initial state.
/// </summary>
public void Reset()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
m_Enumerator.Reset();
}
/// <summary>
/// The current value.
/// </summary>
/// <value>The current value.</value>
public T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Enumerator.GetCurrentKey<T>();
}
}
/// <summary>
/// Gets the element at the current position of the enumerator in the container.
/// </summary>
object IEnumerator.Current => Current;
}
/// <summary>
/// Returns a readonly version of this NativeParallelHashSet instance.
/// </summary>
/// <remarks>ReadOnly containers point to the same underlying data as the NativeParallelHashSet it is made from.</remarks>
/// <returns>ReadOnly instance for this.</returns>
public ReadOnly AsReadOnly()
{
return new ReadOnly(ref this);
}
/// <summary>
/// A read-only alias for the value of a NativeParallelHashSet. Does not have its own allocated storage.
/// </summary>
[NativeContainer]
[NativeContainerIsReadOnly]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public struct ReadOnly
: IEnumerable<T>
{
internal UnsafeParallelHashMap<T, bool> m_Data;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
#endif
internal ReadOnly(ref NativeParallelHashSet<T> data)
{
m_Data = data.m_Data.m_HashMapData;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = data.m_Data.m_Safety;
CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
#endif
}
/// <summary>
/// Whether this hash set has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this hash set has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Data.IsCreated;
}
/// <summary>
/// Whether this hash set is empty.
/// </summary>
/// <value>True if this hash set is empty or if the map has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (!IsCreated)
{
return true;
}
CheckRead();
return m_Data.IsEmpty;
}
}
/// <summary>
/// The current number of items in this hash set.
/// </summary>
/// <returns>The current number of items in this hash set.</returns>
public readonly int Count()
{
CheckRead();
return m_Data.Count();
}
/// <summary>
/// The number of items that fit in the current allocation.
/// </summary>
/// <value>The number of items that fit in the current allocation.</value>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return m_Data.Capacity;
}
}
/// <summary>
/// Returns true if a given item is present in this hash set.
/// </summary>
/// <param name="item">The item to look up.</param>
/// <returns>True if the item was present.</returns>
public readonly bool Contains(T item)
{
CheckRead();
return m_Data.ContainsKey(item);
}
/// <summary>
/// Returns an array with a copy of all this hash set's items (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash set's items (in no particular order).</returns>
public readonly NativeArray<T> ToNativeArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_Data.GetKeyArray(allocator);
}
/// <summary>
/// Returns an enumerator over the items of this hash set.
/// </summary>
/// <returns>An enumerator over the items of this hash set.</returns>
public readonly Enumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
var ash = m_Safety;
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new Enumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = new UnsafeParallelHashMapDataEnumerator(m_Data.m_Buffer),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
}
}
sealed internal class NativeParallelHashSetDebuggerTypeProxy<T>
where T : unmanaged, IEquatable<T>
{
NativeParallelHashSet<T> Data;
public NativeParallelHashSetDebuggerTypeProxy(NativeParallelHashSet<T> data)
{
Data = data;
}
public List<T> Items
{
get
{
var result = new List<T>();
using (var keys = Data.ToNativeArray(Allocator.Temp))
{
for (var k = 0; k < keys.Length; ++k)
{
result.Add(keys[k]);
}
}
return result;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: da168a32991917b48989353c3d849677
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 66713ae417f65c84c944fd6fa9e80129
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,104 @@
<#/*THIS IS A T4 FILE - see t4_text_templating.md for what it is and how to run codegen*/#>
<#@ template debug="True" #>
<#@ output extension=".gen.cs" #>
<#@ assembly name="System.Core" #>
using System;
using Unity.Collections.LowLevel.Unsafe;
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// t4 Packages/com.unity.collections/Unity.Collections/NativeParallelHashSetExtensions.tt
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Unity.Collections
{
/// <summary>
/// Provides extension methods for sets.
/// </summary>
public unsafe static class HashSetExtensions
{
<#
{
foreach (var ContainerType in new[] {
( new[] { "NativeHashSet", "Count" } ),
( new[] { "NativeParallelHashSet", "Count()" } ),
}) {
foreach (var OtherContainerType in new[] {
( "FixedList128Bytes<T>" ),
( "FixedList32Bytes<T>" ),
( "FixedList4096Bytes<T>" ),
( "FixedList512Bytes<T>" ),
( "FixedList64Bytes<T>" ),
( "NativeArray<T>" ),
( "NativeHashSet<T>" ),
( "NativeHashSet<T>.ReadOnly" ),
( "NativeParallelHashSet<T>" ),
( "NativeParallelHashSet<T>.ReadOnly" ),
( "NativeList<T>" ),
}) {
#>
/// <summary>
/// Removes the values from this set which are also present in another collection.
/// </summary>
/// <typeparam name="T">The type of values.</typeparam>
/// <param name="container">The set to remove values from.</param>
/// <param name="other">The collection to compare with.</param>
public static void ExceptWith<T>(this ref <#=ContainerType[0]#><T> container, <#=OtherContainerType#> other)
where T : unmanaged, IEquatable<T>
{
foreach (var item in other)
{
container.Remove(item);
}
}
/// <summary>
/// Removes the values from this set which are absent in another collection.
/// </summary>
/// <typeparam name="T">The type of values.</typeparam>
/// <param name="container">The set to remove values from.</param>
/// <param name="other">The collection to compare with.</param>
public static void IntersectWith<T>(this ref <#=ContainerType[0]#><T> container, <#=OtherContainerType#> other)
where T : unmanaged, IEquatable<T>
{
var result = new UnsafeList<T>(container.<#=ContainerType[1]#>, Allocator.Temp);
foreach (var item in other)
{
if (container.Contains(item))
{
result.Add(item);
}
}
container.Clear();
container.UnionWith(result);
result.Dispose();
}
/// <summary>
/// Adds all distinct values from the other collection to this set.
/// Does not throw if a value is already in this set.
/// </summary>
/// <typeparam name="T">The type of values.</typeparam>
/// <param name="container">The set to add values to.</param>
/// <param name="other">The collection to copy values from.</param>
public static void UnionWith<T>(this ref <#=ContainerType[0]#><T> container, <#=OtherContainerType#> other)
where T : unmanaged, IEquatable<T>
{
foreach (var item in other)
{
container.TryAdd(item);
}
}
<#}}}#>
}
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 6f9fa81af98728e4f8a0db3762124ff9
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,946 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Collections.NotBurstCompatible;
using Unity.Jobs;
namespace Unity.Collections
{
/// <summary>
/// An iterator over all values associated with an individual key in a multi hash map.
/// </summary>
/// <remarks>The iteration order over the values associated with a key is an implementation detail. Do not rely upon any particular ordering.</remarks>
/// <typeparam name="TKey">The type of the keys.</typeparam>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public struct NativeParallelMultiHashMapIterator<TKey>
where TKey : unmanaged
{
internal TKey key;
internal int NextEntryIndex;
internal int EntryIndex;
/// <summary>
/// Returns the entry index.
/// </summary>
/// <returns>The entry index.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetEntryIndex() => EntryIndex;
}
/// <summary>
/// An unordered, expandable associative array. Each key can have more than one associated value.
/// </summary>
/// <remarks>
/// Unlike a regular NativeParallelHashMap, a NativeParallelMultiHashMap can store multiple key-value pairs with the same key.
///
/// The keys are not deduplicated: two key-value pairs with the same key are stored as fully separate key-value pairs.
/// </remarks>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
[StructLayout(LayoutKind.Sequential)]
[NativeContainer]
[DebuggerTypeProxy(typeof(NativeParallelMultiHashMapDebuggerTypeProxy<,>))]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public unsafe struct NativeParallelMultiHashMap<TKey, TValue>
: INativeDisposable
, IEnumerable<KeyValue<TKey, TValue>> // Used by collection initializers.
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
{
internal UnsafeParallelMultiHashMap<TKey, TValue> m_MultiHashMapData;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeParallelMultiHashMap<TKey, TValue>>();
#endif
/// <summary>
/// Returns a newly allocated multi hash map.
/// </summary>
/// <param name="capacity">The number of key-value pairs that should fit in the initial allocation.</param>
/// <param name="allocator">The allocator to use.</param>
public NativeParallelMultiHashMap(int capacity, AllocatorManager.AllocatorHandle allocator)
{
this = default;
Initialize(capacity, ref allocator);
}
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(AllocatorManager.AllocatorHandle) })]
internal void Initialize<U>(int capacity, ref U allocator)
where U : unmanaged, AllocatorManager.IAllocator
{
m_MultiHashMapData = new UnsafeParallelMultiHashMap<TKey, TValue>(capacity, allocator.Handle);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = CollectionHelper.CreateSafetyHandle(allocator.ToAllocator);
if (UnsafeUtility.IsNativeContainerType<TKey>() || UnsafeUtility.IsNativeContainerType<TValue>())
AtomicSafetyHandle.SetNestedContainer(m_Safety, true);
CollectionHelper.SetStaticSafetyId<NativeParallelMultiHashMap<TKey, TValue>>(ref m_Safety, ref s_staticSafetyId.Data);
AtomicSafetyHandle.SetBumpSecondaryVersionOnScheduleWrite(m_Safety, true);
#endif
}
/// <summary>
/// Whether this hash map is empty.
/// </summary>
/// <value>True if the hash map is empty or if the hash map has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return m_MultiHashMapData.IsEmpty;
}
}
/// <summary>
/// Returns the current number of key-value pairs in this hash map.
/// </summary>
/// <remarks>Key-value pairs with matching keys are counted as separate, individual pairs.</remarks>
/// <returns>The current number of key-value pairs in this hash map.</returns>
public readonly int Count()
{
CheckRead();
return m_MultiHashMapData.Count();
}
/// <summary>
/// Returns the number of key-value pairs that fit in the current allocation.
/// </summary>
/// <value>The number of key-value pairs that fit in the current allocation.</value>
/// <param name="value">A new capacity. Must be larger than the current capacity.</param>
/// <exception cref="InvalidOperationException">Thrown if `value` is less than the current capacity.</exception>
public int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly get
{
CheckRead();
return m_MultiHashMapData.Capacity;
}
set
{
CheckWrite();
m_MultiHashMapData.Capacity = value;
}
}
/// <summary>
/// The maximum number of elements this type of container can hold.
/// </summary>
public const int MaxCapacity = UnsafeParallelMultiHashMap<TKey, TValue>.MaxCapacity;
/// <summary>
/// Removes all key-value pairs.
/// </summary>
/// <remarks>Does not change the capacity.</remarks>
public void Clear()
{
CheckWrite();
m_MultiHashMapData.Clear();
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>
/// If a key-value pair with this key is already present, an additional separate key-value pair is added.
/// </remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
public void Add(TKey key, TValue item)
{
CheckWrite();
m_MultiHashMapData.Add(key, item);
}
/// <summary>
/// Removes a key and its associated value(s).
/// </summary>
/// <param name="key">The key to remove.</param>
/// <returns>The number of removed key-value pairs. If the key was not present, returns 0.</returns>
public int Remove(TKey key)
{
CheckWrite();
return m_MultiHashMapData.Remove(key);
}
/// <summary>
/// Removes a single key-value pair.
/// </summary>
/// <param name="it">An iterator representing the key-value pair to remove.</param>
/// <exception cref="InvalidOperationException">Thrown if the iterator is invalid.</exception>
public void Remove(NativeParallelMultiHashMapIterator<TKey> it)
{
CheckWrite();
m_MultiHashMapData.Remove(it);
}
/// <summary>
/// Gets an iterator for a key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="item">Outputs the associated value represented by the iterator.</param>
/// <param name="it">Outputs an iterator.</param>
/// <returns>True if the key was present.</returns>
public bool TryGetFirstValue(TKey key, out TValue item, out NativeParallelMultiHashMapIterator<TKey> it)
{
CheckRead();
return m_MultiHashMapData.TryGetFirstValue(key, out item, out it);
}
/// <summary>
/// Advances an iterator to the next value associated with its key.
/// </summary>
/// <param name="item">Outputs the next value.</param>
/// <param name="it">A reference to the iterator to advance.</param>
/// <returns>True if the key was present and had another value.</returns>
public bool TryGetNextValue(out TValue item, ref NativeParallelMultiHashMapIterator<TKey> it)
{
CheckRead();
return m_MultiHashMapData.TryGetNextValue(out item, ref it);
}
/// <summary>
/// Returns true if a given key is present in this hash map.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <returns>True if the key was present in this hash map.</returns>
public bool ContainsKey(TKey key)
{
return TryGetFirstValue(key, out var temp0, out var temp1);
}
/// <summary>
/// Returns the number of values associated with a given key.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <returns>The number of values associated with the key. Returns 0 if the key was not present.</returns>
public int CountValuesForKey(TKey key)
{
if (!TryGetFirstValue(key, out var value, out var iterator))
{
return 0;
}
var count = 1;
while (TryGetNextValue(out value, ref iterator))
{
count++;
}
return count;
}
/// <summary>
/// Sets a new value for an existing key-value pair.
/// </summary>
/// <param name="item">The new value.</param>
/// <param name="it">The iterator representing a key-value pair.</param>
/// <returns>True if a value was overwritten.</returns>
public bool SetValue(TValue item, NativeParallelMultiHashMapIterator<TKey> it)
{
CheckWrite();
return m_MultiHashMapData.SetValue(item, it);
}
/// <summary>
/// Whether this hash map has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this hash map has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated => m_MultiHashMapData.IsCreated;
/// <summary>
/// Releases all resources (memory and safety handles).
/// </summary>
public void Dispose()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.DisposeSafetyHandle(ref m_Safety);
#endif
m_MultiHashMapData.Dispose();
}
/// <summary>
/// Creates and schedules a job that will dispose this hash map.
/// </summary>
/// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
/// <returns>The handle of a new job that will dispose this hash map.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return inputDeps;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var jobHandle = new UnsafeParallelHashMapDataDisposeJob { Data = new UnsafeParallelHashMapDataDispose { m_Buffer = m_MultiHashMapData.m_Buffer, m_AllocatorLabel = m_MultiHashMapData.m_AllocatorLabel, m_Safety = m_Safety } }.Schedule(inputDeps);
AtomicSafetyHandle.Release(m_Safety);
#else
var jobHandle = new UnsafeParallelHashMapDataDisposeJob { Data = new UnsafeParallelHashMapDataDispose { m_Buffer = m_MultiHashMapData.m_Buffer, m_AllocatorLabel = m_MultiHashMapData.m_AllocatorLabel } }.Schedule(inputDeps);
#endif
m_MultiHashMapData.m_Buffer = null;
return jobHandle;
}
/// <summary>
/// Returns an array with a copy of all the keys (in no particular order).
/// </summary>
/// <remarks>A key with *N* values is included *N* times in the array.
///
/// Use `GetUniqueKeyArray` of <see cref="Unity.Collections.NativeParallelHashMapExtensions"/> instead if you only want one occurrence of each key.</remarks>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all the keys (in no particular order).</returns>
public NativeArray<TKey> GetKeyArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_MultiHashMapData.GetKeyArray(allocator);
}
/// <summary>
/// Returns an array with a copy of all the values (in no particular order).
/// </summary>
/// <remarks>The values are not deduplicated. If you sort the returned array,
/// you can use <see cref="Unity.Collections.NativeParallelHashMapExtensions.Unique{T}"/> to remove duplicate values.</remarks>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all the values (in no particular order).</returns>
public NativeArray<TValue> GetValueArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_MultiHashMapData.GetValueArray(allocator);
}
/// <summary>
/// Returns a NativeKeyValueArrays with a copy of all the keys and values (in no particular order).
/// </summary>
/// <remarks>A key with *N* values is included *N* times in the array.
/// </remarks>
/// <param name="allocator">The allocator to use.</param>
/// <returns>A NativeKeyValueArrays with a copy of all the keys and values (in no particular order).</returns>
public NativeKeyValueArrays<TKey, TValue> GetKeyValueArrays(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_MultiHashMapData.GetKeyValueArrays(allocator);
}
/// <summary>
/// Returns a parallel writer for this hash map.
/// </summary>
/// <returns>A parallel writer for this hash map.</returns>
public ParallelWriter AsParallelWriter()
{
ParallelWriter writer;
writer.m_Writer = m_MultiHashMapData.AsParallelWriter();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
writer.m_Safety = m_Safety;
CollectionHelper.SetStaticSafetyId<ParallelWriter>(ref writer.m_Safety, ref s_staticSafetyId.Data);
#endif
return writer;
}
/// <summary>
/// A parallel writer for a NativeParallelMultiHashMap.
/// </summary>
/// <remarks>
/// Use <see cref="AsParallelWriter"/> to create a parallel writer for a NativeParallelMultiHashMap.
/// </remarks>
[NativeContainer]
[NativeContainerIsAtomicWriteOnly]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int), typeof(int) })]
public unsafe struct ParallelWriter
{
internal UnsafeParallelMultiHashMap<TKey, TValue>.ParallelWriter m_Writer;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ParallelWriter>();
#endif
/// <summary>
/// Returns the index of the current thread.
/// </summary>
/// <remarks>In a job, each thread gets its own copy of the ParallelWriter struct, and the job system assigns
/// each copy the index of its thread.</remarks>
/// <value>The index of the current thread.</value>
public int m_ThreadIndex => m_Writer.m_ThreadIndex;
/// <summary>
/// Returns the number of key-value pairs that fit in the current allocation.
/// </summary>
/// <value>The number of key-value pairs that fit in the current allocation.</value>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Writer.Capacity;
}
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>
/// If a key-value pair with this key is already present, an additional separate key-value pair is added.
/// </remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <exception cref="InvalidOperationException">If the underlying collection is full (as it cannot be resized within a parallel writer).</exception>
public void Add(TKey key, TValue item)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
m_Writer.Add(key, item);
}
/// <summary>
/// Adds a new key-value pair.
/// </summary>
/// <remarks>
/// If a key-value pair with this key is already present, an additional separate key-value pair is added.
/// </remarks>
/// <param name="key">The key to add.</param>
/// <param name="item">The value to add.</param>
/// <param name="threadIndexOverride">The thread index which must be set by a field from a job struct with the <see cref="NativeSetThreadIndexAttribute"/> attribute.</param>
/// <exception cref="InvalidOperationException">If the underlying collection is full (as it cannot be resized within a parallel writer).</exception>
public void Add(TKey key, TValue item, int threadIndexOverride)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
m_Writer.Add(key, item, threadIndexOverride);
}
}
/// <summary>
/// Returns an enumerator over the values of an individual key.
/// </summary>
/// <param name="key">The key to get an enumerator for.</param>
/// <returns>An enumerator over the values of a key.</returns>
public Enumerator GetValuesForKey(TKey key)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return new Enumerator { hashmap = this, key = key, isFirst = 1 };
}
/// <summary>
/// An enumerator over the values of an individual key in a multi hash map.
/// </summary>
/// <remarks>
/// In an enumerator's initial state, <see cref="Current"/> is not valid to read.
/// The first <see cref="MoveNext"/> call advances the enumerator to the first value of the key.
/// </remarks>
public struct Enumerator : IEnumerator<TValue>
{
internal NativeParallelMultiHashMap<TKey, TValue> hashmap;
internal TKey key;
internal byte isFirst;
TValue value;
NativeParallelMultiHashMapIterator<TKey> iterator;
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose() { }
/// <summary>
/// Advances the enumerator to the next value of the key.
/// </summary>
/// <returns>True if <see cref="Current"/> is valid to read after the call.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
//Avoids going beyond the end of the collection.
if (isFirst == 1)
{
isFirst = 0;
return hashmap.TryGetFirstValue(key, out value, out iterator);
}
return hashmap.TryGetNextValue(out value, ref iterator);
}
/// <summary>
/// Resets the enumerator to its initial state.
/// </summary>
public void Reset() => isFirst = 1;
/// <summary>
/// The current value.
/// </summary>
/// <value>The current value.</value>
public TValue Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return value;
}
}
object IEnumerator.Current => Current;
/// <summary>
/// Returns this enumerator.
/// </summary>
/// <returns>This enumerator.</returns>
public Enumerator GetEnumerator() { return this; }
}
/// <summary>
/// Returns an enumerator over the key-value pairs of this hash map.
/// </summary>
/// <remarks>A key with *N* values is visited by the enumerator *N* times.</remarks>
/// <returns>An enumerator over the key-value pairs of this hash map.</returns>
public KeyValueEnumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
var ash = m_Safety;
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new KeyValueEnumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = new UnsafeParallelHashMapDataEnumerator(m_MultiHashMapData.m_Buffer),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<KeyValue<TKey, TValue>> IEnumerable<KeyValue<TKey, TValue>>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// An enumerator over the key-value pairs of a multi hash map.
/// </summary>
/// <remarks>A key with *N* values is visited by the enumerator *N* times.
///
/// In an enumerator's initial state, <see cref="Current"/> is not valid to read.
/// The first <see cref="MoveNext"/> call advances the enumerator to the first key-value pair.
/// </remarks>
[NativeContainer]
[NativeContainerIsReadOnly]
public struct KeyValueEnumerator : IEnumerator<KeyValue<TKey, TValue>>
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
#endif
internal UnsafeParallelHashMapDataEnumerator m_Enumerator;
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose() { }
/// <summary>
/// Advances the enumerator to the next key-value pair.
/// </summary>
/// <returns>True if <see cref="Current"/> is valid to read after the call.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe bool MoveNext()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Enumerator.MoveNext();
}
/// <summary>
/// Resets the enumerator to its initial state.
/// </summary>
public void Reset()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
m_Enumerator.Reset();
}
/// <summary>
/// The current key-value pair.
/// </summary>
/// <value>The current key-value pair.</value>
public readonly KeyValue<TKey, TValue> Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Enumerator.GetCurrent<TKey, TValue>();
}
}
object IEnumerator.Current => Current;
}
/// <summary>
/// Returns a readonly version of this NativeParallelHashMap instance.
/// </summary>
/// <remarks>ReadOnly containers point to the same underlying data as the NativeParallelHashMap it is made from.</remarks>
/// <returns>ReadOnly instance for this.</returns>
public ReadOnly AsReadOnly()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var ash = m_Safety;
return new ReadOnly(m_MultiHashMapData, ash);
#else
return new ReadOnly(m_MultiHashMapData);
#endif
}
/// <summary>
/// A read-only alias for the value of a NativeParallelHashMap. Does not have its own allocated storage.
/// </summary>
[NativeContainer]
[NativeContainerIsReadOnly]
[DebuggerTypeProxy(typeof(NativeParallelHashMapDebuggerTypeProxy<,>))]
[DebuggerDisplay("Count = {m_HashMapData.Count()}, Capacity = {m_HashMapData.Capacity}, IsCreated = {m_HashMapData.IsCreated}, IsEmpty = {IsEmpty}")]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int) })]
public struct ReadOnly
: IEnumerable<KeyValue<TKey, TValue>>
{
internal UnsafeParallelMultiHashMap<TKey, TValue> m_MultiHashMapData;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
[GenerateTestsForBurstCompatibility(CompileTarget = GenerateTestsForBurstCompatibilityAttribute.BurstCompatibleCompileTarget.Editor)]
internal ReadOnly(UnsafeParallelMultiHashMap<TKey, TValue> container, AtomicSafetyHandle safety)
{
m_MultiHashMapData = container;
m_Safety = safety;
CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
}
#else
internal ReadOnly(UnsafeParallelMultiHashMap<TKey, TValue> container)
{
m_MultiHashMapData = container;
}
#endif
/// <summary>
/// Whether this hash map has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this hash map has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_MultiHashMapData.IsCreated;
}
/// <summary>
/// Whether this hash map is empty.
/// </summary>
/// <value>True if this hash map is empty or if the map has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (!IsCreated)
{
return true;
}
CheckRead();
return m_MultiHashMapData.IsEmpty;
}
}
/// <summary>
/// The current number of key-value pairs in this hash map.
/// </summary>
/// <returns>The current number of key-value pairs in this hash map.</returns>
public readonly int Count()
{
CheckRead();
return m_MultiHashMapData.Count();
}
/// <summary>
/// The number of key-value pairs that fit in the current allocation.
/// </summary>
/// <value>The number of key-value pairs that fit in the current allocation.</value>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return m_MultiHashMapData.Capacity;
}
}
/// <summary>
/// Gets an iterator for a key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="item">Outputs the associated value represented by the iterator.</param>
/// <param name="it">Outputs an iterator.</param>
/// <returns>True if the key was present.</returns>
public readonly bool TryGetFirstValue(TKey key, out TValue item, out NativeParallelMultiHashMapIterator<TKey> it)
{
CheckRead();
return m_MultiHashMapData.TryGetFirstValue(key, out item, out it);
}
/// <summary>
/// Advances an iterator to the next value associated with its key.
/// </summary>
/// <param name="item">Outputs the next value.</param>
/// <param name="it">A reference to the iterator to advance.</param>
/// <returns>True if the key was present and had another value.</returns>
public readonly bool TryGetNextValue(out TValue item, ref NativeParallelMultiHashMapIterator<TKey> it)
{
CheckRead();
return m_MultiHashMapData.TryGetNextValue(out item, ref it);
}
/// <summary>
/// Returns true if a given key is present in this hash map.
/// </summary>
/// <param name="key">The key to look up.</param>
/// <returns>True if the key was present.</returns>
public readonly bool ContainsKey(TKey key)
{
CheckRead();
return m_MultiHashMapData.ContainsKey(key);
}
/// <summary>
/// Returns an array with a copy of all this hash map's keys (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash map's keys (in no particular order).</returns>
public readonly NativeArray<TKey> GetKeyArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_MultiHashMapData.GetKeyArray(allocator);
}
/// <summary>
/// Returns an array with a copy of all this hash map's values (in no particular order).
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array with a copy of all this hash map's values (in no particular order).</returns>
public readonly NativeArray<TValue> GetValueArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_MultiHashMapData.GetValueArray(allocator);
}
/// <summary>
/// Returns a NativeKeyValueArrays with a copy of all this hash map's keys and values.
/// </summary>
/// <remarks>The key-value pairs are copied in no particular order. For all `i`, `Values[i]` will be the value associated with `Keys[i]`.</remarks>
/// <param name="allocator">The allocator to use.</param>
/// <returns>A NativeKeyValueArrays with a copy of all this hash map's keys and values.</returns>
public readonly NativeKeyValueArrays<TKey, TValue> GetKeyValueArrays(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_MultiHashMapData.GetKeyValueArrays(allocator);
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
readonly void ThrowKeyNotPresent(TKey key)
{
throw new ArgumentException($"Key: {key} is not present in the NativeParallelHashMap.");
}
/// <summary>
/// Returns an enumerator over the key-value pairs of this hash map.
/// </summary>
/// <remarks>A key with *N* values is visited by the enumerator *N* times.</remarks>
/// <returns>An enumerator over the key-value pairs of this hash map.</returns>
public KeyValueEnumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(m_Safety);
var ash = m_Safety;
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new KeyValueEnumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = new UnsafeParallelHashMapDataEnumerator(m_MultiHashMapData.m_Buffer),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<KeyValue<TKey, TValue>> IEnumerable<KeyValue<TKey, TValue>>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void CheckWrite()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndBumpSecondaryVersion(m_Safety);
#endif
}
}
internal sealed class NativeParallelMultiHashMapDebuggerTypeProxy<TKey, TValue>
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
{
NativeParallelMultiHashMap<TKey, TValue> m_Target;
public NativeParallelMultiHashMapDebuggerTypeProxy(NativeParallelMultiHashMap<TKey, TValue> target)
{
m_Target = target;
}
public List<ListPair<TKey, List<TValue>>> Items
{
get
{
var result = new List<ListPair<TKey, List<TValue>>>();
(NativeArray<TKey>, int) keys = default;
using(NativeParallelHashMap<TKey,TValue> uniques = new NativeParallelHashMap<TKey,TValue>(m_Target.Count(),Allocator.Temp))
{
var enumerator = m_Target.GetEnumerator();
while(enumerator.MoveNext())
uniques.TryAdd(enumerator.Current.Key,default);
keys.Item1 = uniques.GetKeyArray(Allocator.Temp);
keys.Item2 = keys.Item1.Length;
}
using (keys.Item1)
{
for (var k = 0; k < keys.Item2; ++k)
{
var values = new List<TValue>();
if (m_Target.TryGetFirstValue(keys.Item1[k], out var value, out var iterator))
{
do
{
values.Add(value);
}
while (m_Target.TryGetNextValue(out value, ref iterator));
}
result.Add(new ListPair<TKey, List<TValue>>(keys.Item1[k], values));
}
}
return result;
}
}
}
/// <summary>
/// Extension methods for NativeParallelMultiHashMap.
/// </summary>
[GenerateTestsForBurstCompatibility]
public unsafe static class NativeParallelMultiHashMapExtensions
{
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int), typeof(int), typeof(AllocatorManager.AllocatorHandle) })]
internal static void Initialize<TKey, TValue, U>(ref this NativeParallelMultiHashMap<TKey, TValue> container,
int capacity,
ref U allocator)
where TKey : unmanaged, IEquatable<TKey>
where TValue : unmanaged
where U : unmanaged, AllocatorManager.IAllocator
{
container.m_MultiHashMapData = new UnsafeParallelMultiHashMap<TKey, TValue>(capacity, allocator.Handle);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
container.m_Safety = CollectionHelper.CreateSafetyHandle(allocator.Handle);
CollectionHelper.SetStaticSafetyId<NativeParallelMultiHashMap<TKey, TValue>>(ref container.m_Safety, ref NativeParallelMultiHashMap<TKey, TValue>.s_staticSafetyId.Data);
#endif
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1de5774def35a6642a480cfd1b8c11d7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,509 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Burst;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
using System.Collections;
namespace Unity.Collections
{
/// <summary>
/// An unmanaged queue.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
[StructLayout(LayoutKind.Sequential)]
[NativeContainer]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public unsafe struct NativeQueue<T>
: INativeDisposable
where T : unmanaged
{
[NativeDisableUnsafePtrRestriction]
UnsafeQueue<T>* m_Queue;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeQueue<T>>();
#endif
/// <summary>
/// Initializes and returns an instance of NativeQueue.
/// </summary>
/// <param name="allocator">The allocator to use.</param>
public NativeQueue(AllocatorManager.AllocatorHandle allocator)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
CollectionHelper.InitNativeContainer<T>(m_Safety);
CollectionHelper.SetStaticSafetyId<NativeQueue<T>>(ref m_Safety, ref s_staticSafetyId.Data);
#endif
m_Queue = UnsafeQueue<T>.Alloc(allocator);
*m_Queue = new UnsafeQueue<T>(allocator);
}
/// <summary>
/// Returns true if this queue is empty.
/// </summary>
/// <returns>True if this queue has no items or if the queue has not been constructed.</returns>
public readonly bool IsEmpty()
{
if (IsCreated)
{
CheckRead();
return m_Queue->IsEmpty();
}
return true;
}
/// <summary>
/// Returns the current number of elements in this queue.
/// </summary>
/// <remarks>Note that getting the count requires traversing the queue's internal linked list of blocks.
/// Where possible, cache this value instead of reading the property repeatedly.</remarks>
/// <returns>The current number of elements in this queue.</returns>
public readonly int Count
{
get
{
CheckRead();
return m_Queue->Count;
}
}
/// <summary>
/// Returns the element at the front of this queue without removing it.
/// </summary>
/// <returns>The element at the front of this queue.</returns>
public T Peek()
{
CheckRead();
return m_Queue->Peek();
}
/// <summary>
/// Adds an element at the back of this queue.
/// </summary>
/// <param name="value">The value to be enqueued.</param>
public void Enqueue(T value)
{
CheckWrite();
m_Queue->Enqueue(value);
}
/// <summary>
/// Removes and returns the element at the front of this queue.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if this queue is empty.</exception>
/// <returns>The element at the front of this queue.</returns>
public T Dequeue()
{
CheckWrite();
return m_Queue->Dequeue();
}
/// <summary>
/// Removes and outputs the element at the front of this queue.
/// </summary>
/// <param name="item">Outputs the removed element.</param>
/// <returns>True if this queue was not empty.</returns>
public bool TryDequeue(out T item)
{
CheckWrite();
return m_Queue->TryDequeue(out item);
}
/// <summary>
/// Returns an array containing a copy of this queue's content.
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <returns>An array containing a copy of this queue's content. The elements are ordered in the same order they were
/// enqueued, *e.g.* the earliest enqueued element is copied to index 0 of the array.</returns>
public NativeArray<T> ToArray(AllocatorManager.AllocatorHandle allocator)
{
CheckRead();
return m_Queue->ToArray(allocator);
}
/// <summary>
/// Removes all elements from this queue.
/// </summary>
public void Clear()
{
CheckWrite();
m_Queue->Clear();
}
/// <summary>
/// Whether this queue has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this queue has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Queue != null && m_Queue->IsCreated;
}
/// <summary>
/// Releases all resources (memory and safety handles).
/// </summary>
public void Dispose()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.DisposeSafetyHandle(ref m_Safety);
#endif
UnsafeQueue<T>.Free(m_Queue);
m_Queue = null;
}
/// <summary>
/// Creates and schedules a job that releases all resources (memory and safety handles) of this queue.
/// </summary>
/// <param name="inputDeps">The dependency for the new job.</param>
/// <returns>The handle of the new job. The job depends upon `inputDeps` and releases all resources (memory and safety handles) of this queue.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return inputDeps;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var jobHandle = new NativeQueueDisposeJob { Data = new NativeQueueDispose { m_QueueData = (UnsafeQueue<int>*)m_Queue, m_Safety = m_Safety } }.Schedule(inputDeps);
AtomicSafetyHandle.Release(m_Safety);
#else
var jobHandle = new NativeQueueDisposeJob { Data = new NativeQueueDispose { m_QueueData = (UnsafeQueue<int>*)m_Queue } }.Schedule(inputDeps);
#endif
m_Queue = null;
return jobHandle;
}
/// <summary>
/// An enumerator over the values of a container.
/// </summary>
/// <remarks>
/// In an enumerator's initial state, <see cref="Current"/> is invalid.
/// The first <see cref="MoveNext"/> call advances the enumerator to the first value.
/// </remarks>
[NativeContainer]
[NativeContainerIsReadOnly]
public struct Enumerator : IEnumerator<T>
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
#endif
internal UnsafeQueue<T>.Enumerator m_Enumerator;
/// <summary>
/// Does nothing.
/// </summary>
public void Dispose() { }
/// <summary>
/// Advances the enumerator to the next value.
/// </summary>
/// <returns>True if `Current` is valid to read after the call.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_Enumerator.MoveNext();
}
/// <summary>
/// Resets the enumerator to its initial state.
/// </summary>
public void Reset()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
m_Enumerator.Reset();
}
/// <summary>
/// The current value.
/// </summary>
/// <value>The current value.</value>
public T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Enumerator.Current;
}
object IEnumerator.Current => Current;
}
/// <summary>
/// Returns a readonly version of this NativeQueue instance.
/// </summary>
/// <remarks>ReadOnly containers point to the same underlying data as the NativeQueue it is made from.</remarks>
/// <returns>ReadOnly instance for this.</returns>
public ReadOnly AsReadOnly()
{
return new ReadOnly(ref this);
}
/// <summary>
/// A read-only alias for the value of a NativeQueue. Does not have its own allocated storage.
/// </summary>
[NativeContainer]
[NativeContainerIsReadOnly]
public struct ReadOnly
: IEnumerable<T>
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
#endif
UnsafeQueue<T>.ReadOnly m_ReadOnly;
internal ReadOnly(ref NativeQueue<T> data)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = data.m_Safety;
CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
#endif
m_ReadOnly = new UnsafeQueue<T>.ReadOnly(ref *data.m_Queue);
}
/// <summary>
/// Whether this container been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this container has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_ReadOnly.IsCreated;
}
/// <summary>
/// Returns true if this queue is empty.
/// </summary>
/// <remarks>Note that getting the count requires traversing the queue's internal linked list of blocks.
/// Where possible, cache this value instead of reading the property repeatedly.</remarks>
/// <returns>True if this queue has no items or if the queue has not been constructed.</returns>
public readonly bool IsEmpty()
{
CheckRead();
return m_ReadOnly.IsEmpty();
}
/// <summary>
/// Returns the current number of elements in this queue.
/// </summary>
/// <remarks>Note that getting the count requires traversing the queue's internal linked list of blocks.
/// Where possible, cache this value instead of reading the property repeatedly.</remarks>
/// <returns>The current number of elements in this queue.</returns>
public readonly int Count
{
get
{
CheckRead();
return m_ReadOnly.Count;
}
}
/// <summary>
/// The element at an index.
/// </summary>
/// <param name="index">An index.</param>
/// <value>The element at the index.</value>
/// <exception cref="IndexOutOfRangeException">Thrown if the index is out of bounds.</exception>
public readonly T this[int index]
{
get
{
CheckRead();
return m_ReadOnly[index];
}
}
/// <summary>
/// Returns an enumerator over the items of this container.
/// </summary>
/// <returns>An enumerator over the items of this container.</returns>
public readonly Enumerator GetEnumerator()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var ash = m_Safety;
AtomicSafetyHandle.CheckGetSecondaryDataPointerAndThrow(ash);
AtomicSafetyHandle.UseSecondaryVersion(ref ash);
#endif
return new Enumerator
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = ash,
#endif
m_Enumerator = m_ReadOnly.GetEnumerator(),
};
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
throw new NotImplementedException();
}
/// <summary>
/// This method is not implemented. Use <see cref="GetEnumerator"/> instead.
/// </summary>
/// <returns>Throws NotImplementedException.</returns>
/// <exception cref="NotImplementedException">Method is not implemented.</exception>
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
}
/// <summary>
/// Returns a parallel writer for this queue.
/// </summary>
/// <returns>A parallel writer for this queue.</returns>
public ParallelWriter AsParallelWriter()
{
ParallelWriter writer;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
writer.m_Safety = m_Safety;
CollectionHelper.SetStaticSafetyId<ParallelWriter>(ref writer.m_Safety, ref ParallelWriter.s_staticSafetyId.Data);
#endif
writer.unsafeWriter = m_Queue->AsParallelWriter();
return writer;
}
/// <summary>
/// A parallel writer for a NativeQueue.
/// </summary>
/// <remarks>
/// Use <see cref="AsParallelWriter"/> to create a parallel writer for a NativeQueue.
/// </remarks>
[NativeContainer]
[NativeContainerIsAtomicWriteOnly]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public unsafe struct ParallelWriter
{
internal UnsafeQueue<T>.ParallelWriter unsafeWriter;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ParallelWriter>();
#endif
/// <summary>
/// Adds an element at the back of the queue.
/// </summary>
/// <param name="value">The value to be enqueued.</param>
public void Enqueue(T value)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
unsafeWriter.Enqueue(value);
}
/// <summary>
/// Adds an element at the back of the queue.
/// </summary>
/// <param name="value">The value to be enqueued.</param>
/// <param name="threadIndexOverride">The thread index which must be set by a field from a job struct with the <see cref="NativeSetThreadIndexAttribute"/> attribute.</param>
public void Enqueue(T value, int threadIndexOverride)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
unsafeWriter.Enqueue(value, threadIndexOverride);
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void CheckWrite()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
}
}
[NativeContainer]
[GenerateTestsForBurstCompatibility]
internal unsafe struct NativeQueueDispose
{
[NativeDisableUnsafePtrRestriction]
public UnsafeQueue<int>* m_QueueData;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
#endif
public void Dispose()
{
UnsafeQueue<int>.Free(m_QueueData);
}
}
[BurstCompile]
struct NativeQueueDisposeJob : IJob
{
public NativeQueueDispose Data;
public void Execute()
{
Data.Dispose();
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 2d8c01f04a0874c9384ae360c07d0098
timeCreated: 1503921931
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,427 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
namespace Unity.Collections
{
/// <summary>
/// An unmanaged single value.
/// </summary>
/// <remarks>The functional equivalent of an array of length 1.
/// When you need just one value, NativeReference can be preferable to an array because it better conveys the intent.</remarks>
/// <typeparam name="T">The type of value.</typeparam>
[StructLayout(LayoutKind.Sequential)]
[NativeContainer]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public unsafe struct NativeReference<T>
: INativeDisposable
, IEquatable<NativeReference<T>>
where T : unmanaged
{
[NativeDisableUnsafePtrRestriction]
internal void* m_Data;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
static readonly SharedStatic<int> s_SafetyId = SharedStatic<int>.GetOrCreate<NativeReference<T>>();
#endif
internal AllocatorManager.AllocatorHandle m_AllocatorLabel;
/// <summary>
/// Initializes and returns an instance of NativeReference.
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
public NativeReference(AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
{
Allocate(allocator, out this);
if (options == NativeArrayOptions.ClearMemory)
{
UnsafeUtility.MemClear(m_Data, sizeof(T));
}
}
/// <summary>
/// Initializes and returns an instance of NativeReference.
/// </summary>
/// <param name="allocator">The allocator to use.</param>
/// <param name="value">The initial value.</param>
public NativeReference(T value, AllocatorManager.AllocatorHandle allocator)
{
Allocate(allocator, out this);
*(T*)m_Data = value;
}
static void Allocate(AllocatorManager.AllocatorHandle allocator, out NativeReference<T> reference)
{
CollectionHelper.CheckAllocator(allocator);
reference = default;
reference.m_Data = Memory.Unmanaged.Allocate(sizeof(T), UnsafeUtility.AlignOf<T>(), allocator);
reference.m_AllocatorLabel = allocator;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
reference.m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
CollectionHelper.InitNativeContainer<T>(reference.m_Safety);
CollectionHelper.SetStaticSafetyId<NativeReference<T>>(ref reference.m_Safety, ref s_SafetyId.Data);
#endif
}
/// <summary>
/// The value stored in this reference.
/// </summary>
/// <param name="value">The new value to store in this reference.</param>
/// <value>The value stored in this reference.</value>
public T Value
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return *(T*)m_Data;
}
set
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
*(T*)m_Data = value;
}
}
/// <summary>
/// Whether this reference has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this reference has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated => m_Data != null;
/// <summary>
/// Releases all resources (memory and safety handles).
/// </summary>
public void Dispose()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return;
}
if (CollectionHelper.ShouldDeallocate(m_AllocatorLabel))
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.DisposeSafetyHandle(ref m_Safety);
#endif
Memory.Unmanaged.Free(m_Data, m_AllocatorLabel);
m_AllocatorLabel = Allocator.Invalid;
}
m_Data = null;
}
/// <summary>
/// Creates and schedules a job that will release all resources (memory and safety handles) of this reference.
/// </summary>
/// <param name="inputDeps">A job handle. The newly scheduled job will depend upon this handle.</param>
/// <returns>The handle of a new job that will release all resources (memory and safety handles) of this reference.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return inputDeps;
}
if (CollectionHelper.ShouldDeallocate(m_AllocatorLabel))
{
var jobHandle = new NativeReferenceDisposeJob
{
Data = new NativeReferenceDispose
{
m_Data = m_Data,
m_AllocatorLabel = m_AllocatorLabel,
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = m_Safety
#endif
}
}.Schedule(inputDeps);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.Release(m_Safety);
#endif
m_Data = null;
m_AllocatorLabel = Allocator.Invalid;
return jobHandle;
}
m_Data = null;
return inputDeps;
}
/// <summary>
/// Copy the value of another reference to this reference.
/// </summary>
/// <param name="reference">The reference to copy from.</param>
public void CopyFrom(NativeReference<T> reference)
{
Copy(this, reference);
}
/// <summary>
/// Copy the value of this reference to another reference.
/// </summary>
/// <param name="reference">The reference to copy to.</param>
public void CopyTo(NativeReference<T> reference)
{
Copy(reference, this);
}
/// <summary>
/// Returns true if the value stored in this reference is equal to the value stored in another reference.
/// </summary>
/// <param name="other">A reference to compare with.</param>
/// <returns>True if the value stored in this reference is equal to the value stored in another reference.</returns>
[ExcludeFromBurstCompatTesting("Equals boxes because Value does not implement IEquatable<T>")]
public bool Equals(NativeReference<T> other)
{
return Value.Equals(other.Value);
}
/// <summary>
/// Returns true if the value stored in this reference is equal to an object.
/// </summary>
/// <remarks>Can only be equal if the object is itself a NativeReference.</remarks>
/// <param name="obj">An object to compare with.</param>
/// <returns>True if the value stored in this reference is equal to the object.</returns>
[ExcludeFromBurstCompatTesting("Takes managed object")]
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is NativeReference<T> && Equals((NativeReference<T>)obj);
}
/// <summary>
/// Returns the hash code of this reference.
/// </summary>
/// <returns>The hash code of this reference.</returns>
public override int GetHashCode()
{
return Value.GetHashCode();
}
/// <summary>
/// Returns true if the values stored in two references are equal.
/// </summary>
/// <param name="left">A reference.</param>
/// <param name="right">Another reference.</param>
/// <returns>True if the two values are equal.</returns>
public static bool operator ==(NativeReference<T> left, NativeReference<T> right)
{
return left.Equals(right);
}
/// <summary>
/// Returns true if the values stored in two references are unequal.
/// </summary>
/// <param name="left">A reference.</param>
/// <param name="right">Another reference.</param>
/// <returns>True if the two values are unequal.</returns>
public static bool operator !=(NativeReference<T> left, NativeReference<T> right)
{
return !left.Equals(right);
}
/// <summary>
/// Copies the value of a reference to another reference.
/// </summary>
/// <param name="dst">The destination reference.</param>
/// <param name="src">The source reference.</param>
public static void Copy(NativeReference<T> dst, NativeReference<T> src)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(src.m_Safety);
AtomicSafetyHandle.CheckWriteAndThrow(dst.m_Safety);
#endif
UnsafeUtility.MemCpy(dst.m_Data, src.m_Data, sizeof(T));
}
/// <summary>
/// Returns a read-only reference aliasing the value of this reference.
/// </summary>
/// <returns>A read-only reference aliasing the value of this reference.</returns>
public ReadOnly AsReadOnly()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
return new ReadOnly(m_Data, ref m_Safety);
#else
return new ReadOnly(m_Data);
#endif
}
/// <summary>
/// Returns a read-only native reference that aliases the content of a native reference.
/// </summary>
/// <param name="nativeReference">NativeReference to alias.</param>
/// <returns>A read-only native reference that aliases the content of a native reference.</returns>
public static implicit operator ReadOnly(NativeReference<T> nativeReference)
{
return nativeReference.AsReadOnly();
}
/// <summary>
/// A read-only alias for the value of a NativeReference. Does not have its own allocated storage.
/// </summary>
[NativeContainer]
[NativeContainerIsReadOnly]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public unsafe struct ReadOnly
{
[NativeDisableUnsafePtrRestriction]
readonly void* m_Data;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<ReadOnly>();
[GenerateTestsForBurstCompatibility(CompileTarget = GenerateTestsForBurstCompatibilityAttribute.BurstCompatibleCompileTarget.Editor)]
internal ReadOnly(void* data, ref AtomicSafetyHandle safety)
{
m_Data = data;
m_Safety = safety;
CollectionHelper.SetStaticSafetyId<ReadOnly>(ref m_Safety, ref s_staticSafetyId.Data);
}
#else
internal ReadOnly(void* data)
{
m_Data = data;
}
#endif
/// <summary>
/// The value aliased by this reference.
/// </summary>
/// <value>The value aliased by the reference.</value>
public T Value
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return *(T*)m_Data;
}
}
}
}
[NativeContainer]
unsafe struct NativeReferenceDispose
{
[NativeDisableUnsafePtrRestriction]
internal void* m_Data;
internal AllocatorManager.AllocatorHandle m_AllocatorLabel;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
#endif
public void Dispose()
{
Memory.Unmanaged.Free(m_Data, m_AllocatorLabel);
}
}
[BurstCompile]
struct NativeReferenceDisposeJob : IJob
{
internal NativeReferenceDispose Data;
public void Execute()
{
Data.Dispose();
}
}
}
namespace Unity.Collections.LowLevel.Unsafe
{
/// <summary>
/// Provides extension methods for NativeReference.
/// </summary>
[GenerateTestsForBurstCompatibility]
public static class NativeReferenceUnsafeUtility
{
/// <summary>
/// Returns a pointer to this reference's stored value.
/// </summary>
/// <remarks>Performs a job safety check for read-write access.</remarks>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="reference">The reference.</param>
/// <returns>A pointer to this reference's stored value.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public static unsafe T* GetUnsafePtr<T>(this NativeReference<T> reference)
where T : unmanaged
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(reference.m_Safety);
#endif
return (T*)reference.m_Data;
}
/// <summary>
/// Returns a pointer to this reference's stored value.
/// </summary>
/// <remarks>Performs a job safety check for read-only access.</remarks>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="reference">The reference.</param>
/// <returns>A pointer to this reference's stored value.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public static unsafe T* GetUnsafeReadOnlyPtr<T>(this NativeReference<T> reference)
where T : unmanaged
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(reference.m_Safety);
#endif
return (T*)reference.m_Data;
}
/// <summary>
/// Returns a pointer to this reference's stored value.
/// </summary>
/// <remarks>Performs no job safety checks.</remarks>
/// <typeparam name="T">The type of the value.</typeparam>
/// <param name="reference">The reference.</param>
/// <returns>A pointer to this reference's stored value.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public static unsafe T* GetUnsafePtrWithoutChecks<T>(this NativeReference<T> reference)
where T : unmanaged
{
return (T*)reference.m_Data;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ca5dd80efed23904a980e0f7fb23ed5d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,277 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
namespace Unity.Collections
{
/// <summary>
/// A fixed-size circular buffer. For single-threaded uses only.
/// </summary>
/// <remarks>
/// This container can't be used in parallel jobs, just on single-thread (for example: main thread, or single IJob).
/// </remarks>
/// <typeparam name="T">The type of the elements.</typeparam>
[StructLayout(LayoutKind.Sequential)]
[NativeContainer]
[DebuggerDisplay("Length = {Length}, Capacity = {Capacity}, IsCreated = {IsCreated}, IsEmpty = {IsEmpty}")]
[DebuggerTypeProxy(typeof(NativeRingQueueDebugView<>))]
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public unsafe struct NativeRingQueue<T>
: INativeDisposable
where T : unmanaged
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeRingQueue<T>>();
#endif
[NativeDisableUnsafePtrRestriction]
internal UnsafeRingQueue<T>* m_RingQueue;
/// <summary>
/// Whether this queue has been allocated (and not yet deallocated).
/// </summary>
/// <value>True if this queue has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_RingQueue != null && m_RingQueue->IsCreated;
}
/// <summary>
/// Whether the queue is empty.
/// </summary>
/// <value>True if the queue is empty or the queue has not been constructed.</value>
public readonly bool IsEmpty
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_RingQueue == null || m_RingQueue->Length == 0;
}
/// <summary>
/// The number of elements currently in this queue.
/// </summary>
/// <value>The number of elements currently in this queue.</value>
public readonly int Length
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return CollectionHelper.AssumePositive(m_RingQueue->Length);
}
}
/// <summary>
/// The number of elements that fit in the internal buffer.
/// </summary>
/// <value>The number of elements that fit in the internal buffer.</value>
public readonly int Capacity
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
CheckRead();
return CollectionHelper.AssumePositive(m_RingQueue->Capacity);
}
}
/// <summary>
/// The maximum number of elements this type of container can hold.
/// </summary>
public const int MaxCapacity = UnsafeRingQueue<T>.MaxCapacity;
/// <summary>
/// Initializes and returns an instance of NativeRingQueue.
/// </summary>
/// <param name="capacity">The capacity.</param>
/// <param name="allocator">The allocator to use.</param>
/// <param name="options">Whether newly allocated bytes should be zeroed out.</param>
public NativeRingQueue(int capacity, AllocatorManager.AllocatorHandle allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory)
{
CollectionHelper.CheckAllocator(allocator);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
CollectionHelper.SetStaticSafetyId<NativeRingQueue<T>>(ref m_Safety, ref s_staticSafetyId.Data);
#endif
m_RingQueue = UnsafeRingQueue<T>.Alloc(allocator);
*m_RingQueue = new UnsafeRingQueue<T>(capacity, allocator, options);
}
/// <summary>
/// Releases all resources (memory and safety handles).
/// </summary>
public void Dispose()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.DisposeSafetyHandle(ref m_Safety);
#endif
UnsafeRingQueue<T>.Free(m_RingQueue);
m_RingQueue = null;
}
/// <summary>
/// Creates and schedules a job that will dispose this queue.
/// </summary>
/// <param name="inputDeps">The handle of a job which the new job will depend upon.</param>
/// <returns>The handle of a new job that will dispose this queue. The new job depends upon inputDeps.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return inputDeps;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var jobHandle = new NativeRingQueueDisposeJob { Data = new NativeRingQueueDispose { m_QueueData = (UnsafeRingQueue<int>*)m_RingQueue, m_Safety = m_Safety } }.Schedule(inputDeps);
AtomicSafetyHandle.Release(m_Safety);
#else
var jobHandle = new NativeRingQueueDisposeJob { Data = new NativeRingQueueDispose { m_QueueData = (UnsafeRingQueue<int>*)m_RingQueue } }.Schedule(inputDeps);
#endif
m_RingQueue = null;
return jobHandle;
}
/// <summary>
/// Adds an element at the front of the queue.
/// </summary>
/// <remarks>Does nothing if the queue is full.</remarks>
/// <param name="value">The value to be added.</param>
/// <returns>True if the value was added.</returns>
public bool TryEnqueue(T value)
{
CheckWrite();
return m_RingQueue->TryEnqueue(value);
}
/// <summary>
/// Adds an element at the front of the queue.
/// </summary>
/// <param name="value">The value to be added.</param>
/// <exception cref="InvalidOperationException">Thrown if the queue was full.</exception>
public void Enqueue(T value)
{
CheckWrite();
m_RingQueue->Enqueue(value);
}
/// <summary>
/// Removes the element from the end of the queue.
/// </summary>
/// <remarks>Does nothing if the queue is empty.</remarks>
/// <param name="item">Outputs the element removed.</param>
/// <returns>True if an element was removed.</returns>
public bool TryDequeue(out T item)
{
CheckRead();
return m_RingQueue->TryDequeue(out item);
}
/// <summary>
/// Removes the element from the end of the queue.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if the queue was empty.</exception>
/// <returns>Returns the removed element.</returns>
public T Dequeue()
{
CheckRead();
return m_RingQueue->Dequeue();
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
readonly void CheckWrite()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
}
}
internal unsafe sealed class NativeRingQueueDebugView<T>
where T : unmanaged
{
UnsafeRingQueue<T>* Data;
public NativeRingQueueDebugView(NativeRingQueue<T> data)
{
Data = data.m_RingQueue;
}
public T[] Items
{
get
{
T[] result = new T[Data->Length];
var read = Data->m_Read;
var capacity = Data->m_Capacity;
for (var i = 0; i < result.Length; ++i)
{
result[i] = Data->Ptr[(read + i) % capacity];
}
return result;
}
}
}
[NativeContainer]
[GenerateTestsForBurstCompatibility]
internal unsafe struct NativeRingQueueDispose
{
[NativeDisableUnsafePtrRestriction]
public UnsafeRingQueue<int>* m_QueueData;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
public AtomicSafetyHandle m_Safety;
#endif
public void Dispose()
{
UnsafeRingQueue<int>.Free(m_QueueData);
}
}
[BurstCompile]
internal unsafe struct NativeRingQueueDisposeJob : IJob
{
public NativeRingQueueDispose Data;
public void Execute()
{
Data.Dispose();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7d1c578573cb6b34b860a0eb47293b24
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ea14c18964a134080bea2f114390f80b
timeCreated: 1492169478
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,886 @@
using System;
using System.Diagnostics;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Burst;
using Unity.Jobs;
using UnityEngine.Assertions;
using System.Runtime.CompilerServices;
namespace Unity.Collections
{
/// <summary>
/// A set of untyped, append-only buffers. Allows for concurrent reading and concurrent writing without synchronization.
/// </summary>
/// <remarks>
/// As long as each individual buffer is written in one thread and read in one thread, multiple
/// threads can read and write the stream concurrently, *e.g.*
/// while thread *A* reads from buffer *X* of a stream, thread *B* can read from
/// buffer *Y* of the same stream.
///
/// Each buffer is stored as a chain of blocks. When a write exceeds a buffer's current capacity, another block
/// is allocated and added to the end of the chain. Effectively, expanding the buffer never requires copying the existing
/// data (unlike with <see cref="NativeList{T}"/>, for example).
///
/// **All writing to a stream should be completed before the stream is first read. Do not write to a stream after the first read.**
/// Violating these rules won't *necessarily* cause any problems, but they are the intended usage pattern.
///
/// Writing is done with <see cref="NativeStream.Writer"/>, and reading is done with <see cref="NativeStream.Reader"/>.
/// An individual reader or writer cannot be used concurrently across threads: each thread must use its own.
///
/// The data written to an individual buffer can be heterogeneous in type, and the data written
/// to different buffers of a stream can be entirely different in type, number, and order. Just make sure
/// that the code reading from a particular buffer knows what to expect to read from it.
/// </remarks>
[NativeContainer]
[GenerateTestsForBurstCompatibility]
public unsafe struct NativeStream : INativeDisposable
{
UnsafeStream m_Stream;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeStream>();
#endif
/// <summary>
/// Initializes and returns an instance of NativeStream.
/// </summary>
/// <param name="bufferCount">The number of buffers to give the stream. You usually want
/// one buffer for each thread that will read or write the stream.</param>
/// <param name="allocator">The allocator to use.</param>
public NativeStream(int bufferCount, AllocatorManager.AllocatorHandle allocator)
{
AllocateBlock(out this, allocator);
m_Stream.AllocateForEach(bufferCount);
}
/// <summary>
/// Creates and schedules a job to allocate a new stream.
/// </summary>
/// <remarks>The stream can be used on the main thread after completing the returned job or used in other jobs that depend upon the returned job.
///
/// Using a job to allocate the buffers can be more efficient, particularly for a stream with many buffers.
/// </remarks>
/// <typeparam name="T">Ignored.</typeparam>
/// <param name="stream">Outputs the new stream.</param>
/// <param name="bufferCount">A list whose length determines the number of buffers in the stream.</param>
/// <param name="dependency">A job handle. The new job will depend upon this handle.</param>
/// <param name="allocator">The allocator to use.</param>
/// <returns>The handle of the new job.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new[] { typeof(int) })]
public static JobHandle ScheduleConstruct<T>(out NativeStream stream, NativeList<T> bufferCount, JobHandle dependency, AllocatorManager.AllocatorHandle allocator)
where T : unmanaged
{
AllocateBlock(out stream, allocator);
var jobData = new ConstructJobList { List = (UntypedUnsafeList*)bufferCount.GetUnsafeList(), Container = stream };
return jobData.Schedule(dependency);
}
/// <summary>
/// Creates and schedules a job to allocate a new stream.
/// </summary>
/// <remarks>The stream can be used...
/// - after completing the returned job
/// - or in other jobs that depend upon the returned job.
///
/// Allocating the buffers in a job can be more efficient, particularly for a stream with many buffers.
/// </remarks>
/// <param name="stream">Outputs the new stream.</param>
/// <param name="bufferCount">An array whose value at index 0 determines the number of buffers in the stream.</param>
/// <param name="dependency">A job handle. The new job will depend upon this handle.</param>
/// <param name="allocator">The allocator to use.</param>
/// <returns>The handle of the new job.</returns>
public static JobHandle ScheduleConstruct(out NativeStream stream, NativeArray<int> bufferCount, JobHandle dependency, AllocatorManager.AllocatorHandle allocator)
{
AllocateBlock(out stream, allocator);
var jobData = new ConstructJobArray { ForEachCountArray = bufferCount, Container = stream };
return jobData.Schedule(dependency);
}
/// <summary>
/// Creates and schedules a job to allocate a new stream.
/// </summary>
/// <remarks>The stream can be used...
/// - after completing the returned job
/// - or in other jobs that depend upon the returned job.
///
/// Allocating the buffers in a job can be more efficient, particularly for a stream with many buffers.
/// </remarks>
/// <param name="stream">Outputs the new stream.</param>
/// <param name="bufferCount">The number of buffers in the stream.</param>
/// <param name="dependency">A job handle. The new job will depend upon this handle.</param>
/// <param name="allocator">The allocator to use.</param>
/// <returns>The handle of the new job.</returns>
public static JobHandle ScheduleConstruct(out NativeStream stream, NativeReference<int> bufferCount, JobHandle dependency, AllocatorManager.AllocatorHandle allocator)
{
AllocateBlock(out stream, allocator);
var jobData = new ConstructJob { ForEachCount = bufferCount, Container = stream };
return jobData.Schedule(dependency);
}
/// <summary>
/// Returns true if this stream is empty.
/// </summary>
/// <returns>True if this stream is empty or the stream has not been constructed.</returns>
public readonly bool IsEmpty()
{
CheckRead();
return m_Stream.IsEmpty();
}
/// <summary>
/// Whether this stream has been allocated (and not yet deallocated).
/// </summary>
/// <remarks>Does not necessarily reflect whether the buffers of the stream have themselves been allocated.</remarks>
/// <value>True if this stream has been allocated (and not yet deallocated).</value>
public readonly bool IsCreated
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => m_Stream.IsCreated;
}
/// <summary>
/// The number of buffers in this stream.
/// </summary>
/// <value>The number of buffers in this stream.</value>
public readonly int ForEachCount
{
get
{
CheckRead();
return m_Stream.ForEachCount;
}
}
/// <summary>
/// Returns a reader of this stream.
/// </summary>
/// <returns>A reader of this stream.</returns>
public Reader AsReader()
{
return new Reader(ref this);
}
/// <summary>
/// Returns a writer of this stream.
/// </summary>
/// <returns>A writer of this stream.</returns>
public Writer AsWriter()
{
return new Writer(ref this);
}
/// <summary>
/// Returns the total number of items in the buffers of this stream.
/// </summary>
/// <remarks>Each <see cref="Writer.Write{T}"/> and <see cref="Writer.Allocate"/> call increments this number.</remarks>
/// <returns>The total number of items in the buffers of this stream.</returns>
public int Count()
{
CheckRead();
return m_Stream.Count();
}
/// <summary>
/// Returns a new NativeArray copy of this stream's data.
/// </summary>
/// <remarks>The length of the array will equal the count of this stream.
///
/// Each buffer of this stream is copied to the array, one after the other.
/// </remarks>
/// <typeparam name="T">The type of values in the array.</typeparam>
/// <param name="allocator">The allocator to use.</param>
/// <returns>A new NativeArray copy of this stream's data.</returns>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public NativeArray<T> ToNativeArray<T>(AllocatorManager.AllocatorHandle allocator) where T : unmanaged
{
CheckRead();
return m_Stream.ToNativeArray<T>(allocator);
}
/// <summary>
/// Releases all resources (memory and safety handles).
/// </summary>
public void Dispose()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.DisposeSafetyHandle(ref m_Safety);
#endif
m_Stream.Dispose();
}
/// <summary>
/// Creates and schedules a job that will release all resources (memory and safety handles) of this stream.
/// </summary>
/// <param name="inputDeps">A job handle which the newly scheduled job will depend upon.</param>
/// <returns>The handle of a new job that will release all resources (memory and safety handles) of this stream.</returns>
public JobHandle Dispose(JobHandle inputDeps)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (!AtomicSafetyHandle.IsDefaultValue(m_Safety))
{
AtomicSafetyHandle.CheckExistsAndThrow(m_Safety);
}
#endif
if (!IsCreated)
{
return inputDeps;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var jobHandle = new NativeStreamDisposeJob { Data = new NativeStreamDispose { m_StreamData = m_Stream, m_Safety = m_Safety } }.Schedule(inputDeps);
AtomicSafetyHandle.Release(m_Safety);
#else
var jobHandle = new NativeStreamDisposeJob { Data = new NativeStreamDispose { m_StreamData = m_Stream } }.Schedule(inputDeps);
#endif
m_Stream = default;
return jobHandle;
}
internal UnsafeStream GetUnsafeStream() => m_Stream;
[BurstCompile]
struct ConstructJobList : IJob
{
public NativeStream Container;
[ReadOnly]
[NativeDisableUnsafePtrRestriction]
public UntypedUnsafeList* List;
public void Execute()
{
var forEachCount = List->m_length;
if (forEachCount > 0)
{
Container.AllocateForEach(forEachCount);
}
}
}
[BurstCompile]
struct ConstructJobArray : IJob
{
public NativeStream Container;
[ReadOnly]
public NativeArray<int> ForEachCountArray;
public void Execute()
{
var forEachCount = ForEachCountArray.Length > 0 ? ForEachCountArray[0] : 0;
if (forEachCount > 0)
{
Container.AllocateForEach(ForEachCountArray[0]);
}
}
}
[BurstCompile]
struct ConstructJob : IJob
{
public NativeStream Container;
public NativeReference<int>.ReadOnly ForEachCount;
public void Execute()
{
if (ForEachCount.Value > 0)
{
Container.AllocateForEach(ForEachCount.Value);
}
}
}
static void AllocateBlock(out NativeStream stream, AllocatorManager.AllocatorHandle allocator)
{
CollectionHelper.CheckAllocator(allocator);
UnsafeStream.AllocateBlock(out stream.m_Stream, allocator);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
stream.m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
CollectionHelper.SetStaticSafetyId(ref stream.m_Safety, ref s_staticSafetyId.Data, "Unity.Collections.NativeStream");
#endif
}
void AllocateForEach(int forEachCount)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CheckForEachCountGreaterThanZero(forEachCount);
var blockData = (UnsafeStreamBlockData*)m_Stream.m_BlockData.Range.Pointer;
var ranges = (UnsafeStreamRange*)blockData->Ranges.Range.Pointer;
Assert.IsTrue(ranges == null);
Assert.AreEqual(0, blockData->RangeCount);
Assert.AreNotEqual(0, blockData->BlockCount);
#endif
m_Stream.AllocateForEach(forEachCount);
}
/// <summary>
/// Writes data into a buffer of a <see cref="NativeStream"/>.
/// </summary>
/// <remarks>An individual writer can only be used for one buffer of one stream.
/// Do not create more than one writer for an individual buffer.</remarks>
[NativeContainer]
[NativeContainerSupportsMinMaxWriteRestriction]
[GenerateTestsForBurstCompatibility]
public unsafe struct Writer
{
UnsafeStream.Writer m_Writer;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<Writer>();
#pragma warning disable CS0414 // warning CS0414: The field 'NativeStream.Writer.m_Length' is assigned but its value is never used
int m_Length;
#pragma warning restore CS0414
int m_MinIndex;
int m_MaxIndex;
#endif
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
[NativeDisableUnsafePtrRestriction]
void* m_PassByRefCheck;
#endif
internal Writer(ref NativeStream stream)
{
m_Writer = stream.m_Stream.AsWriter();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = stream.m_Safety;
CollectionHelper.SetStaticSafetyId(ref m_Safety, ref s_staticSafetyId.Data, "Unity.Collections.NativeStream.Writer");
m_Length = int.MaxValue;
m_MinIndex = int.MinValue;
m_MaxIndex = int.MinValue;
#endif
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
m_PassByRefCheck = null;
#endif
}
/// <summary>
/// The number of buffers in the stream of this writer.
/// </summary>
/// <value>The number of buffers in the stream of this writer.</value>
public int ForEachCount
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
return m_Writer.ForEachCount;
}
}
/// <summary>
/// For internal use only.
/// </summary>
/// <param name="foreEachIndex"></param>
public void PatchMinMaxRange(int foreEachIndex)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_MinIndex = foreEachIndex;
m_MaxIndex = foreEachIndex;
#endif
}
/// <summary>
/// Readies this writer to write to a particular buffer of the stream.
/// </summary>
/// <remarks>Must be called before using this writer. For an individual writer, call this method only once.
///
/// After calling BeginForEachIndex on this writer, passing this writer into functions must be passed by reference.
///
/// When done using this writer, you must call <see cref="EndForEachIndex"/>.</remarks>
/// <param name="foreachIndex">The index of the buffer to write.</param>
public void BeginForEachIndex(int foreachIndex)
{
CheckBeginForEachIndex(foreachIndex);
m_Writer.BeginForEachIndex(foreachIndex);
}
/// <summary>
/// Readies the buffer written by this writer for reading.
/// </summary>
/// <remarks>Must be called before reading the buffer written by this writer.</remarks>
public void EndForEachIndex()
{
CheckEndForEachIndex();
m_Writer.EndForEachIndex();
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
m_Writer.m_ForeachIndex = int.MinValue;
#endif
}
/// <summary>
/// Write a value to a buffer.
/// </summary>
/// <remarks>The value is written to the buffer which was specified
/// with <see cref="BeginForEachIndex"/>.
/// </remarks>
/// <typeparam name="T">The type of value to write.</typeparam>
/// <param name="value">The value to write.</param>
/// <exception cref="ArgumentException">Thrown if BeginForEachIndex was not called.</exception>
/// <exception cref="ArgumentException">Thrown when the NativeStream.Writer instance has been passed by value instead of by reference.</exception>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public void Write<T>(T value) where T : unmanaged
{
ref T dst = ref Allocate<T>();
dst = value;
}
/// <summary>
/// Allocate space in a buffer.
/// </summary>
/// <remarks>The space is allocated in the buffer which was specified
/// with <see cref="BeginForEachIndex"/>.
/// </remarks>
/// <typeparam name="T">The type of value to allocate space for.</typeparam>
/// <returns>A reference to the allocation.</returns>
/// <exception cref="ArgumentException">Thrown if BeginForEachIndex was not called.</exception>
/// <exception cref="ArgumentException">Thrown when the NativeStream.Writer instance has been passed by value instead of by reference.</exception>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public ref T Allocate<T>() where T : unmanaged
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (UnsafeUtility.IsNativeContainerType<T>())
AtomicSafetyHandle.SetNestedContainer(m_Safety, true);
#endif
int size = sizeof(T);
return ref UnsafeUtility.AsRef<T>(Allocate(size));
}
/// <summary>
/// Allocate space in a buffer.
/// </summary>
/// <remarks>The space is allocated in the buffer which was specified
/// with <see cref="BeginForEachIndex"/>.</remarks>
/// <param name="size">The number of bytes to allocate.</param>
/// <returns>The allocation.</returns>
/// <exception cref="ArgumentException">Thrown if BeginForEachIndex was not called.</exception>
/// <exception cref="ArgumentException">Thrown when the NativeStream.Writer instance has been passed by value instead of by reference.</exception>
public byte* Allocate(int size)
{
CheckAllocateSize(size);
return m_Writer.Allocate(size);
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckBeginForEachIndex(int foreachIndex)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
if (m_PassByRefCheck == null)
{
m_PassByRefCheck = UnsafeUtility.AddressOf(ref this);
}
var blockData = (UnsafeStreamBlockData*)m_Writer.m_BlockData.Range.Pointer;
var ranges = (UnsafeStreamRange*)blockData->Ranges.Range.Pointer;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if (foreachIndex < m_MinIndex || foreachIndex > m_MaxIndex)
{
// When the code is not running through the job system no ParallelForRange patching will occur
// We can't grab m_BlockStream->RangeCount on creation of the writer because the RangeCount can be initialized
// in a job after creation of the writer
if (m_MinIndex == int.MinValue && m_MaxIndex == int.MinValue)
{
m_MinIndex = 0;
m_MaxIndex = blockData->RangeCount - 1;
}
if (foreachIndex < m_MinIndex || foreachIndex > m_MaxIndex)
{
throw new ArgumentException($"Index {foreachIndex} is out of restricted IJobParallelFor range [{m_MinIndex}...{m_MaxIndex}] in NativeStream.");
}
}
#endif
if (m_Writer.m_ForeachIndex != int.MinValue)
{
throw new ArgumentException($"BeginForEachIndex must always be balanced by a EndForEachIndex call");
}
Assert.IsTrue(foreachIndex >= 0 && foreachIndex < blockData->RangeCount);
if (0 != ranges[foreachIndex].ElementCount)
{
throw new ArgumentException($"BeginForEachIndex can only be called once for the same index ({foreachIndex}).");
}
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckEndForEachIndex()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
if (m_Writer.m_ForeachIndex == int.MinValue)
{
throw new System.ArgumentException("EndForEachIndex must always be called balanced by a BeginForEachIndex or AppendForEachIndex call");
}
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckAllocateSize(int size)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
if (m_PassByRefCheck != UnsafeUtility.AddressOf(ref this)
|| m_Writer.m_ForeachIndex == int.MinValue)
{
throw new ArgumentException("BeginForEachIndex has not been called on NativeStream.Writer, or NativeStream.Writer is not passed by reference.");
}
if (size > UnsafeStreamBlockData.AllocationSize - sizeof(void*))
{
throw new ArgumentException("Allocation size is too large");
}
#endif
}
}
/// <summary>
/// Reads data from a buffer of a <see cref="NativeStream"/>.
/// </summary>
/// <remarks>An individual reader can only be used for one buffer of one stream.
/// Do not create more than one reader for an individual buffer.</remarks>
[NativeContainer]
[NativeContainerIsReadOnly]
[GenerateTestsForBurstCompatibility]
public unsafe struct Reader
{
UnsafeStream.Reader m_Reader;
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
int m_RemainingBlocks;
#endif
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<Reader>();
#endif
internal Reader(ref NativeStream stream)
{
m_Reader = stream.m_Stream.AsReader();
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
m_RemainingBlocks = 0;
#endif
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_Safety = stream.m_Safety;
CollectionHelper.SetStaticSafetyId(ref m_Safety, ref s_staticSafetyId.Data, "Unity.Collections.NativeStream.Reader");
#endif
}
/// <summary>
/// Readies this reader to read a particular buffer of the stream.
/// </summary>
/// <remarks>Must be called before using this reader. For an individual reader, call this method only once.
///
/// When done using this reader, you must call <see cref="EndForEachIndex"/>.</remarks>
/// <param name="foreachIndex">The index of the buffer to read.</param>
/// <returns>The number of elements left to read from the buffer.</returns>
public int BeginForEachIndex(int foreachIndex)
{
CheckBeginForEachIndex(foreachIndex);
var remainingItemCount = m_Reader.BeginForEachIndex(foreachIndex);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
var blockData = (UnsafeStreamBlockData*)m_Reader.m_BlockData.Range.Pointer;
var ranges = (UnsafeStreamRange*)blockData->Ranges.Range.Pointer;
m_RemainingBlocks = ranges[foreachIndex].NumberOfBlocks;
if (m_RemainingBlocks == 0)
{
m_Reader.m_CurrentBlockEnd = (byte*)m_Reader.m_CurrentBlock + m_Reader.m_LastBlockSize;
}
#endif
return remainingItemCount;
}
/// <summary>
/// Checks if all data has been read from the buffer.
/// </summary>
/// <remarks>If you intentionally don't want to read *all* the data in the buffer, don't call this method.
/// Otherwise, calling this method is recommended, even though it's not strictly necessary.</remarks>
/// <exception cref="ArgumentException">Thrown if not all the buffer's data has been read.</exception>
public void EndForEachIndex()
{
m_Reader.EndForEachIndex();
CheckEndForEachIndex();
}
/// <summary>
/// The number of buffers in the stream of this reader.
/// </summary>
/// <value>The number of buffers in the stream of this reader.</value>
public int ForEachCount
{
get
{
CheckRead();
return m_Reader.ForEachCount;
}
}
/// <summary>
/// The number of items not yet read from the buffer.
/// </summary>
/// <value>The number of items not yet read from the buffer.</value>
public int RemainingItemCount => m_Reader.RemainingItemCount;
/// <summary>
/// Returns the internal unsafe stream reader.
/// </summary>
/// <remarks>Internally, the NativeStream.Reader uses an unsafe stream reader for access to the stream content.</remarks>
/// <returns>The internal unsafe stream reader.</returns>
public UnsafeStream.Reader GetUnsafeReader() => m_Reader;
/// <summary>
/// Returns a pointer to the next position to read from the buffer. Advances the reader some number of bytes.
/// </summary>
/// <param name="size">The number of bytes to advance the reader.</param>
/// <returns>A pointer to the next position to read from the buffer.</returns>
/// <exception cref="ArgumentException">Thrown if the reader would advance past the end of the buffer.</exception>
public byte* ReadUnsafePtr(int size)
{
CheckReadSize(size);
m_Reader.m_RemainingItemCount--;
byte* ptr = m_Reader.m_CurrentPtr;
m_Reader.m_CurrentPtr += size;
if (m_Reader.m_CurrentPtr > m_Reader.m_CurrentBlockEnd)
{
/*
* On netfw/mono/il2cpp, doing m_CurrentBlock->Data does not throw, because it knows that it can
* just do pointer + 8. On netcore, doing that throws a NullReferenceException. So, first check for
* out of bounds accesses, and only then update m_CurrentBlock and m_CurrentPtr.
*/
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
m_RemainingBlocks--;
CheckNotReadingOutOfBounds(size);
#endif
m_Reader.m_CurrentBlock = m_Reader.m_CurrentBlock->Next;
m_Reader.m_CurrentPtr = m_Reader.m_CurrentBlock->Data;
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
if (m_RemainingBlocks <= 0)
{
m_Reader.m_CurrentBlockEnd = (byte*)m_Reader.m_CurrentBlock + m_Reader.m_LastBlockSize;
}
else
{
m_Reader.m_CurrentBlockEnd = (byte*)m_Reader.m_CurrentBlock + UnsafeStreamBlockData.AllocationSize;
}
#else
m_Reader.m_CurrentBlockEnd = (byte*)m_Reader.m_CurrentBlock + UnsafeStreamBlockData.AllocationSize;
#endif
ptr = m_Reader.m_CurrentPtr;
m_Reader.m_CurrentPtr += size;
}
return ptr;
}
/// <summary>
/// Reads the next value from the buffer.
/// </summary>
/// <remarks>Each read advances the reader to the next item in the buffer.</remarks>
/// <typeparam name="T">The type of value to read.</typeparam>
/// <returns>A reference to the next value from the buffer.</returns>
/// <exception cref="ArgumentException">Thrown if the reader would advance past the end of the buffer.</exception>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public ref T Read<T>() where T : unmanaged
{
int size = sizeof(T);
return ref UnsafeUtility.AsRef<T>(ReadUnsafePtr(size));
}
/// <summary>
/// Reads the next value from the buffer. Does not advance the reader.
/// </summary>
/// <typeparam name="T">The type of value to read.</typeparam>
/// <returns>A reference to the next value from the buffer.</returns>
/// <exception cref="ArgumentException">Thrown if the read would go past the end of the buffer.</exception>
[GenerateTestsForBurstCompatibility(GenericTypeArguments = new [] { typeof(int) })]
public ref T Peek<T>() where T : unmanaged
{
int size = sizeof(T);
CheckReadSize(size);
return ref m_Reader.Peek<T>();
}
/// <summary>
/// Returns the total number of items in the buffers of the stream.
/// </summary>
/// <returns>The total number of items in the buffers of the stream.</returns>
public int Count()
{
CheckRead();
return m_Reader.Count();
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckNotReadingOutOfBounds(int size)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
if (m_RemainingBlocks < 0)
throw new System.ArgumentException("Reading out of bounds");
if (m_RemainingBlocks == 0 && size + sizeof(void*) > m_Reader.m_LastBlockSize)
throw new System.ArgumentException("Reading out of bounds");
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckReadSize(int size)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.IsTrue(size <= UnsafeStreamBlockData.AllocationSize - (sizeof(void*)));
if (m_Reader.m_RemainingItemCount < 1)
{
throw new ArgumentException("There are no more items left to be read.");
}
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckBeginForEachIndex(int forEachIndex)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
var blockData = (UnsafeStreamBlockData*)m_Reader.m_BlockData.Range.Pointer;
if ((uint)forEachIndex >= (uint)blockData->RangeCount)
{
throw new System.ArgumentOutOfRangeException(nameof(forEachIndex), $"foreachIndex: {forEachIndex} must be between 0 and ForEachCount: {blockData->RangeCount}");
}
#endif
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
void CheckEndForEachIndex()
{
if (m_Reader.m_RemainingItemCount != 0)
{
throw new System.ArgumentException("Not all elements (Count) have been read. If this is intentional, simply skip calling EndForEachIndex();");
}
if (m_Reader.m_CurrentBlockEnd != m_Reader.m_CurrentPtr)
{
throw new System.ArgumentException("Not all data (Data Size) has been read. If this is intentional, simply skip calling EndForEachIndex();");
}
}
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS"), Conditional("UNITY_DOTS_DEBUG")]
static void CheckForEachCountGreaterThanZero(int forEachCount)
{
if (forEachCount <= 0)
throw new ArgumentException("foreachCount must be > 0", "foreachCount");
}
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
readonly void CheckRead()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
}
}
[NativeContainer]
[GenerateTestsForBurstCompatibility]
internal unsafe struct NativeStreamDispose
{
public UnsafeStream m_StreamData;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal AtomicSafetyHandle m_Safety;
#endif
public void Dispose()
{
m_StreamData.Dispose();
}
}
[BurstCompile]
struct NativeStreamDisposeJob : IJob
{
public NativeStreamDispose Data;
public void Execute()
{
Data.Dispose();
}
}
}
namespace Unity.Collections.LowLevel.Unsafe
{
/// <summary>
/// Provides unsafe utility methods for NativeStream.
/// </summary>
[GenerateTestsForBurstCompatibility]
public static unsafe class NativeStreamUnsafeUtility
{
/// <summary>
/// Returns a pointer to this stream's <see cref="NativeStream.ForEachCount">buffer counter</see>.
/// </summary>
/// <param name="stream"> The stream.</param>
/// <returns>A pointer to this stream's <see cref="NativeStream.ForEachCount">buffer counter</see>.</returns>
[GenerateTestsForBurstCompatibility]
public static void* GetUnsafeForEachCountPtr(ref this NativeStream stream)
{
return stream.GetUnsafeStream().GetForEachCountPtr();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 64aa0d92f72fa4af49049126211731d0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

Some files were not shown because too many files have changed in this diff Show More