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,353 @@
#region allocator-custom-example
using System;
using AOT;
using System.Collections.Generic;
using System.Threading.Tasks;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Burst;
using System.Threading;
// This is the example code used in
// Packages/com.unity.collections/Documentation~/allocator/allocator-custom.md
// Example custom allocator. The allocator is able to allocate memory from Allocator.Persistant,
// if successful, initialize the allocated memory with a user configured value and increment an
// allocation count. The allocator is able to deallocate the memory, if successful, decrement
// the allocation count.
// A custom allocator must implement AllocatorManager.IAllocator interface
[BurstCompile(CompileSynchronously = true)]
internal struct ExampleCustomAllocator : AllocatorManager.IAllocator
{
// A custom allocator must contain AllocatorManager.AllocatorHandle
AllocatorManager.AllocatorHandle m_handle;
// Implement the Function property required by IAllocator interface
public AllocatorManager.TryFunction Function => AllocatorFunction;
// Implement the Handle property required by IAllocator interface
public AllocatorManager.AllocatorHandle Handle { get { return m_handle; } set { m_handle = value; } }
// Implement the ToAllocator property required by IAllocator interface
public Allocator ToAllocator { get { return m_handle.ToAllocator; } }
// Implement the IsCustomAllocator property required by IAllocator interface
public bool IsCustomAllocator { get { return m_handle.IsCustomAllocator; } }
// Implement the IsAutoDispose property required by IAllocator interface
// Allocations made by this example allocator are not automatically disposed.
// This implementation can be skipped because the default implementation of
// this property is false.
public bool IsAutoDispose { get { return false; } }
// Implement the Dispose method required by IDisposable interface because
// AllocatorManager.IAllocator implements IDisposable
public void Dispose()
{
// Make sure no memory leaks
Assert.AreEqual(0, m_allocationCount);
m_handle.Dispose();
}
#region allocator-custom-try
// Value to initialize the allocated memory
byte m_initialValue;
// Allocation count
int m_allocationCount;
// Implement the Try method required by IAllocator interface
public unsafe int Try(ref AllocatorManager.Block block)
{
// Error status
int error = 0;
// Allocate
if (block.Range.Pointer == IntPtr.Zero)
{
// Allocate memory from Allocator.Persistant and restore the original allocator
AllocatorManager.AllocatorHandle tempAllocator = block.Range.Allocator;
block.Range.Allocator = Allocator.Persistent;
error = AllocatorManager.Try(ref block);
block.Range.Allocator = tempAllocator;
// return if error occurs
if (error != 0)
return error;
// if allocation succeeds, intialize the memory with the initial value and increment the allocation count
if (block.Range.Pointer != IntPtr.Zero)
{
UnsafeUtility.MemSet((void*)block.Range.Pointer, m_initialValue, block.Bytes);
Interlocked.Increment(ref m_allocationCount);
}
return 0;
}
// Deallocate
else
{
// Deallocate memory from Allocator.Persistant and restore the original allocator
AllocatorManager.AllocatorHandle tempAllocator = block.Range.Allocator;
block.Range.Allocator = Allocator.Persistent;
error = AllocatorManager.Try(ref block);
block.Range.Allocator = tempAllocator;
// return if error occurs
if (error != 0)
return error;
// if deallocation succeeds, decrement the allocation count
if (block.Range.Pointer == IntPtr.Zero)
{
Interlocked.Decrement(ref m_allocationCount);
}
return 0;
}
}
#endregion // allocator-custom-try
#region allocator-custom-allocator-function
// Implement the allocator function of delegate AllocatorManager.TryFunction that is
// required when register the allocator on the global allocator table
[BurstCompile(CompileSynchronously = true)]
[MonoPInvokeCallback(typeof(AllocatorManager.TryFunction))]
public static unsafe int AllocatorFunction(IntPtr customAllocatorPtr, ref AllocatorManager.Block block)
{
return ((ExampleCustomAllocator*)customAllocatorPtr)->Try(ref block);
}
#endregion // allocator-custom-allocator-function
// Property to get the initial value
public byte InitialValue => m_initialValue;
// Property to get the allocation count
public int AllocationCount => m_allocationCount;
// Initialize the allocator
public void Initialize(byte initialValue)
{
m_initialValue = initialValue;
m_allocationCount = 0;
}
}
#endregion // allocator-custom-example
#region allocator-custom-user-struct
// Example user structure that contains the custom allocator
internal struct ExampleCustomAllocatorStruct
{
// Use AllocatorHelper to help creating the example custom alloctor
AllocatorHelper<ExampleCustomAllocator> customAllocatorHelper;
// Custom allocator property for accessibility
public ref ExampleCustomAllocator customAllocator => ref customAllocatorHelper.Allocator;
// Create the example custom allocator
void CreateCustomAllocator(AllocatorManager.AllocatorHandle backgroundAllocator, byte initialValue)
{
// Allocate the custom allocator from backgroundAllocator and register the allocator
customAllocatorHelper = new AllocatorHelper<ExampleCustomAllocator>(backgroundAllocator);
// Set the initial value to initialize the memory
customAllocator.Initialize(initialValue);
}
#region allocator-custom-dispose
// Dispose the custom allocator
void DisposeCustomAllocator()
{
// Dispose the custom allocator
customAllocator.Dispose();
// Unregister the custom allocator and dispose it
customAllocatorHelper.Dispose();
}
#endregion // allocator-custom-dispose
// Constructor of user structure
public ExampleCustomAllocatorStruct(byte initialValue)
{
this = default;
CreateCustomAllocator(Allocator.Persistent, initialValue);
}
// Dispose the user structure
public void Dispose()
{
DisposeCustomAllocator();
}
#region allocator-custom-use
// Sample code to use the custom allocator to allocate containers
public void UseCustomAllocator(out NativeArray<int> nativeArray, out NativeList<int> nativeList)
{
// Use custom allocator to allocate a native array and check initial value.
nativeArray = CollectionHelper.CreateNativeArray<int, ExampleCustomAllocator>(100, ref customAllocator, NativeArrayOptions.UninitializedMemory);
Assert.AreEqual(customAllocator.InitialValue, (byte)nativeArray[0] & 0xFF);
nativeArray[0] = 0xFE;
// Use custom allocator to allocate a native list and check initial value.
nativeList = new NativeList<int>(customAllocator.Handle);
for (int i = 0; i < 50; i++)
{
nativeList.Add(i);
}
unsafe
{
// Use custom allocator to allocate a byte buffer.
byte* bytePtr = (byte*)AllocatorManager.Allocate(ref customAllocator, sizeof(byte), sizeof(byte), 10);
Assert.AreEqual(customAllocator.InitialValue, bytePtr[0]);
// Free the byte buffer.
AllocatorManager.Free(customAllocator.ToAllocator, bytePtr, 10);
}
}
#endregion // allocator-custom-use
// Get allocation count from the custom allocator
public int AllocationCount => customAllocator.AllocationCount;
public void UseCustomAllocatorHandle(out NativeArray<int> nativeArray, out NativeList<int> nativeList)
{
// Use custom allocator to allocate a native array and check initial value.
nativeArray = CollectionHelper.CreateNativeArray<int>(100, customAllocator.ToAllocator, NativeArrayOptions.UninitializedMemory);
Assert.AreEqual(customAllocator.InitialValue, (byte)nativeArray[0] & 0xFF);
nativeArray[0] = 0xFE;
// Use custom allocator to allocate a native list and check initial value.
nativeList = new NativeList<int>(customAllocator.Handle);
for (int i = 0; i < 50; i++)
{
nativeList.Add(i);
}
unsafe
{
// Use custom allocator to allocate a byte buffer.
byte* bytePtr = (byte*)AllocatorManager.Allocate(ref customAllocator, sizeof(byte), sizeof(byte), 10);
Assert.AreEqual(customAllocator.InitialValue, bytePtr[0]);
// Free the byte buffer.
AllocatorManager.Free(customAllocator.ToAllocator, bytePtr, 10);
}
}
}
internal class ExampleCustomAllocatorStructUsage
{
// Initial value for the custom allocator.
const int IntialValue = 0xAB;
// Test code.
[Test]
public void UseCustomAllocator_Works()
{
ExampleCustomAllocatorStruct exampleStruct = new ExampleCustomAllocatorStruct(IntialValue);
// Allocate native array and native list from the custom allocator
exampleStruct.UseCustomAllocator(out NativeArray<int> nativeArray, out NativeList<int> nativeList);
// Able to access the native array and native list
Assert.AreEqual(nativeArray[0], 0xFE);
Assert.AreEqual(nativeList[10], 10);
// Need to use CollectionHelper.DisposeNativeArray to dispose the native array from a custom allocator
CollectionHelper.Dispose(nativeArray) ;
// Dispose the native list
nativeList.Dispose();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
// Object disposed exception throws because nativeArray is already disposed
Assert.Throws<ObjectDisposedException>(() =>
{
nativeArray[0] = 0xEF;
});
// Object disposed exception throws because nativeList is already disposed
Assert.Throws<ObjectDisposedException>(() =>
{
nativeList[10] = 0x10;
});
#endif
// Check allocation count after dispose the native array and native list
Assert.AreEqual(0, exampleStruct.AllocationCount);
// Dispose the user structure
exampleStruct.Dispose();
}
[Test]
public void UseCustomAllocatorHandle_Works()
{
ExampleCustomAllocatorStruct exampleStruct = new ExampleCustomAllocatorStruct(IntialValue);
// Allocate native array and native list from the custom allocator handle
exampleStruct.UseCustomAllocatorHandle(out NativeArray<int> nativeArray, out NativeList<int> nativeList);
// Able to access the native array and native list
Assert.AreEqual(nativeArray[0], 0xFE);
Assert.AreEqual(nativeList[10], 10);
// Need to use CollectionHelper.DisposeNativeArray to dispose the native array from a custom allocator
CollectionHelper.Dispose(nativeArray);
// Dispose the native list
nativeList.Dispose();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
// Object disposed exception throws because nativeArray is already disposed
Assert.Throws<ObjectDisposedException>(() =>
{
nativeArray[0] = 0xEF;
});
// Object disposed exception throws because nativeList is already disposed
Assert.Throws<ObjectDisposedException>(() =>
{
nativeList[10] = 0x10;
});
#endif
// Check allocation count after dispose the native array and native list
Assert.AreEqual(0, exampleStruct.AllocationCount);
// Dispose the user structure
exampleStruct.Dispose();
}
[Test]
public void CustomAllocatorHandle_MultiThreadWorks()
{
ExampleCustomAllocatorStruct exampleStruct = new ExampleCustomAllocatorStruct(IntialValue);
var taskList = new List<Task>();
// create 128 native array with another threads
for (var i = 0; i < 128; i++)
{
var task = Task.Run(() =>
{
var nativeArray = CollectionHelper.CreateNativeArray<int, ExampleCustomAllocator>(100, ref exampleStruct.customAllocator,
NativeArrayOptions.UninitializedMemory);
CollectionHelper.Dispose(nativeArray);
});
taskList.Add(task);
}
Task.WaitAll(taskList.ToArray());
exampleStruct.Dispose();
}
}
#endregion // allocator-custom-user-struct
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 56d662dab3a7e9044a036b9b0a52486e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,123 @@
#region allocator-rewindable-example
using System;
using NUnit.Framework;
using Unity.Collections;
// This is the example code used in
// Packages/com.unity.collections/Documentation~/allocator/allocator-rewindable.md
// Example user structure
internal struct ExampleStruct
{
// Use AllocatorHelper to help creating a rewindable alloctor
AllocatorHelper<RewindableAllocator> rwdAllocatorHelper;
// Rewindable allocator property for accessibility
public ref RewindableAllocator RwdAllocator => ref rwdAllocatorHelper.Allocator;
// Create the rewindable allocator
void CreateRewindableAllocator(AllocatorManager.AllocatorHandle backgroundAllocator, int initialBlockSize, bool enableBlockFree = false)
{
// Allocate the rewindable allocator from backgroundAllocator and register the allocator
rwdAllocatorHelper = new AllocatorHelper<RewindableAllocator>(backgroundAllocator);
// Allocate the first memory block with initialBlockSize in bytes, and indicate whether
// to enable the rewindable allocator with individual block free through enableBlockFree
RwdAllocator.Initialize(initialBlockSize, enableBlockFree);
}
// Constructor of user structure
public ExampleStruct(int initialBlockSize)
{
this = default;
CreateRewindableAllocator(Allocator.Persistent, initialBlockSize, false);
}
// Dispose the user structure
public void Dispose()
{
DisposeRewindableAllocator();
}
#region allocator-rewindable-use
// Sample code to use rewindable allocator to allocate containers
public unsafe void UseRewindableAllocator(out NativeArray<int> nativeArray, out NativeList<int> nativeList, out byte* bytePtr)
{
// Use rewindable allocator to allocate a native array, no need to dispose the array manually
// CollectionHelper is required to create/allocate native array from a custom allocator.
nativeArray = CollectionHelper.CreateNativeArray<int, RewindableAllocator>(100, ref RwdAllocator);
nativeArray[0] = 0xFE;
// Use rewindable allocator to allocate a native list, do not need to dispose the list manually
nativeList = new NativeList<int>(RwdAllocator.Handle);
for (int i = 0; i < 50; i++)
{
nativeList.Add(i);
}
// Use custom allocator to allocate a byte buffer.
bytePtr = (byte*)AllocatorManager.Allocate(ref RwdAllocator, sizeof(byte), sizeof(byte), 10);
bytePtr[0] = 0xAB;
}
#endregion // allocator-rewindable-use
#region allocator-rewindable-free
// Free all allocations from the rewindable allocator
public void FreeRewindableAllocator()
{
RwdAllocator.Rewind();
}
#endregion // allocator-rewindable-free
#region allocator-rewindable-dispose
// Dispose the rewindable allocator
void DisposeRewindableAllocator()
{
// Dispose all the memory blocks in the rewindable allocator
RwdAllocator.Dispose();
// Unregister the rewindable allocator and dispose it
rwdAllocatorHelper.Dispose();
}
#endregion // allocator-rewindable-dispose
}
internal class ExampleStructSampleUsage
{
// Initial block size of the rewindable allocator.
const int IntialBlockSize = 128 * 1024;
[Test]
public unsafe void UseRewindableAllocator_Works()
{
ExampleStruct exampleStruct = new ExampleStruct(IntialBlockSize);
// Allocate native array and native list from rewindable allocator
exampleStruct.UseRewindableAllocator(out NativeArray<int> nativeArray, out NativeList<int> nativeList, out byte* bytePtr);
// Still able to access the native array, native list and byte buffer
Assert.AreEqual(nativeArray[0], 0xFE);
Assert.AreEqual(nativeList[10], 10);
Assert.AreEqual(bytePtr[0], 0xAB);
// Free all memories allocated from the rewindable allocator
// No need to dispose the native array and native list
exampleStruct.FreeRewindableAllocator();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
// Object disposed exception throws because nativeArray is already disposed
Assert.Throws<ObjectDisposedException>(() =>
{
nativeArray[0] = 0xEF;
});
// Object disposed exception throws because nativeList is already disposed
Assert.Throws<ObjectDisposedException>(() =>
{
nativeList[10] = 0x10;
});
#endif
// Dispose the user structure
exampleStruct.Dispose();
}
}
#endregion // allocator-rewindable-example
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2875d3f6474aaee46b2421966a741a1d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,159 @@
using System;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.Tests;
internal class BitFieldTests : CollectionsTestFixture
{
[Test]
public void BitField32_Get_Set()
{
var test = new BitField32();
uint bits;
bits = test.GetBits(0, 32);
Assert.AreEqual(0x0, bits);
test.SetBits(0, true);
bits = test.GetBits(0, 32);
Assert.AreEqual(0x1, bits);
test.SetBits(0, true, 32);
bits = test.GetBits(0, 32);
Assert.AreEqual(0xffffffff, bits);
Assert.IsTrue(test.TestAll(0, 32));
test.SetBits(0, false, 32);
bits = test.GetBits(0, 32);
Assert.AreEqual(0x0, bits);
test.SetBits(15, true, 7);
Assert.IsTrue(test.TestAll(15, 7));
test.SetBits(3, true, 3);
Assert.IsTrue(test.TestAll(3, 3));
bits = test.GetBits(0, 32);
Assert.AreEqual(0x3f8038, bits);
bits = test.GetBits(0, 15);
Assert.AreEqual(0x38, bits);
Assert.IsFalse(test.TestNone(0, 32));
Assert.IsFalse(test.TestAll(0, 32));
Assert.IsTrue(test.TestAny(0, 32));
}
[Test]
public void BitField32_Count_Leading_Trailing()
{
var test = new BitField32();
Assert.AreEqual(0, test.CountBits());
Assert.AreEqual(32, test.CountLeadingZeros());
Assert.AreEqual(32, test.CountTrailingZeros());
test.SetBits(31, true);
Assert.AreEqual(1, test.CountBits());
Assert.AreEqual(0, test.CountLeadingZeros());
Assert.AreEqual(31, test.CountTrailingZeros());
test.SetBits(0, true);
Assert.AreEqual(2, test.CountBits());
Assert.AreEqual(0, test.CountLeadingZeros());
Assert.AreEqual(0, test.CountTrailingZeros());
test.SetBits(31, false);
Assert.AreEqual(1, test.CountBits());
Assert.AreEqual(31, test.CountLeadingZeros());
Assert.AreEqual(0, test.CountTrailingZeros());
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public void BitField32_Throws()
{
var test = new BitField32();
for (byte i = 0; i < 32; ++i)
{
Assert.DoesNotThrow(() => { test.GetBits(i, (byte)(32 - i)); });
}
Assert.Throws<ArgumentException>(() => { test.GetBits(0, 33); });
Assert.Throws<ArgumentException>(() => { test.GetBits(1, 32); });
}
[Test]
public void BitField64_Get_Set()
{
var test = new BitField64();
ulong bits;
bits = test.GetBits(0, 64);
Assert.AreEqual(0x0, bits);
test.SetBits(0, true);
bits = test.GetBits(0, 64);
Assert.AreEqual(0x1, bits);
test.SetBits(0, true, 64);
bits = test.GetBits(0, 64);
Assert.AreEqual(0xfffffffffffffffful, bits);
Assert.IsTrue(test.TestAll(0, 64));
test.SetBits(0, false, 64);
bits = test.GetBits(0, 64);
Assert.AreEqual(0x0ul, bits);
test.SetBits(15, true, 7);
Assert.IsTrue(test.TestAll(15, 7));
test.SetBits(3, true, 3);
Assert.IsTrue(test.TestAll(3, 3));
bits = test.GetBits(0, 32);
Assert.AreEqual(0x3f8038, bits);
bits = test.GetBits(0, 15);
Assert.AreEqual(0x38, bits);
Assert.IsFalse(test.TestNone(0, 64));
Assert.IsFalse(test.TestAll(0, 64));
Assert.IsTrue(test.TestAny(0, 64));
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public void BitField64_Throws()
{
var test = new BitField64();
for (byte i = 0; i < 64; ++i)
{
Assert.DoesNotThrow(() => { test.GetBits(i, (byte)(64 - i)); });
}
Assert.Throws<ArgumentException>(() => { test.GetBits(0, 65); });
Assert.Throws<ArgumentException>(() => { test.GetBits(1, 64); });
}
[Test]
public void BitField64_Count_Leading_Trailing()
{
var test = new BitField64();
Assert.AreEqual(0, test.CountBits());
Assert.AreEqual(64, test.CountLeadingZeros());
Assert.AreEqual(64, test.CountTrailingZeros());
test.SetBits(63, true);
Assert.AreEqual(1, test.CountBits());
Assert.AreEqual(0, test.CountLeadingZeros());
Assert.AreEqual(63, test.CountTrailingZeros());
test.SetBits(0, true);
Assert.AreEqual(2, test.CountBits());
Assert.AreEqual(0, test.CountLeadingZeros());
Assert.AreEqual(0, test.CountTrailingZeros());
test.SetBits(63, false);
Assert.AreEqual(1, test.CountBits());
Assert.AreEqual(63, test.CountLeadingZeros());
Assert.AreEqual(0, test.CountTrailingZeros());
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e4ba623f239d54340a5b682234f32027
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,105 @@
using NUnit.Framework;
using Unity.Burst;
using Unity.Jobs.LowLevel.Unsafe;
namespace Unity.Collections.Tests
{
// If ENABLE_UNITY_COLLECTIONS_CHECKS is not defined we will ignore the test
// When using this attribute, consider it to logically AND with any other TestRequiresxxxx attribute
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal class TestRequiresCollectionChecks : System.Attribute
{
public TestRequiresCollectionChecks(string msg = null) { }
}
#else
internal class TestRequiresCollectionChecks : IgnoreAttribute
{
public TestRequiresCollectionChecks(string msg = null) : base($"Test requires ENABLE_UNITY_COLLECTION_CHECKS which is not defined{(msg == null ? "." : $": {msg}")}") { }
}
#endif
// If ENABLE_UNITY_COLLECTIONS_CHECKS and UNITY_DOTS_DEBUG is not defined we will ignore the test
// conversely if either of them are defined the test will be run.
// When using this attribute, consider it to logically AND with any other TestRequiresxxxx attribute
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
internal class TestRequiresDotsDebugOrCollectionChecks : System.Attribute
{
public TestRequiresDotsDebugOrCollectionChecks(string msg = null) { }
}
#else
internal class TestRequiresDotsDebugOrCollectionChecks : IgnoreAttribute
{
public TestRequiresDotsDebugOrCollectionChecks(string msg = null) : base($"Test requires UNITY_DOTS_DEBUG || ENABLE_UNITY_COLLECTION_CHECKS which neither are defined{(msg == null ? "." : $": {msg}")}") { }
}
#endif
internal class CollectionsTestCommonBase
{
AllocatorHelper<RewindableAllocator> rwdAllocatorHelper;
protected AllocatorHelper<RewindableAllocator> CommonRwdAllocatorHelper => rwdAllocatorHelper;
protected ref RewindableAllocator CommonRwdAllocator => ref rwdAllocatorHelper.Allocator;
[SetUp]
public virtual void Setup()
{
}
[OneTimeSetUp]
public void OneTimeSetup()
{
rwdAllocatorHelper = new AllocatorHelper<RewindableAllocator>(Allocator.Persistent);
CommonRwdAllocator.Initialize(128 * 1024, true);
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
CommonRwdAllocator.Dispose();
rwdAllocatorHelper.Dispose();
}
[TearDown]
public virtual void TearDown()
{
CommonRwdAllocator.Rewind();
// This is test only behavior for determinism. Rewind twice such that all
// tests start with an allocator containing only one memory block.
CommonRwdAllocator.Rewind();
}
}
/// <summary>
/// Collections test fixture to do setup and teardown.
/// </summary>
/// <remarks>
/// Jobs debugger and safety checks should always be enabled when running collections tests. This fixture verifies
/// those are enabled to prevent crashing the editor.
/// </remarks>
internal abstract class CollectionsTestFixture : CollectionsTestCommonBase
{
static string SafetyChecksMenu = "Jobs > Burst > Safety Checks";
private bool JobsDebuggerWasEnabled;
[SetUp]
public override void Setup()
{
base.Setup();
// Many ECS tests will only pass if the Jobs Debugger enabled;
// force it enabled for all tests, and restore the original value at teardown.
JobsDebuggerWasEnabled = JobsUtility.JobDebuggerEnabled;
JobsUtility.JobDebuggerEnabled = true;
Assert.IsTrue(BurstCompiler.Options.EnableBurstSafetyChecks, $"Collections tests must have Burst safety checks enabled! To enable, go to {SafetyChecksMenu}");
}
[TearDown]
public override void TearDown()
{
JobsUtility.JobDebuggerEnabled = JobsDebuggerWasEnabled;
base.TearDown();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0de8369d937c43f09392e4cd032cfe19
timeCreated: 1589905000
@@ -0,0 +1,272 @@
using System;
using NUnit.Framework;
using Unity.Burst;
using Unity.Collections;
using Unity.Mathematics;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
internal class ConcurrentMaskTests
{
internal struct Test
{
internal long value;
internal int bits;
internal long expectedModified;
internal int offset;
internal bool expectedWorked;
internal Test(ulong uValue, ulong uExpectedModified, bool w)
{
this = default;
value = (long)uValue;
expectedModified = (long)uExpectedModified;
expectedWorked = w;
}
internal Test(ulong uValue, int bits, ulong uExpectedModified, bool w)
{
this = default;
value = (long)uValue;
this.bits = bits;
expectedModified = (long)uExpectedModified;
expectedWorked = w;
}
internal Test(ulong uValue, ulong uExpectedModified, int offset, bool w)
{
this = default;
value = (long)uValue;
expectedModified = (long)uExpectedModified;
this.offset = offset;
expectedWorked = w;
}
internal Test(ulong uValue, int bits, ulong uExpectedModified, int offset, bool w)
{
value = (long)uValue;
this.bits = bits;
expectedModified = (long)uExpectedModified;
this.offset = offset;
expectedWorked = w;
}
}
[Test]
public void AllocatesOneBitFromLong()
{
foreach(var test in new Test[] {
new Test(0x0000000000000000UL,0x0000000000000001UL, true),
new Test(0x0000000000000001UL,0x0000000000000003UL, true),
new Test(0x00000000000000FFUL,0x00000000000001FFUL, true),
new Test(0x0000000000000100UL,0x0000000000000101UL, true),
new Test(0x7FFFFFFFFFFFFFFFUL,0xFFFFFFFFFFFFFFFFUL, true),
new Test(0x8000000000000000UL,0x8000000000000001UL, true),
}) {
long value = test.value;
long expectedModified = test.expectedModified;
long modified = value;
var worked = ConcurrentMask.TryAllocate(ref modified, out int _, 1);
Assert.AreEqual(expectedModified, modified);
Assert.AreEqual(test.expectedWorked, ConcurrentMask.Succeeded(worked));
}
}
[Test]
public void FailsToAllocateOneBitFromLong()
{
foreach(var test in new Test[] {
new Test(0xFFFFFFFFFFFFFFFFUL,0xFFFFFFFFFFFFFFFFUL, false)
}) {
long value = test.value;
long expectedModified = test.expectedModified;
long modified = value;
var worked = ConcurrentMask.TryAllocate(ref modified, out int _, 1);
Assert.AreEqual(expectedModified, modified);
Assert.AreEqual(test.expectedWorked, ConcurrentMask.Succeeded(worked));
}
}
[Test]
public void AllocatesMultipleBitsFromLong()
{
foreach(var test in new Test[] {
new Test(0x0000000000000000UL, 64,0xFFFFFFFFFFFFFFFFUL, true),
new Test(0x0000000000000000UL, 2,0x0000000000000003UL, true),
new Test(0x0000000000000001UL,63,0xFFFFFFFFFFFFFFFFUL, true),
new Test(0x00000000000000FFUL,8, 0x000000000000FFFFUL, true),
new Test(0x00000000000FF0FFUL,8, 0x000000000FFFF0FFUL, true),
}) {
long value = test.value;
long expectedModified = test.expectedModified;
long modified = value;
var worked = ConcurrentMask.TryAllocate(ref modified, out int _, test.bits);
Assert.AreEqual(expectedModified, modified);
Assert.AreEqual(test.expectedWorked, ConcurrentMask.Succeeded(worked));
}
}
[Test]
public void FailsToAllocateMultipleBitsFromLong()
{
foreach(var test in new Test[] {
new Test(0x0000000000000000UL, 65,0x0000000000000000UL, false),
new Test(0x0000000000000001UL,64,0x0000000000000001UL, false),
new Test(0xFF000000000000FFUL,49, 0xFF000000000000FFUL, false),
}) {
long value = test.value;
long expectedModified = test.expectedModified;
long modified = value;
var worked = ConcurrentMask.TryAllocate(ref modified, out int _, test.bits);
Assert.AreEqual(expectedModified, modified);
Assert.AreEqual(test.expectedWorked, ConcurrentMask.Succeeded(worked));
}
}
[Test]
public void FreesOneBitFromLong()
{
foreach(var test in new Test[] {
new Test(0x0000000000000000UL,0x0000000000000001UL, 0, true),
new Test(0x0000000000000001UL,0x0000000000000003UL, 1, true),
new Test(0x00000000000000FFUL,0x00000000000001FFUL, 8, true),
new Test(0x0000000000000100UL,0x0000000000000101UL, 0, true),
new Test(0x7FFFFFFFFFFFFFFFUL,0xFFFFFFFFFFFFFFFFUL, 63, true),
new Test(0x8000000000000000UL,0x8000000000000001UL, 0, true),
}) {
long expectedModified = (long)test.value;
long modified = (long)test.expectedModified;
var worked = ConcurrentMask.TryFree(ref modified, test.offset, 1);
Assert.AreEqual(expectedModified, modified);
Assert.AreEqual(test.expectedWorked, ConcurrentMask.Succeeded(worked));
}
}
[Test]
public void FreesMultipleBitsFromLong()
{
foreach(var test in new Test[] {
new Test(0x0000000000000000UL, 64,0xFFFFFFFFFFFFFFFFUL, 0, true),
new Test(0x0000000000000000UL, 2,0x0000000000000003UL, 0, true),
new Test(0x0000000000000001UL,63,0xFFFFFFFFFFFFFFFFUL, 1, true),
new Test(0x00000000000000FFUL,8, 0x000000000000FFFFUL, 8, true),
new Test(0x00000000000FF0FFUL,8, 0x000000000FFFF0FFUL, 20, true),
}) {
long expectedModified = test.value;
long modified = test.expectedModified;
var worked = ConcurrentMask.TryFree(ref modified, test.offset, test.bits);
Assert.AreEqual(expectedModified, modified);
Assert.AreEqual(test.expectedWorked, ConcurrentMask.Succeeded(worked));
}
}
[Test]
public void AllocatesOneBitFromArray()
{
var storage = new NativeList<long>(3, Allocator.Persistent);
storage.Length = 3;
for(var i = 0; i < 64; ++i)
{
var worked = ConcurrentMask.TryAllocate(ref storage, out int offset, 1);
Assert.AreEqual(true, ConcurrentMask.Succeeded(worked));
Assert.AreEqual(i, offset);
}
Assert.AreEqual(-1L, storage[0]);
Assert.AreEqual(0L, storage[1]);
Assert.AreEqual(0L, storage[2]);
for(var i = 0; i < 64; ++i)
{
var worked = ConcurrentMask.TryAllocate(ref storage, out int offset, 1);
Assert.AreEqual(true, ConcurrentMask.Succeeded(worked));
Assert.AreEqual(64+i, offset);
}
Assert.AreEqual(-1L, storage[0]);
Assert.AreEqual(-1L, storage[1]);
Assert.AreEqual(0L, storage[2]);
storage.Dispose();
}
[Test]
public void AllocatesMultipleBitsFromArray()
{
var storage = new NativeList<long>(3, Allocator.Persistent);
storage.Length = 3;
for(var i = 0; i < 3; ++i)
{
var worked = ConcurrentMask.TryAllocate(ref storage, out int offset, 33);
Assert.AreEqual(true, ConcurrentMask.Succeeded(worked));
Assert.AreEqual(i * 64, offset);
}
{
var worked = ConcurrentMask.TryAllocate(ref storage, out int offset, 33);
Assert.AreEqual(false, ConcurrentMask.Succeeded(worked));
}
storage.Dispose();
}
[Test]
public void FreesOneBitFromArray()
{
var storage = new NativeList<long>(3, Allocator.Persistent);
storage.Length = 3;
ConcurrentMask.TryAllocate(ref storage, out int _, 64);
ConcurrentMask.TryAllocate(ref storage, out int _, 64);
ConcurrentMask.TryAllocate(ref storage, out int _, 64);
for(var i = 0; i < 64 * 3; ++i)
{
var worked = ConcurrentMask.TryFree(ref storage, i, 1);
Assert.AreEqual(true, ConcurrentMask.Succeeded(worked));
}
Assert.AreEqual(0L, storage[0]);
Assert.AreEqual(0L, storage[1]);
Assert.AreEqual(0L, storage[2]);
storage.Dispose();
}
[Test]
public void FreesMultipleBitsFromArray()
{
var storage = new NativeList<long>(3, Allocator.Persistent);
storage.Length = 3;
ConcurrentMask.TryAllocate(ref storage, out int _, 64);
ConcurrentMask.TryAllocate(ref storage, out int _, 64);
ConcurrentMask.TryAllocate(ref storage, out int _, 64);
for(var i = 0; i < 3; ++i)
{
var worked = ConcurrentMask.TryFree(ref storage, i * 64 + 1, 63);
Assert.AreEqual(true, ConcurrentMask.Succeeded(worked));
}
Assert.AreEqual(1L, storage[0]);
Assert.AreEqual(1L, storage[1]);
Assert.AreEqual(1L, storage[2]);
storage.Dispose();
}
[BurstCompile(CompileSynchronously = true)]
struct AllocateJob : IJobParallelFor
{
[NativeDisableContainerSafetyRestriction] public NativeList<long> m_storage;
public void Execute(int index)
{
ConcurrentMask.TryAllocate(ref m_storage, out int _, 1);
}
}
[Test]
public void AllocatesFromJob()
{
const int kLengthInWords = 10;
const int kLengthInBits = kLengthInWords * 64;
var storage = new NativeList<long>(kLengthInWords, Allocator.Persistent);
storage.Length = kLengthInWords;
for (int i = 0; i < kLengthInWords; ++i)
Assert.AreEqual(0L, storage[i]);
var allocateJob = new AllocateJob();
allocateJob.m_storage = storage;
allocateJob.Schedule(kLengthInBits, 1).Complete();
for (int i = 0; i < kLengthInWords; ++i)
Assert.AreEqual(~0L, storage[i]);
storage.Dispose();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b21a3382971974da1b398c348949244e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,526 @@
using System;
using AOT;
using NUnit.Framework;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Jobs.LowLevel.Unsafe;
using Unity.Collections.Tests;
internal class CustomAllocatorTests : CollectionsTestCommonBase
{
[TestCase(1337, 1337)]
[TestCase(0xFFFF, 0x0000)]
[TestCase(0x0000, 0xFFFF)]
[TestCase(0xFFFF, 0xFFFF)]
[TestCase(0x0000, 0x0000)]
public void AllocatorHandleToAllocatorRoundTripWorks(int i, int v)
{
var Index = (ushort)i;
var Version = (ushort)v;
AllocatorManager.AllocatorHandle srcHandle = new AllocatorManager.AllocatorHandle{ Index = Index, Version = Version };
Allocator srcAllocator = srcHandle.ToAllocator;
AllocatorManager.AllocatorHandle destHandle = AllocatorManager.ConvertToAllocatorHandle(srcAllocator);
Assert.AreEqual(srcHandle.Index, destHandle.Index);
Assert.AreEqual(srcHandle.Version, destHandle.Version);
Allocator destAllocator = destHandle.ToAllocator;
Assert.AreEqual(srcAllocator, destAllocator);
}
[Test]
public void AllocatorVersioningWorks()
{
AllocatorManager.Initialize();
var origin = AllocatorManager.Persistent;
var storage = origin.AllocateBlock(default(byte), 100000); // allocate a block of bytes from Malloc.Persistent
for(var i = 1; i <= 3; ++i)
{
var allocatorHelper = new AllocatorHelper<AllocatorManager.StackAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize(storage);
var oldIndex = allocator.Handle.Index;
var oldVersion = allocator.Handle.Version;
allocator.Dispose();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var newVersion = AllocatorManager.SharedStatics.Version.Ref.Data.ElementAt(oldIndex);
Assert.AreEqual(oldVersion + 1, newVersion);
#endif
allocatorHelper.Dispose();
}
storage.Dispose();
AllocatorManager.Shutdown();
}
[Test]
public void ReleasingChildHandlesWorks()
{
AllocatorManager.Initialize();
var origin = AllocatorManager.Persistent;
var storage = origin.AllocateBlock(default(byte), 100000); // allocate a block of bytes from Malloc.Persistent
var allocatorHelper = new AllocatorHelper<AllocatorManager.StackAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize(storage);
var list = NativeList<int>.New(10, ref allocator);
list.Add(0); // put something in the list, so it'll have a size for later
allocator.Dispose(); // ok to tear down the storage that the stack allocator used, too.
#if ENABLE_UNITY_COLLECTIONS_CHECKS
Assert.Throws<ObjectDisposedException>(
() => {
list[0] = 0; // we haven't disposed this list, but it was released automatically already. so this is an error.
});
#endif
storage.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
[Test]
public unsafe void ReleasingChildAllocatorsWorks()
{
AllocatorManager.Initialize();
var origin = AllocatorManager.Persistent;
var parentStorage = origin.AllocateBlock(default(byte), 100000); // allocate a block of bytes from Malloc.Persistent
var parentHelper = new AllocatorHelper<AllocatorManager.StackAllocator>(AllocatorManager.Persistent);
ref var parent = ref parentHelper.Allocator;
parent.Initialize(parentStorage); // and make a stack allocator from it
var childStorage = parent.AllocateBlock(default(byte), 10000); // allocate some space from the parent
var childHelper = new AllocatorHelper<AllocatorManager.StackAllocator>(AllocatorManager.Persistent);
childHelper.Allocator.Initialize(childStorage); // and make a stack allocator from it
parent.Dispose(); // tear down the parent allocator
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<ArgumentException>(() =>
{
childHelper.Allocator.Allocate(default(byte), 1000); // try to allocate from the child - it should fail.
});
#endif
parentStorage.Dispose();
parentHelper.Dispose();
childHelper.Dispose();
AllocatorManager.Shutdown();
}
[Test]
public void AllocatesAndFreesFromMono()
{
AllocatorManager.Initialize();
const int kLength = 100;
var expectedAlignment = math.max(JobsUtility.CacheLineSize, UnsafeUtility.AlignOf<int>());
for (int i = 0; i < kLength; ++i)
{
var allocator = AllocatorManager.Persistent;
var block = allocator.AllocateBlock(default(int), i);
if(i != 0)
Assert.AreNotEqual(IntPtr.Zero, block.Range.Pointer);
Assert.AreEqual(i, block.Range.Items);
Assert.AreEqual(UnsafeUtility.SizeOf<int>(), block.BytesPerItem);
Assert.AreEqual(expectedAlignment, block.Alignment);
Assert.AreEqual(AllocatorManager.Persistent.Value, block.Range.Allocator.Value);
allocator.FreeBlock(ref block);
}
AllocatorManager.Shutdown();
}
[BurstCompile(CompileSynchronously = true)]
struct AllocateJob : IJobParallelFor
{
public NativeArray<AllocatorManager.Block> m_blocks;
public void Execute(int index)
{
var allocator = AllocatorManager.Persistent;
m_blocks[index] = allocator.AllocateBlock(default(int), index);
}
}
[BurstCompile(CompileSynchronously = true)]
struct FreeJob : IJobParallelFor
{
public NativeArray<AllocatorManager.Block> m_blocks;
public void Execute(int index)
{
var temp = m_blocks[index];
temp.Free();
m_blocks[index] = temp;
}
}
[Test]
public void AllocatesAndFreesFromBurst()
{
AllocatorManager.Initialize();
const int kLength = 100;
var blocks = new NativeArray<AllocatorManager.Block>(kLength, Allocator.Persistent);
var allocateJob = new AllocateJob();
allocateJob.m_blocks = blocks;
allocateJob.Schedule(kLength, 1).Complete();
var expectedAlignment = math.max(JobsUtility.CacheLineSize, UnsafeUtility.AlignOf<int>());
for (int i = 0; i < kLength; ++i)
{
var block = allocateJob.m_blocks[i];
if(i != 0)
Assert.AreNotEqual(IntPtr.Zero, block.Range.Pointer);
Assert.AreEqual(i, block.Range.Items);
Assert.AreEqual(UnsafeUtility.SizeOf<int>(), block.BytesPerItem);
Assert.AreEqual(expectedAlignment, block.Alignment);
Assert.AreEqual(AllocatorManager.Persistent.Value, block.Range.Allocator.Value);
}
var freeJob = new FreeJob();
freeJob.m_blocks = blocks;
freeJob.Schedule(kLength, 1).Complete();
for (int i = 0; i < kLength; ++i)
{
var block = allocateJob.m_blocks[i];
Assert.AreEqual(IntPtr.Zero, block.Range.Pointer);
Assert.AreEqual(0, block.Range.Items);
Assert.AreEqual(UnsafeUtility.SizeOf<int>(), block.BytesPerItem);
Assert.AreEqual(expectedAlignment, block.Alignment);
Assert.AreEqual(AllocatorManager.Persistent.Value, block.Range.Allocator.Value);
}
blocks.Dispose();
AllocatorManager.Shutdown();
}
// This allocator wraps UnsafeUtility.Malloc, but also initializes memory to some constant value after allocating.
[BurstCompile(CompileSynchronously = true)]
struct ClearToValueAllocator : AllocatorManager.IAllocator
{
public AllocatorManager.AllocatorHandle Handle { get { return m_handle; } set { m_handle = value; } }
public Allocator ToAllocator { get { return m_handle.ToAllocator; } }
public bool IsCustomAllocator { get { return m_handle.IsCustomAllocator; } }
internal AllocatorManager.AllocatorHandle m_handle;
internal AllocatorManager.AllocatorHandle m_parent;
public byte m_clearValue;
public void Initialize<T>(byte ClearValue, ref T parent) where T : unmanaged, AllocatorManager.IAllocator
{
m_parent = parent.Handle;
m_clearValue = ClearValue;
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
parent.Handle.AddChildAllocator(m_handle);
#endif
}
public unsafe int Try(ref AllocatorManager.Block block)
{
var temp = block.Range.Allocator;
block.Range.Allocator = m_parent;
var error = AllocatorManager.Try(ref block);
block.Range.Allocator = temp;
if (error != 0)
return error;
if (block.Range.Pointer != IntPtr.Zero) // if we allocated or reallocated...
UnsafeUtility.MemSet((void*)block.Range.Pointer, m_clearValue, block.Bytes); // clear to a value.
return 0;
}
[BurstCompile(CompileSynchronously = true)]
[MonoPInvokeCallback(typeof(AllocatorManager.TryFunction))]
public static unsafe int Try(IntPtr state, ref AllocatorManager.Block block)
{
return ((ClearToValueAllocator*)state)->Try(ref block);
}
public AllocatorManager.TryFunction Function => Try;
public void Dispose()
{
m_handle.Dispose();
}
}
[BurstCompile(CompileSynchronously = true)]
internal struct CountingAllocator : AllocatorManager.IAllocator
{
public AllocatorManager.AllocatorHandle Handle { get { return m_handle; } set { m_handle = value; } }
public Allocator ToAllocator { get { return m_handle.ToAllocator; } }
public bool IsCustomAllocator { get { return m_handle.IsCustomAllocator; } }
public AllocatorManager.AllocatorHandle m_handle;
public int AllocationCount;
public long Used;
public bool WasUsed => AllocationCount > 0;
public bool IsUsed => Used > 0;
public void Initialize()
{
AllocationCount = 0;
Used = 0;
#if ENABLE_UNITY_ALLOCATIONS_CHECKS
AllocatorManager.Persistent.Handle.AddChildAllocator(m_handle);
#endif
}
public int Try(ref AllocatorManager.Block block)
{
if (block.Range.Pointer != IntPtr.Zero)
{
Used -= block.AllocatedBytes;
}
var temp = block.Range.Allocator;
block.Range.Allocator = AllocatorManager.Persistent;
var error = AllocatorManager.Try(ref block);
block.Range.Allocator = temp;
if (error != 0)
return error;
if (block.Range.Pointer != IntPtr.Zero) // if we allocated or reallocated...
{
++AllocationCount;
Used += block.AllocatedBytes;
}
return 0;
}
[BurstCompile(CompileSynchronously = true)]
[MonoPInvokeCallback(typeof(AllocatorManager.TryFunction))]
public static unsafe int Try(IntPtr state, ref AllocatorManager.Block block)
{
return ((CountingAllocator*)state)->Try(ref block);
}
public AllocatorManager.TryFunction Function => Try;
public void Dispose()
{
m_handle.Dispose();
}
}
[Test]
public void UserDefinedAllocatorWorks()
{
AllocatorManager.Initialize();
var parent = AllocatorManager.Persistent;
var allocatorHelper = new AllocatorHelper<ClearToValueAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize(0, ref parent);
var expectedAlignment = math.max(JobsUtility.CacheLineSize, UnsafeUtility.AlignOf<int>());
for (byte ClearValue = 0; ClearValue < 0xF; ++ClearValue)
{
allocator.m_clearValue = ClearValue;
const int kLength = 100;
for (int i = 1; i < kLength; ++i)
{
var block = allocator.AllocateBlock(default(int), i);
Assert.AreNotEqual(IntPtr.Zero, block.Range.Pointer);
Assert.AreEqual(i, block.Range.Items);
Assert.AreEqual(UnsafeUtility.SizeOf<int>(), block.BytesPerItem);
Assert.AreEqual(expectedAlignment, block.Alignment);
allocator.FreeBlock(ref block);
}
}
allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
// this is testing for the case where we want+ to install a stack allocator that itself allocates from a big hunk
// of memory provided by the default Persistent allocator, and then make allocations on the stack allocator.
[Test]
public void StackAllocatorWorks()
{
AllocatorManager.Initialize();
var origin = AllocatorManager.Persistent;
var backingStorage = origin.AllocateBlock(default(byte), 100000); // allocate a block of bytes from Malloc.Persistent
var allocatorHelper = new AllocatorHelper<AllocatorManager.StackAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize(backingStorage);
var expectedAlignment = math.max(JobsUtility.CacheLineSize, UnsafeUtility.AlignOf<int>());
const int kLength = 100;
for (int i = 1; i < kLength; ++i)
{
var block = allocator.AllocateBlock(default(int), i);
Assert.AreNotEqual(IntPtr.Zero, block.Range.Pointer);
Assert.AreEqual(i, block.Range.Items);
Assert.AreEqual(UnsafeUtility.SizeOf<int>(), block.BytesPerItem);
Assert.AreEqual(expectedAlignment, block.Alignment);
allocator.FreeBlock(ref block);
}
allocator.Dispose();
backingStorage.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
[Test]
public void CustomAllocatorNativeListWorksWithoutHandles()
{
AllocatorManager.Initialize();
var allocator = AllocatorManager.Persistent;
var list = NativeList<byte>.New(100, ref allocator);
list.Dispose(ref allocator);
AllocatorManager.Shutdown();
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public void CustomAllocatorNativeListThrowsWhenAllocatorIsWrong()
{
AllocatorManager.Initialize();
var allocator0 = AllocatorManager.Persistent;
var list = NativeList<byte>.New(100, ref allocator0);
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
list.Dispose(ref CommonRwdAllocatorHelper.Allocator);
});
list.Dispose(ref allocator0);
AllocatorManager.Shutdown();
}
// this is testing for the case where we want to install a custom allocator that clears memory to a constant
// byte value, and then have an UnsafeList use that custom allocator.
[Test]
public void CustomAllocatorUnsafeListWorks()
{
AllocatorManager.Initialize();
var parent = AllocatorManager.Persistent;
var allocatorHelper = new AllocatorHelper<ClearToValueAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize(0xFE, ref parent);
for (byte ClearValue = 0; ClearValue < 0xF; ++ClearValue)
{
allocator.m_clearValue = ClearValue;
var unsafelist = new UnsafeList<byte>(1, allocator.Handle);
const int kLength = 100;
unsafelist.Resize(kLength);
for (int i = 0; i < kLength; ++i)
Assert.AreEqual(ClearValue, unsafelist[i]);
unsafelist.Dispose();
}
allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
[Test]
public unsafe void SlabAllocatorWorks()
{
var SlabSizeInBytes = 256;
var SlabSizeInInts = SlabSizeInBytes / sizeof(int);
var Slabs = 256;
AllocatorManager.Initialize();
var origin = AllocatorManager.Persistent;
var backingStorage = origin.AllocateBlock(default(byte), Slabs * SlabSizeInBytes); // allocate a block of bytes from Malloc.Persistent
var allocatorHelper = new AllocatorHelper<AllocatorManager.SlabAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize(backingStorage, SlabSizeInBytes, Slabs * SlabSizeInBytes);
var expectedAlignment = math.max(JobsUtility.CacheLineSize, UnsafeUtility.AlignOf<int>());
var block0 = allocator.AllocateBlock(default(int), SlabSizeInInts);
Assert.AreNotEqual(IntPtr.Zero, block0.Range.Pointer);
Assert.AreEqual(SlabSizeInInts, block0.Range.Items);
Assert.AreEqual(UnsafeUtility.SizeOf<int>(), block0.BytesPerItem);
Assert.AreEqual(expectedAlignment, block0.Alignment);
Assert.AreEqual(1, allocator.Occupied[0]);
var block1 = allocator.AllocateBlock(default(int), SlabSizeInInts - 1);
Assert.AreNotEqual(IntPtr.Zero, block1.Range.Pointer);
Assert.AreEqual(SlabSizeInInts - 1, block1.Range.Items);
Assert.AreEqual(UnsafeUtility.SizeOf<int>(), block1.BytesPerItem);
Assert.AreEqual(expectedAlignment, block1.Alignment);
Assert.AreEqual(3, allocator.Occupied[0]);
allocator.FreeBlock(ref block0);
Assert.AreEqual(2, allocator.Occupied[0]);
allocator.FreeBlock(ref block1);
Assert.AreEqual(0, allocator.Occupied[0]);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<ArgumentException>(() =>
{
allocatorHelper.Allocator.AllocateBlock(default(int), 65);
});
#endif
allocator.Dispose();
backingStorage.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
[Test]
public unsafe void CollectionHelper_IsAligned()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<ArgumentException>(() => CollectionHelper.IsAligned((void*)0x0, 0)); // value is 0
Assert.Throws<ArgumentException>(() => CollectionHelper.IsAligned((void*)0x1000, 0)); // alignment is 0
Assert.Throws<ArgumentException>(() => CollectionHelper.IsAligned((void*)0x1000, 3)); // alignment is not pow2
#endif
for (var i = 0; i < 31; ++i)
{
Assert.IsTrue(CollectionHelper.IsAligned((void*)0x80000000, 1<<i));
}
}
[Test]
public void AllocatorManager_AllocateBlock_UsesAlignmentArgument()
{
int sizeOf = 1;
int alignOf = 4096;
int items = 1;
var temp = AllocatorManager.Temp;
var block = temp.AllocateBlock(sizeOf, alignOf, items);
Assert.AreNotEqual(IntPtr.Zero, block.Range.Pointer);
unsafe
{
Assert.IsTrue(CollectionHelper.IsAligned((void*)block.Range.Pointer, alignOf));
}
}
[Test]
public void AllocatorManager_AllocateBlock_AlwaysCacheLineAligned()
{
int sizeOf = 1;
int items = 1;
var temp = AllocatorManager.Temp;
for (int alignment = 1; alignment < 256; ++alignment)
{
var block = temp.AllocateBlock(sizeOf, alignment, items);
Assert.AreNotEqual(IntPtr.Zero, block.Range.Pointer);
unsafe
{
Assert.IsTrue(CollectionHelper.IsAligned((void*)block.Range.Pointer, CollectionHelper.CacheLineSize));
}
}
}
[Test]
public void AllocatorManager_Block_DoesNotOverflow()
{
AllocatorManager.Block block = default;
block.BytesPerItem = int.MaxValue;
block.AllocatedItems = 2;
block.Range = new AllocatorManager.Range { Items = 2 };
long ExpectedAllocatedBytes = (long)block.BytesPerItem * (long)block.AllocatedItems;
long ExpectedBytes = (long)block.BytesPerItem * (long)block.Range.Items;
Assert.AreEqual(ExpectedAllocatedBytes, block.AllocatedBytes);
Assert.AreEqual(ExpectedBytes, block.Bytes);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: dca80967668c4d89a4dae5bd097484ef
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,167 @@
// Example code used in trunk, unity/Documentation/ApiDocs/Unity.Collections.LowLevel.Unsafe/NativeContainerAttribute.mem.xml
using System.Diagnostics;
using System;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Collections;
using Unity.Burst;
// Marks our struct as a NativeContainer.
// If ENABLE_UNITY_COLLECTIONS_CHECKS is enabled,
// it is required that m_Safety with exactly this name.
[NativeContainer]
// The [NativeContainerSupportsMinMaxWriteRestriction] enables
// a common jobification pattern where an IJobParallelFor is split into ranges
// And the job is only allowed to access the index range being Executed by that worker thread.
// Effectively limiting access of the array to the specific index passed into the Execute(int index) method
// This attribute requires m_MinIndex & m_MaxIndex to exist.
// and the container is expected to perform out of bounds checks against it.
// m_MinIndex & m_MaxIndex will be set by the job scheduler before Execute is called on the worker thread.
[NativeContainerSupportsMinMaxWriteRestriction]
// It is recommended to always implement a Debugger proxy
// to visualize the contents of the array in VisualStudio and other tools.
[DebuggerDisplay("Length = {Length}")]
[DebuggerTypeProxy(typeof(NativeCustomArrayDebugView<>))]
internal unsafe struct NativeCustomArray<T> : IDisposable where T : unmanaged
{
internal void* m_Buffer;
internal int m_Length;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal int m_MinIndex;
internal int m_MaxIndex;
internal AtomicSafetyHandle m_Safety;
internal static readonly SharedStatic<int> s_staticSafetyId = SharedStatic<int>.GetOrCreate<NativeCustomArray<T>>();
#endif
internal Allocator m_AllocatorLabel;
public NativeCustomArray(int length, Allocator allocator)
{
int totalSize = sizeof(T) * length;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
// Native allocation is only valid for Temp, TempJob, Persistent or registered custom allocator
if (allocator <= Allocator.None)
throw new ArgumentException("Allocator must be Temp, TempJob, Persistent or registered custom allcoator", "allocator");
if (length < 0)
throw new ArgumentOutOfRangeException("length", "Length must be >= 0");
if (!UnsafeUtility.IsBlittable<T>())
throw new ArgumentException(string.Format("{0} used in NativeCustomArray<{0}> must be blittable", typeof(T)));
#endif
m_Buffer = AllocatorManager.Allocate(allocator, totalSize, UnsafeUtility.AlignOf<T>());
UnsafeUtility.MemClear(m_Buffer, totalSize);
m_Length = length;
m_AllocatorLabel = allocator;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
m_MinIndex = 0;
m_MaxIndex = length - 1;
m_Safety = CollectionHelper.CreateSafetyHandle(allocator);
CollectionHelper.SetStaticSafetyId<NativeCustomArray<T>>(ref m_Safety, ref s_staticSafetyId.Data);
#endif
}
public int Length { get { return m_Length; } }
public unsafe T this[int index]
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
// If the container is currently not allowed to read from the buffer
// then this will throw an exception.
// This handles all cases, from already disposed containers
// to safe multithreaded access.
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
// Perform out of range checks based on
// the NativeContainerSupportsMinMaxWriteRestriction policy
if (index < m_MinIndex || index > m_MaxIndex)
FailOutOfRangeError(index);
#endif
// Read the element from the allocated native memory
return UnsafeUtility.ReadArrayElement<T>(m_Buffer, index);
}
set
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
// If the container is currently not allowed to write to the buffer
// then this will throw an exception.
// This handles all cases, from already disposed containers
// to safe multithreaded access.
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
// Perform out of range checks based on
// the NativeContainerSupportsMinMaxWriteRestriction policy
if (index < m_MinIndex || index > m_MaxIndex)
FailOutOfRangeError(index);
#endif
// Writes value to the allocated native memory
UnsafeUtility.WriteArrayElement(m_Buffer, index, value);
}
}
public T[] ToArray()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
var array = new T[Length];
for (var i = 0; i < Length; i++)
array[i] = UnsafeUtility.ReadArrayElement<T>(m_Buffer, i);
return array;
}
public bool IsCreated
{
get { return m_Buffer != null; }
}
public void Dispose()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
CollectionHelper.DisposeSafetyHandle(ref m_Safety);
#endif
AllocatorManager.Free(m_AllocatorLabel, m_Buffer);
m_Buffer = null;
m_Length = 0;
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
private void FailOutOfRangeError(int index)
{
if (index < Length && (m_MinIndex != 0 || m_MaxIndex != Length - 1))
throw new IndexOutOfRangeException(string.Format(
"Index {0} is out of restricted IJobParallelFor range [{1}...{2}] in ReadWriteBuffer.\n" +
"ReadWriteBuffers are restricted to only read & write the element at the job index. " +
"You can use double buffering strategies to avoid race conditions due to " +
"reading & writing in parallel to the same elements from a job.",
index, m_MinIndex, m_MaxIndex));
throw new IndexOutOfRangeException(string.Format("Index {0} is out of range of '{1}' Length.", index, Length));
}
#endif
}
// Visualizes the custom array in the C# debugger
internal sealed class NativeCustomArrayDebugView<T> where T : unmanaged
{
private NativeCustomArray<T> m_Array;
public NativeCustomArrayDebugView(NativeCustomArray<T> array)
{
m_Array = array;
}
public T[] Items
{
get { return m_Array.ToArray(); }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7d464d1935bb3084cbed9d87692699cf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,837 @@
using System;
using NUnit.Framework;
using Unity.Collections.NotBurstCompatible;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using UnityEngine.TestTools;
using UnityEngine;
namespace Unity.Collections.Tests
{
internal class DataStreamTests
{
internal class ReadAndWrite
{
[TestCase(ushort.MaxValue)]
[TestCase(ushort.MinValue)]
public void UShort(ushort expected)
{
bool Write(ref DataStreamWriter writer) => writer.WriteUShort(expected);
CheckReadWrite(sizeof(ushort), reader => reader.ReadUShort(), Write, expected);
}
[TestCase((uint) 0b101010)]
[TestCase((uint) 0b111111)]
public void RawBits(uint expected)
{
bool Write(ref DataStreamWriter writer) => writer.WriteRawBits(expected, 6);
CheckReadWrite(6, reader => reader.ReadRawBits(6), Write, expected);
}
[Test]
public void RawBits_OutOfCapacity()
{
const uint expected = 0b101011001;
var writer = new DataStreamWriter(1, Allocator.Temp);
Assert.False(writer.WriteRawBits(expected, 9));
Assert.True(writer.HasFailedWrites);
}
[TestCase(uint.MaxValue)]
[TestCase(uint.MinValue)]
public void UInt(uint expected)
{
bool Write(ref DataStreamWriter writer) => writer.WriteUInt(expected);
CheckReadWrite(sizeof(uint), reader => reader.ReadUInt(), Write, expected);
}
[TestCase(float.MaxValue)]
[TestCase(float.MinValue)]
public void Float(float expected)
{
bool Write(ref DataStreamWriter writer) => writer.WriteFloat(expected);
CheckReadWrite(sizeof(float), reader => reader.ReadFloat(), Write, expected);
}
[TestCase(short.MaxValue)]
[TestCase(short.MinValue)]
public void Short(short expected)
{
bool Write(ref DataStreamWriter writer) => writer.WriteShort(expected);
CheckReadWrite(sizeof(short), reader => reader.ReadShort(), Write, expected);
}
[Test]
public void FixedString32()
{
var expected = new FixedString32Bytes("This is a string");
bool Write(ref DataStreamWriter writer) => writer.WriteFixedString32(expected);
CheckReadWrite(expected.Length + FixedStringHeader, reader => reader.ReadFixedString32(), Write, expected);
}
[Test]
public void FixedString64()
{
var expected = new FixedString64Bytes("This is a string");
bool Write(ref DataStreamWriter writer) => writer.WriteFixedString64(expected);
CheckReadWrite(expected.Length + FixedStringHeader, reader => reader.ReadFixedString64(), Write, expected);
}
[Test]
public void FixedString128()
{
var expected = new FixedString128Bytes("This is a string");
bool Write(ref DataStreamWriter writer) => writer.WriteFixedString128(expected);
CheckReadWrite(expected.Length + FixedStringHeader, reader => reader.ReadFixedString128(), Write, expected);
}
[Test]
public void FixedString512()
{
var expected = new FixedString512Bytes("This is a string");
bool Write(ref DataStreamWriter writer) => writer.WriteFixedString512(expected);
CheckReadWrite(expected.Length + FixedStringHeader, reader => reader.ReadFixedString512(), Write, expected);
}
[Test]
public void FixedString4096()
{
var expected = new FixedString4096Bytes("This is a string");
bool Write(ref DataStreamWriter writer) => writer.WriteFixedString4096(expected);
CheckReadWrite(expected.Length + FixedStringHeader, reader => reader.ReadFixedString4096(), Write,
expected);
}
[Test]
public void LongLooped()
{
const long baseVal = -99;
const long expected = -1979;
bool Write(ref DataStreamWriter writer, long value) => writer.WriteLong(value);
long Read(ref DataStreamReader reader) => reader.ReadLong();
CheckReadWriteLooped(sizeof(long), baseVal, expected, Write, Read, (l, u) => l + u);
}
}
internal class ReadAndWriteNetworkOrder
{
[TestCase(int.MaxValue)]
[TestCase(int.MinValue)]
public void Int(int expected)
{
bool Write(ref DataStreamWriter writer) => writer.WriteIntNetworkByteOrder(expected);
CheckReadWrite(sizeof(int), reader => reader.ReadIntNetworkByteOrder(), Write, expected);
}
[TestCase(uint.MaxValue)]
[TestCase(uint.MinValue)]
public void UInt(uint expected)
{
bool Write(ref DataStreamWriter writer) => writer.WriteUIntNetworkByteOrder(expected);
CheckReadWrite(sizeof(uint), reader => reader.ReadUIntNetworkByteOrder(), Write, expected);
}
[TestCase(short.MaxValue)]
[TestCase(short.MinValue)]
public void Short(short expected)
{
bool Write(ref DataStreamWriter writer) => writer.WriteShortNetworkByteOrder(expected);
CheckReadWrite(sizeof(short), reader => reader.ReadShortNetworkByteOrder(), Write, expected);
}
[TestCase(ushort.MaxValue)]
[TestCase(ushort.MinValue)]
public void UShort(ushort expected)
{
bool Write(ref DataStreamWriter writer) => writer.WriteUShortNetworkByteOrder(expected);
CheckReadWrite(sizeof(ushort), reader => reader.ReadUShortNetworkByteOrder(), Write, expected);
}
[Test]
public void ReadIncorrect()
{
var dataStream = new DataStreamWriter(4, Allocator.Temp);
dataStream.WriteIntNetworkByteOrder(1979);
dataStream.Flush();
var reader = new DataStreamReader(dataStream.AsNativeArray());
Assert.AreNotEqual(1979, reader.ReadInt());
}
}
internal class ReadWritePacked
{
[Test]
public void UInt()
{
const uint expected = 1979;
const uint baseVal = 2000;
bool Write(ref DataStreamWriter writer) => writer.WriteUInt(expected);
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model, uint value) => writer.WritePackedUInt(value, model);
uint Read(ref DataStreamReader reader) => reader.ReadUInt();
uint ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedUInt(model);
CheckReadWritePackedLooped(sizeof(uint), baseVal, expected, Write, WritePacked, Read, ReadPacked, (l, u) => l + u);
}
[Test]
public void IntExistingData()
{
unsafe
{
var n = 300 * 4;
var data = stackalloc byte[n];
var compressionModel = StreamCompressionModel.Default;
var dataStream = new DataStreamWriter(data, n);
const int base_val = -10;
const int count = 20;
for (int i = 0; i < count; ++i)
dataStream.WritePackedInt(base_val + i, compressionModel);
dataStream.WriteInt((int)1979);
dataStream.Flush();
var na = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(data, n, Allocator.Invalid);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref na, AtomicSafetyHandle.GetTempMemoryHandle());
#endif
var reader = new DataStreamReader(na);
for (int i = 0; i < count; ++i)
{
var val = reader.ReadPackedInt(compressionModel);
Assert.AreEqual(base_val + i, val);
}
Assert.AreEqual(1979, reader.ReadInt());
}
}
[Test]
[UnityPlatform(exclude = new[] { RuntimePlatform.Android })] // Re-enable and fix https://jira.unity3d.com/browse/UUM-138845
public void Int()
{
const int expected = -1979;
const int baseVal = -10;
bool Write(ref DataStreamWriter writer) => writer.WriteInt(expected);
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model, int value) => writer.WritePackedInt(value, model);
int Read(ref DataStreamReader reader) => reader.ReadInt();
int ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedInt(model);
CheckReadWritePackedLooped(sizeof(int), baseVal, expected, Write, WritePacked, Read, ReadPacked, (i, u) => (int)(i + u));
}
[Test]
[UnityPlatform(exclude = new[] { RuntimePlatform.Android })] // Re-enable and fix https://jira.unity3d.com/browse/UUM-138845
public void Long()
{
const long expected = -1979;
const long baseVal = -99;
bool Write(ref DataStreamWriter writer) => writer.WriteLong(expected);
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model, long value) => writer.WritePackedLong(value, model);
long Read(ref DataStreamReader reader) => reader.ReadLong();
long ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedLong(model);
CheckReadWritePackedLooped(sizeof(long), baseVal, expected, Write, WritePacked, Read, ReadPacked, (l, u) => l + u);
}
[Test]
[UnityPlatform(exclude = new[] { RuntimePlatform.Android })] // Re-enable and fix https://jira.unity3d.com/browse/UUM-138845
public void ULong()
{
const ulong expected = 1979;
const ulong baseVal = 2000;
bool Write(ref DataStreamWriter writer) => writer.WriteULong(expected);
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model, ulong value) => writer.WritePackedULong(value, model);
ulong Read(ref DataStreamReader reader) => reader.ReadULong();
ulong ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedULong(model);
CheckReadWritePackedLooped(sizeof(ulong), baseVal, expected, Write, WritePacked, Read, ReadPacked, (l, u) => l + u);
}
[Test]
public void Float()
{
const float expected = 1979.1f;
const float baseVal = 2000.1f;
bool Write(ref DataStreamWriter writer) => writer.WriteFloat(expected);
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model, float value) => writer.WritePackedFloat(value, model);
float Read(ref DataStreamReader reader) => reader.ReadFloat();
float ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedFloat(model);
CheckReadWritePackedLooped(sizeof(float), baseVal, expected, Write, WritePacked, Read, ReadPacked, (l, u) => l + u);
}
[Test]
public void Double()
{
const double expected = 1979.1989;
const double baseVal = 2000.2000;
bool Write(ref DataStreamWriter writer) => writer.WriteDouble(expected);
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model, double value) => writer.WritePackedDouble(value, model);
double Read(ref DataStreamReader reader) => reader.ReadDouble();
double ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedDouble(model);
CheckReadWritePackedLooped(sizeof(double), baseVal, expected, Write, WritePacked, Read, ReadPacked, (l, u) => l + u);
}
[Test]
public void WriteOutSideOfCapacity_Fails()
{
var model = StreamCompressionModel.Default;
var writer = new DataStreamWriter(sizeof(uint) / 2, Allocator.Temp);
Assert.False(writer.HasFailedWrites);
Assert.False(writer.WritePackedUInt(uint.MaxValue, model), "Writing a uint where there is no room should fail.");
Assert.That(writer.HasFailedWrites);
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public void ReadOutSideOfCapacity_Fails()
{
var model = StreamCompressionModel.Default;
var reader = new DataStreamReader(new NativeArray<byte>(0, Allocator.Temp));
LogAssert.Expect(LogType.Error, "Trying to read 2 bits from a stream where only 0 are available");
Assert.That(reader.ReadPackedUInt(model), Is.EqualTo(0));
Assert.That(reader.HasFailedReads);
}
}
internal class ReadWritePackedDelta
{
[Test]
public void Int()
{
const int expected = int.MaxValue;
const int baseline = int.MinValue;
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model) => writer.WritePackedIntDelta(expected, baseline, model);
int ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedIntDelta(baseline, model);
CheckReadWritePacked(sizeof(int), ReadPacked, WritePacked, expected);
}
[Test]
[UnityPlatform(exclude = new[] { RuntimePlatform.Android })] // Re-enable and fix https://jira.unity3d.com/browse/UUM-138845
public void Long()
{
const long expected = long.MaxValue;
const long baseline = long.MinValue;
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model) => writer.WritePackedLongDelta(expected, baseline, model);
long ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedLongDelta(baseline, model);
CheckReadWritePacked(sizeof(long), ReadPacked, WritePacked, expected);
}
[Test]
[UnityPlatform(exclude = new[] { RuntimePlatform.Android })] // Re-enable and fix https://jira.unity3d.com/browse/UUM-138845
public void ULong()
{
const ulong expected = ulong.MaxValue;
const ulong baseline = ulong.MinValue;
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model) => writer.WritePackedULongDelta(expected, baseline, model);
ulong ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedULongDelta(baseline, model);
CheckReadWritePacked(sizeof(ulong), ReadPacked, WritePacked, expected);
}
[Test]
public void FixedString32()
{
var expected = new FixedString32Bytes("This is a string");
var baseline = new FixedString32Bytes("This is another string");
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model) => writer.WritePackedFixedString32Delta(expected, baseline, model);
FixedString32Bytes ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedFixedString32Delta(baseline, model);
CheckReadWritePacked(expected.Length + FixedStringHeader, ReadPacked, WritePacked, expected);
}
[Test]
public void FixedString32_LargerBaseline()
{
var expected = new FixedString32Bytes("This is another string");
var baseline = new FixedString32Bytes("This is a string");
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model) => writer.WritePackedFixedString32Delta(expected, baseline, model);
FixedString32Bytes ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedFixedString32Delta(baseline, model);
CheckReadWritePacked(expected.Length + FixedStringHeader, ReadPacked, WritePacked, expected);
}
[Test]
public void FixedString64()
{
var expected = new FixedString64Bytes("This is a string");
var baseline = new FixedString64Bytes("This is another string");
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model) => writer.WritePackedFixedString64Delta(expected, baseline, model);
FixedString64Bytes ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedFixedString64Delta(baseline, model);
CheckReadWritePacked(expected.Length + FixedStringHeader, ReadPacked, WritePacked, expected);
}
[Test]
public void FixedString128()
{
var expected = new FixedString128Bytes("This is a string");
var baseline = new FixedString128Bytes("This is another string");
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model) => writer.WritePackedFixedString128Delta(expected, baseline, model);
FixedString128Bytes ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedFixedString128Delta(baseline, model);
CheckReadWritePacked(expected.Length + FixedStringHeader, ReadPacked, WritePacked, expected);
}
[Test]
public void FixedString512()
{
var expected = new FixedString512Bytes("This is a string");
var baseline = new FixedString512Bytes("This is another string");
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model) => writer.WritePackedFixedString512Delta(expected, baseline, model);
FixedString512Bytes ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedFixedString512Delta(baseline, model);
CheckReadWritePacked(expected.Length + FixedStringHeader, ReadPacked, WritePacked, expected);
}
[Test]
public void FixedString4096()
{
var expected = new FixedString4096Bytes("This is a string");
var baseline = new FixedString4096Bytes("This is another string");
bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model) => writer.WritePackedFixedString4096Delta(expected, baseline, model);
FixedString4096Bytes ReadPacked(ref DataStreamReader reader, StreamCompressionModel model) => reader.ReadPackedFixedString4096Delta(baseline, model);
CheckReadWritePacked(expected.Length + FixedStringHeader, ReadPacked, WritePacked, expected);
}
[Test]
public void Float_OutOfBoundsFails()
{
const float expected = float.MaxValue;
const float baseline = float.MinValue;
var model = StreamCompressionModel.Default;
var writer = new DataStreamWriter(sizeof(float) / 2, Allocator.Temp);
Assert.False(writer.HasFailedWrites);
Assert.False(writer.WritePackedFloatDelta(expected, baseline, model));
Assert.That(writer.HasFailedWrites);
}
[Test]
public void Float_UnchangedData()
{
const float expected = float.MaxValue;
const float baseline = float.MaxValue;
var model = StreamCompressionModel.Default;
var writer = new DataStreamWriter(1, Allocator.Temp);
Assert.True(writer.WritePackedFloatDelta(expected, baseline, model));
var reader = new DataStreamReader(writer.AsNativeArray());
Assert.AreEqual(baseline, reader.ReadPackedFloatDelta(baseline, model));
Assert.That(reader.GetBitsRead(), Is.EqualTo(1));
}
[Test]
public void Float_ChangedData()
{
const float expected = float.MaxValue;
const float baseline = float.MinValue;
var model = StreamCompressionModel.Default;
var writer = new DataStreamWriter(sizeof(float) + 1, Allocator.Temp);
Assert.True(writer.WritePackedFloatDelta(expected, baseline, model));
var reader = new DataStreamReader(writer.AsNativeArray());
Assert.AreEqual(1, reader.ReadRawBits(1));
var uf = new UIntFloat
{
intValue = reader.ReadRawBits(32)
};
Assert.AreEqual(expected, uf.floatValue);
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public void UInt_OutOfCapacity()
{
var model = StreamCompressionModel.Default;
var writer = new DataStreamWriter(0, Allocator.Temp);
var reader = new DataStreamReader(writer.AsNativeArray());
LogAssert.Expect(LogType.Error, "Trying to read 2 bits from a stream where only 0 are available");
Assert.That(reader.ReadPackedUInt(model), Is.EqualTo(0));
Assert.That(reader.HasFailedReads);
}
// We test with a variable amount of writes to ensure we overflow the internal ulong bitBuffer.
[Test]
public void Flush_Works([Values(1, 7, 24, 65)]int numWrites)
{
const int baseline = 100;
var model = StreamCompressionModel.Default;
var writer = new DataStreamWriter(512, Allocator.Temp);
// Writer:
for(int i = 0; i < numWrites; i++)
writer.WritePackedUIntDelta((uint) (100 + i), baseline, model);
// Flush, and write another sentinel value in.
writer.Flush();
writer.WritePackedUIntDelta(45, baseline, model);
writer.Flush();
Assert.IsFalse(writer.HasFailedWrites, "Sanity: writer.HasFailedWrites");
// Reader:
var reader = new DataStreamReader(writer.AsNativeArray());
for(int i = 0; i < numWrites; i++)
{
var read = reader.ReadPackedUIntDelta(baseline, model);
Assert.AreEqual((uint)(100 + i), read, "100 + i");
}
// When we flush the reader, we expect to now be aligned.
reader.Flush();
var read45 = reader.ReadPackedUIntDelta(baseline, model);
Assert.AreEqual(45, read45, "45");
reader.Flush();
Assert.IsFalse(reader.HasFailedReads, "reader.HasFailedReads");
Assert.AreEqual(writer.LengthInBits, reader.GetBitsRead(), "writer.LengthInBits vs reader.GetBitsRead()");
LogAssert.NoUnexpectedReceived();
}
[Test]
public void NotMirroringFlushCall_Fails()
{
const int baseline = 100;
var model = StreamCompressionModel.Default;
var writer = new DataStreamWriter(512, Allocator.Temp);
// Writer:
writer.WritePackedUIntDelta(100, baseline, model);
Assert.AreNotEqual(0, writer.LengthInBits % 8, "Sanity: Not byte aligned!");
writer.Flush();
writer.WritePackedUIntDelta(45, baseline, model);
writer.Flush();
Assert.IsFalse(writer.HasFailedWrites, "Sanity: writer.HasFailedWrites");
// Reader:
var reader = new DataStreamReader(writer.AsNativeArray());
var read = reader.ReadPackedUIntDelta(baseline, model);
Assert.AreEqual(100u, read, "100u");
// SKIPPED: reader.Flush();
// THUS: Read pointer alignment should be wrong.
LogAssert.ignoreFailingMessages = true; // Defensive: Technically we're reading too FEW bits,
// so we shouldn't get error logs here.
Assert.AreNotEqual(45, reader.ReadPackedIntDelta(baseline, model), "!45");
Assert.AreNotEqual(writer.LengthInBits, reader.GetBitsRead(), "writer.LengthInBits vs reader.GetBitsRead()");
}
[Test]
public void CanMixPackedAndNonPacked()
{
const int baseline = 200;
var model = StreamCompressionModel.Default;
var writer = new DataStreamWriter(12, Allocator.Temp);
writer.WritePackedIntDelta(201, baseline, model);
Assert.AreNotEqual(0, writer.LengthInBits % 8, "Sanity: This test is invalid if we accidentally byte-align.");
writer.WriteInt(202);
writer.WritePackedInt(203, model);
writer.WriteInt(204);
Assert.IsFalse(writer.HasFailedWrites, "Sanity: writer.HasFailedWrites");
var reader = new DataStreamReader(writer.AsNativeArray());
Assert.AreEqual(201, reader.ReadPackedIntDelta(baseline, model));
Assert.AreEqual(202, reader.ReadInt());
Assert.AreEqual(203, reader.ReadPackedInt(model));
Assert.AreEqual(204, reader.ReadInt());
Assert.IsFalse(reader.HasFailedReads, "reader.HasFailedReads");
}
}
[Test]
public void IsCreated_ReturnsTrueAfterConstructor()
{
var dataStream = new DataStreamWriter(4, Allocator.Temp);
Assert.True(dataStream.IsCreated, "Buffer must be created after calling constructor.");
}
[Test]
public void LengthInBits_MatchesWrittenCount()
{
var dataStream = new DataStreamWriter(4, Allocator.Temp);
dataStream.WriteByte(0);
Assert.That(dataStream.LengthInBits, Is.EqualTo(1 * 8));
dataStream.WriteByte(1);
dataStream.WriteByte(1);
Assert.That(dataStream.LengthInBits, Is.EqualTo(3 * 8));
}
[Test]
public void CreateStreamWithPartOfSourceByteArray()
{
byte[] byteArray =
{
(byte)'s', (byte)'o', (byte)'m', (byte)'e',
(byte)' ', (byte)'d', (byte)'a', (byte)'t', (byte)'a'
};
DataStreamWriter dataStream;
dataStream = new DataStreamWriter(4, Allocator.Temp);
dataStream.WriteBytes(new NativeArray<byte>(byteArray, Allocator.Temp).GetSubArray(0, 4));
Assert.AreEqual(dataStream.Length, 4);
var reader = new DataStreamReader(dataStream.AsNativeArray());
for (int i = 0; i < dataStream.Length; ++i)
{
Assert.AreEqual(byteArray[i], reader.ReadByte());
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
LogAssert.Expect(LogType.Error, "Trying to read 1 bytes from a stream where only 0 are available");
Assert.AreEqual(0, reader.ReadByte());
#endif
}
[Test]
public void CreateStreamWithSourceByteArray()
{
byte[] byteArray = new byte[100];
byteArray[0] = (byte)'a';
byteArray[1] = (byte)'b';
byteArray[2] = (byte)'c';
DataStreamWriter dataStream1, dataStream2;
dataStream1 = new DataStreamWriter(byteArray.Length, Allocator.Temp);
dataStream2 = new DataStreamWriter(byteArray.Length, Allocator.Temp);
dataStream1.WriteBytes(new NativeArray<byte>(byteArray, Allocator.Temp));
dataStream2.WriteBytes(byteArray);
var arr1 = dataStream1.AsNativeArray();
var arr2 = dataStream2.AsNativeArray();
var reader1 = new DataStreamReader(arr1);
var reader2 = new DataStreamReader(arr2);
for (var i = 0; i < byteArray.Length; ++i)
{
Assert.AreEqual(byteArray[i], reader1.ReadByte());
Assert.AreEqual(byteArray[i], reader2.ReadByte());
}
}
[Test]
public void ReadIntoExistingNativeByteArray()
{
var byteArray = new NativeArray<byte>(100, Allocator.Temp);
DataStreamWriter dataStream;
dataStream = new DataStreamWriter(3, Allocator.Temp);
{
dataStream.WriteByte((byte)'a');
dataStream.WriteByte((byte)'b');
dataStream.WriteByte((byte)'c');
var reader = new DataStreamReader(dataStream.AsNativeArray());
reader.ReadBytes(byteArray.GetSubArray(0, dataStream.Length));
reader = new DataStreamReader(dataStream.AsNativeArray());
for (int i = 0; i < reader.Length; ++i)
{
Assert.AreEqual(byteArray[i], reader.ReadByte());
}
}
}
[Test]
public void ReadIntoExistingByteArray()
{
var byteArray = new byte[3];
DataStreamWriter dataStream;
dataStream = new DataStreamWriter(3, Allocator.Temp);
{
dataStream.WriteByte((byte)'a');
dataStream.WriteByte((byte)'b');
dataStream.WriteByte((byte)'c');
var reader = new DataStreamReader(dataStream.AsNativeArray());
reader.ReadBytes(byteArray);
reader = new DataStreamReader(dataStream.AsNativeArray());
for (int i = 0; i < reader.Length; ++i)
{
Assert.AreEqual(byteArray[i], reader.ReadByte());
}
}
}
[Test]
public void ReadingDataFromStreamWithSliceOffset()
{
var dataStream = new DataStreamWriter(100, Allocator.Temp);
dataStream.WriteByte((byte)'a');
dataStream.WriteByte((byte)'b');
dataStream.WriteByte((byte)'c');
dataStream.WriteByte((byte)'d');
dataStream.WriteByte((byte)'e');
dataStream.WriteByte((byte)'f');
var reader = new DataStreamReader(dataStream.AsNativeArray().GetSubArray(3, 3));
Assert.AreEqual('d', reader.ReadByte());
Assert.AreEqual('e', reader.ReadByte());
Assert.AreEqual('f', reader.ReadByte());
}
[Test]
public void GetStreamReaderUnsafePtr()
{
var a = new NativeArray<byte>(1, Allocator.Temp);
a[0] = (byte)42;
var reader = new DataStreamReader(a);
unsafe
{
var ptr = (byte*)reader.GetUnsafeReadOnlyPtr();
Assert.AreEqual((byte)42, *ptr);
}
}
[Test]
public void WriteOutOfBounds()
{
var dataStream = new DataStreamWriter(9, Allocator.Temp);
Assert.IsTrue(dataStream.WriteInt(42));
Assert.AreEqual(4, dataStream.Length);
Assert.IsTrue(dataStream.WriteInt(42));
Assert.AreEqual(8, dataStream.Length);
Assert.IsFalse(dataStream.HasFailedWrites);
Assert.IsFalse(dataStream.WriteInt(42));
Assert.AreEqual(8, dataStream.Length);
Assert.IsTrue(dataStream.HasFailedWrites);
Assert.IsFalse(dataStream.WriteShort(42));
Assert.AreEqual(8, dataStream.Length);
Assert.IsTrue(dataStream.HasFailedWrites);
Assert.IsTrue(dataStream.WriteByte(42));
Assert.AreEqual(9, dataStream.Length);
Assert.IsTrue(dataStream.HasFailedWrites);
Assert.IsFalse(dataStream.WriteByte(42));
Assert.AreEqual(9, dataStream.Length);
Assert.IsTrue(dataStream.HasFailedWrites);
}
[Test]
public void ReadWritePackedUIntWithDeferred()
{
var compressionModel = StreamCompressionModel.Default;
var dataStream = new DataStreamWriter(300 * 4, Allocator.Temp);
uint base_val = 2000;
uint count = 277;
var def = dataStream;
dataStream.WriteInt((int)0);
for (uint i = 0; i < count; ++i)
dataStream.WritePackedUInt(base_val + i, compressionModel);
dataStream.Flush();
def.WriteInt(1979);
def = dataStream;
dataStream.WriteInt((int)0);
def.WriteInt(1979);
dataStream.Flush();
var reader = new DataStreamReader(dataStream.AsNativeArray());
Assert.AreEqual(1979, reader.ReadInt());
for (uint i = 0; i < count; ++i)
{
var val = reader.ReadPackedUInt(compressionModel);
Assert.AreEqual(base_val + i, val);
}
Assert.AreEqual(1979, reader.ReadInt());
}
[Test]
public void PassDataStreamReaderToJob()
{
using (var returnValue = new NativeArray<int>(1, Allocator.TempJob))
{
var writer = new DataStreamWriter(sizeof(int), Allocator.Temp);
writer.WriteInt(42);
var reader = new DataStreamReader(writer.AsNativeArray());
new ReaderTestJob
{
Reader = reader,
ReturnValue = returnValue
}.Run();
Assert.AreEqual(42, returnValue[0]);
}
}
private struct ReaderTestJob : IJob
{
public DataStreamReader Reader;
public NativeArray<int> ReturnValue;
public void Execute()
{
ReturnValue[0] = Reader.ReadInt();
}
}
delegate T Read<out T>(ref DataStreamReader reader);
delegate T ReadPacked<out T>(ref DataStreamReader reader, StreamCompressionModel model);
delegate bool Write(ref DataStreamWriter writer);
delegate T Sum<T>(T x, uint y);
delegate bool WriteWithValue<in T>(ref DataStreamWriter writer, T value);
delegate bool WritePacked(ref DataStreamWriter writer, StreamCompressionModel model);
delegate bool WritePackedWithValue<in T>(ref DataStreamWriter writer, StreamCompressionModel model, T value);
const int FixedStringHeader = 2;
static void CheckReadWritePackedLooped<T>(int size, T baseVal, T expected,
Write write, WritePackedWithValue<T> writePackedWithValue,
Read<T> read, ReadPacked<T> readPacked, Sum<T> sum)
{
var compressionModel = StreamCompressionModel.Default;
var dataStream = new DataStreamWriter(300 * size, Allocator.Temp);
const int count = 277;
for (uint i = 0; i < count; ++i)
{
T res = sum(baseVal, i);
writePackedWithValue(ref dataStream, compressionModel, res);
}
write(ref dataStream);
dataStream.Flush();
var reader = new DataStreamReader(dataStream.AsNativeArray());
for (uint i = 0; i < count; ++i)
{
var val = readPacked(ref reader, compressionModel);
Assert.AreEqual(sum(baseVal, i), val);
}
Assert.AreEqual(expected, read(ref reader));
}
static void CheckReadWritePacked<T>(int size, ReadPacked<T> read, WritePacked write, T value)
{
var model = StreamCompressionModel.Default;
var writer = new DataStreamWriter(size, Allocator.Temp);
write(ref writer, model);
writer.Flush();
var reader = new DataStreamReader(writer.AsNativeArray());
Assert.That(read(ref reader, model), Is.EqualTo(value));
}
static void CheckReadWrite<T>(int size, Func<DataStreamReader, T> read, Write write, T value)
{
var writer = new DataStreamWriter(size, Allocator.Temp);
write(ref writer);
writer.Flush();
Assert.That(read(new DataStreamReader(writer.AsNativeArray())), Is.EqualTo(value));
}
static void CheckReadWriteLooped<T>(int size, T baseVal, T expected, WriteWithValue<T> write, Read<T> read, Sum<T> sum)
{
var writer = new DataStreamWriter(300 * size, Allocator.Temp);
const int count = 277;
for (uint i = 0; i < count; ++i)
{
write(ref writer, sum(baseVal, i));
}
write(ref writer, expected);
writer.Flush();
var reader = new DataStreamReader(writer.AsNativeArray());
for (uint i = 0; i < count; ++i)
{
var val = read(ref reader);
Assert.AreEqual(sum(baseVal, i), val);
}
Assert.AreEqual(expected, read(ref reader));
}
[Test]
public void MiNiCheck()
{
var model = StreamCompressionModel.Default;
Assert.That(model.ToString(), Is.EqualTo("Unity.Collections.StreamCompressionModel"));
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c9fa73c3f49c43bc8f21fedf53591b10
timeCreated: 1643881980
@@ -0,0 +1,38 @@
using System;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace Unity.Collections.Tests
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
internal class EmbeddedPackageOnlyTestAttribute : NUnitAttribute, IApplyToTest
{
public void ApplyToTest(Test test)
{
#if UNITY_EDITOR
var assembly = test.Method?.TypeInfo?.Assembly ?? test.TypeInfo?.Assembly;
if (assembly == null)
{
UnityEngine.Debug.LogError($"The {nameof(EmbeddedPackageOnlyTestAttribute)} attribute can only be applied to tests in an assembly.");
return;
}
var package = UnityEditor.PackageManager.PackageInfo.FindForAssembly(assembly);
if (package == null)
{
UnityEngine.Debug.LogError(
$"The {nameof(EmbeddedPackageOnlyTestAttribute)} attribute can only be applied to tests in a package.");
return;
}
if (package.source == UnityEditor.PackageManager.PackageSource.Embedded ||
package.source == UnityEditor.PackageManager.PackageSource.Local)
return;
#endif
test.RunState = RunState.Ignored;
test.Properties.Add(PropertyNames.SkipReason, "Only runs in the editor when this package is embedded or referenced locally.");
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4668a20175cc94ab284013b3a4ce4a9e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,207 @@
using System;
using System.Runtime.CompilerServices;
using NUnit.Framework;
/// <summary>
/// This class mirrors parts of the Assert API from NUnit in a sane way.
/// The problem with NUnit is that stuff like Assert.AreEqual(15, 16) creates allocations behind the scenes, so tests
/// that checks large collections will spend the vast majority of their time just checking their results.
/// You can use this by writing
/// using Assert = FastAssert;
/// at the top of your file. There are some parts of the API that you may need to fix up manually, mainly because this
/// class does not expose overloads like Assert.AreEqual(object a, object b) because that's just asking for pain.
/// </summary>
internal static class FastAssert
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsTrue(bool b)
{
if (!b)
{
Assert.IsTrue(b);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsTrue(bool b, string msg)
{
if (!b)
{
Assert.IsTrue(b, msg);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void True(bool b)
{
if (!b)
{
Assert.IsTrue(b);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void True(bool b, string msg)
{
if (!b)
{
Assert.IsTrue(b, msg);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsFalse(bool b)
{
if (b)
{
Assert.IsFalse(b);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void IsFalse(bool b, string msg)
{
if (b)
{
Assert.IsFalse(b, msg);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void False(bool b)
{
if (b)
{
Assert.IsFalse(b);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void False(bool b, string msg)
{
if (b)
{
Assert.IsFalse(b, msg);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual<T>(in T a, in T b) where T : IEquatable<T>
{
if (!a.Equals(b))
{
Assert.Fail($"{a} != {b}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreEqual<T>(in T a, in T b, string msg) where T : IEquatable<T>
{
if (!a.Equals(b))
{
Assert.Fail($"{a} != {b}: {msg}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreNotEqual<T>(in T a, in T b) where T : IEquatable<T>
{
if (a.Equals(b))
{
Assert.Fail($"{a} == {b}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AreNotEqual<T>(in T a, in T b, string msg) where T : IEquatable<T>
{
if (a.Equals(b))
{
Assert.Fail($"{a} == {b}: {msg}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void LessOrEqual<T>(in T a, in T b) where T : IComparable<T>
{
if (a.CompareTo(b) > 0)
{
Assert.Fail($"{a} > {b}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void LessOrEqual<T>(in T a, in T b, string msg) where T : IComparable<T>
{
if (a.CompareTo(b) > 0)
{
Assert.Fail($"{a} > {b}: {msg}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Less<T>(in T a, in T b) where T : IComparable<T>
{
if (a.CompareTo(b) >= 0)
{
Assert.Fail($"{a} >= {b}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Less<T>(in T a, in T b, string msg) where T : IComparable<T>
{
if (a.CompareTo(b) >= 0)
{
Assert.Fail($"{a} >= {b}: {msg}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void GreaterOrEqual<T>(in T a, in T b) where T : IComparable<T>
{
if (a.CompareTo(b) < 0)
{
Assert.Fail($"{a} < {b}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void GreaterOrEqual<T>(in T a, in T b, string msg) where T : IComparable<T>
{
if (a.CompareTo(b) < 0)
{
Assert.Fail($"{a} < {b}: {msg}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Greater<T>(in T a, in T b) where T : IComparable<T>
{
if (a.CompareTo(b) <= 0)
{
Assert.Fail($"{a} <= {b}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Greater<T>(in T a, in T b, string msg) where T : IComparable<T>
{
if (a.CompareTo(b) <= 0)
{
Assert.Fail($"{a} <= {b}: {msg}");
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DoesNotThrow(TestDelegate del)
{
Assert.DoesNotThrow(del);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Throws<T>(TestDelegate del) where T : Exception
{
Assert.Throws<T>(del);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 46bf253b4ab641ca9ead38f10efc8d17
timeCreated: 1623678741
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a3e73147e051c3f448aa8c6a4e07c55b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,725 @@
<#/*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.Globalization" #>
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// t4 Samples/Packages/com.unity.collections/Unity.Collections.Tests/FixedListTests.tt
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Collections.Tests;
using UnityEngine;
internal class FixedListTests : CollectionsTestFixture
{
struct NonComparableStruct
{
public int a;
}
struct DescendingComparer<T> : IComparer<T> where T : IComparable<T>
{
public int Compare(T x, T y) => y.CompareTo(x);
}
<#
{
var SIZES = new int[] {32, 64, 128};
for (var size = 0; size < 3; ++size)
{
var BYTES = SIZES[size];
var TYPENAME = String.Format("FixedList{0}Bytes", BYTES);
#>
[Test]
public void <#=TYPENAME #>DebugView()
{
var list = new <#=TYPENAME #><NonComparableStruct>();
CollectionAssert.IsEmpty(new <#=TYPENAME #>DebugView<NonComparableStruct>(list).Items);
var reference = new []
{
new NonComparableStruct{ a = 123 },
new NonComparableStruct{ a = 234 },
new NonComparableStruct{ a = 345 },
};
list.Add(reference[0]);
list.Add(reference[1]);
list.Add(reference[2]);
CollectionAssert.AreEqual(reference, new <#=TYPENAME #>DebugView<NonComparableStruct>(list).Items);
}
<#
}
}
{
var TYPES = new string[] {"byte", "int", "float"};
var TYPESIZES = new int[] {1, 4, 4};
var SIZES = new int[] {32, 64, 128};
for (var type = 0; type < 3; ++type)
{
for (var size = 0; size < 3; ++size)
{
var BYTES = SIZES[size];
var TYPE = TYPES[type];
var TYPESIZE = TYPESIZES[type];
var MAXLENGTH = BYTES - 2;
var TYPENAME = String.Format("FixedList{0}Bytes", BYTES);
var TYPENAME_IDENTIFIER = String.Format("FixedList{0}{1}_", BYTES, new CultureInfo("en-US").TextInfo.ToTitleCase(TYPE));
var EXPECTEDCAPACITY = (BYTES - 2) / TYPESIZE;
var BUFFERTYPE = String.Format("FixedBytes{0}Align8", BYTES);
#>
public readonly unsafe struct <#=TYPENAME_IDENTIFIER #>Wrapper
{
readonly <#=TYPENAME #><<#=TYPE #>> _values;
internal <#=TYPE #>* Values => (<#=TYPE #>*)_values.Buffer;
public <#=TYPENAME_IDENTIFIER #>Wrapper(<#=TYPE #> x, <#=TYPE #> y)
{
_values = new <#=TYPENAME #><<#=TYPE #>>();
_values.Add(x);
_values.Add(y);
_values.Sort();
}
}
unsafe void <#=TYPENAME_IDENTIFIER #>ReadonlyWorksFunc1(in <#=TYPENAME_IDENTIFIER #>Wrapper list, <#=TYPE #>* originalValues)
{
<#=TYPE #>* values = list.Values;
Assert.AreEqual(originalValues[0], values[0], "Values[0] mismatch in func1");
Assert.AreEqual(originalValues[1], values[1], "Values[1] mismatch in func1");
Assert.AreEqual((ulong)originalValues, (ulong)values, "Buffer pointer mismatch in func1");
}
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #>ReadonlyWorks()
{
var list = new <#=TYPENAME_IDENTIFIER #>Wrapper(17, 23);
<#=TYPE #>* values = list.Values;
<#=TYPENAME_IDENTIFIER #>ReadonlyWorksFunc1(list, values);
}
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #><#=BUFFERTYPE#>IsAlignedGeneric()
{
var list = new FixedList<<#=TYPE#>, <#=BUFFERTYPE#>>();
Assert.IsTrue((((ulong)list.Buffer) & (sizeof(<#=TYPE#>) - 1)) == 0);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #><#=BUFFERTYPE#>ToNativeArrayWorksGeneric()
{
var list = new FixedList<<#=TYPE#>, <#=BUFFERTYPE#>>();
for (var i = 0; i < <#=EXPECTEDCAPACITY#>; ++i)
list.Add((<#=TYPE#>)(i * 123 + 234));
using (var array = list.ToNativeArray(Allocator.Temp))
{
for (var i = 0; i < <#=EXPECTEDCAPACITY#>; ++i)
Assert.AreEqual((<#=TYPE#>)(i * 123 + 234), array[i]);
}
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>ToNativeArrayWorks()
{
var list = new <#=TYPENAME #><<#=TYPE#>>();
for (var i = 0; i < <#=EXPECTEDCAPACITY#>; ++i)
list.Add((<#=TYPE#>)(i * 123 + 234));
using (var array = list.ToNativeArray(Allocator.Temp))
{
for (var i = 0; i < <#=EXPECTEDCAPACITY#>; ++i)
Assert.AreEqual((<#=TYPE#>)(i * 123 + 234), array[i]);
}
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericHasExpectedLayout()
{
var actual = new <#=TYPENAME #><<#=TYPE#>>();
for (var i = 0; i < <#=EXPECTEDCAPACITY #>; ++i)
actual.Add((<#=TYPE #>)i);
unsafe
{
var e = stackalloc byte[<#=BYTES #>];
e[0] = (byte)((<#=EXPECTEDCAPACITY #> >> 0) & 0xFF);
e[1] = (byte)((<#=EXPECTEDCAPACITY #> >> 8) & 0xFF);
for (var i = 0; i < <#=EXPECTEDCAPACITY #>; ++i)
{
var s = (<#=TYPE #>)i;
UnsafeUtility.MemCpy(e + 2 + FixedList.PaddingBytes<<#=TYPE#>>() + sizeof(<#=TYPE #>) * i, &s, sizeof(<#=TYPE #>));
}
Assert.AreEqual(0, UnsafeUtility.MemCmp(e, &actual.data, <#=BYTES #>));
}
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public void <#=TYPENAME_IDENTIFIER #>GenericHasExpectedCapacity()
{
var list = new <#=TYPENAME #><<#=TYPE#>>();
var expectedCapacity = list.Capacity;
for (int i = 0; i < expectedCapacity; ++i)
list.Add((<#=TYPE #>)i);
Assert.Throws<IndexOutOfRangeException>(() => { list.Add((<#=TYPE #>)expectedCapacity); });
}
<#
if (EXPECTEDCAPACITY >= 5)
{
#>
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #>GenericAdd()
{
var list = new <#=TYPENAME #><<#=TYPE#>>();
var capacity = list.Capacity;
for (var i = 0; i < capacity; ++i)
{
list.Add((<#=TYPE#>)i);
Assert.AreEqual(i + 1, list.Length);
Assert.AreEqual(i, list[i]);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<IndexOutOfRangeException>(() => { list.Add(0); });
#endif
Assert.AreEqual(capacity, list.Length); // Verify length didn't change
}
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #>GenericAddRange()
{
var list = new <#=TYPENAME #><<#=TYPE#>>();
var capacity = list.Capacity;
var items = stackalloc <#=TYPE#>[capacity];
for (var i = 0; i < capacity; ++i)
items[i] = (<#=TYPE#>)i;
var half = capacity / 2;
list.AddRange(items, half);
Assert.AreEqual(half, list.Length);
for (var i = 0; i < half; ++i)
Assert.AreEqual(i, list[i]);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<IndexOutOfRangeException>(() => { list.AddRange(items, capacity); });
#endif
Assert.AreEqual(half, list.Length); // Verify length didn't change
}
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #>GenericAddNoResize()
{
var list = new <#=TYPENAME #><<#=TYPE#>>();
var capacity = list.Capacity;
for (var i = 0; i < capacity; ++i)
{
list.AddNoResize((<#=TYPE#>)i);
Assert.AreEqual(i + 1, list.Length);
Assert.AreEqual(i, list[i]);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<IndexOutOfRangeException>(() => { list.AddNoResize(0); });
#endif
Assert.AreEqual(capacity, list.Length); // Verify length didn't change
}
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #>GenericAddRangeNoResize()
{
var list = new <#=TYPENAME #><<#=TYPE#>>();
var capacity = list.Capacity;
var items = stackalloc <#=TYPE#>[capacity];
for (var i = 0; i < capacity; ++i)
items[i] = (<#=TYPE#>)i;
var half = capacity / 2;
list.AddRangeNoResize(items, half);
Assert.AreEqual(half, list.Length);
list.Clear();
list.AddRangeNoResize(new ReadOnlySpan<<#=TYPE#>>(items, half));
Assert.AreEqual(half, list.Length);
for (var i = 0; i < half; ++i)
Assert.AreEqual(i, list[i]);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<IndexOutOfRangeException>(() => { list.AddRangeNoResize(items, capacity); });
Assert.Throws<IndexOutOfRangeException>(() => { list.AddRangeNoResize(new ReadOnlySpan<<#=TYPE#>>(items, capacity)); });
#endif
Assert.AreEqual(half, list.Length); // Verify length didn't change
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericAddReplicate()
{
var list = new <#=TYPENAME #><<#=TYPE#>>();
list.AddReplicate(42, 2);
Assert.AreEqual(2, list.Length);
foreach (var item in list)
Assert.AreEqual(42, item);
list.AddReplicate(42, 3);
Assert.AreEqual(5, list.Length);
foreach (var item in list)
Assert.AreEqual(42, item);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<IndexOutOfRangeException>(() => { list.AddReplicate(42, 1000); });
#endif
Assert.AreEqual(5, list.Length); // Verify length didn't change
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericInsertRangeWithBeginEnd()
{
var list = new <#=TYPENAME #><<#=TYPE#>>() { 0, 3, 4 };
list.InsertRangeWithBeginEnd(1, 3);
list[1] = 1;
list[2] = 2;
for (var i = 0; i < 5; ++i)
Assert.AreEqual(i, list[i]);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericInsertRange()
{
var list = new <#=TYPENAME #><<#=TYPE#>>() { 0, 3, 4 };
Assert.AreEqual(3, list.Length);
list.InsertRange(1, 2);
Assert.AreEqual(5, list.Length);
list[1] = 1;
list[2] = 2;
Assert.DoesNotThrow(() => list.InsertRange(1, 0));
Assert.AreEqual(5, list.Length);
for (var i = 0; i < 5; ++i)
Assert.AreEqual(i, list[i]);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericRemoveRange()
{
var list = new <#=TYPENAME #><<#=TYPE#>>() { 0, 3, 3, 1, 2 };
list.RemoveRange(1, 2);
for (var i = 0; i < 3; ++i)
Assert.AreEqual(i, list[i]);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericInsert()
{
var list = new <#=TYPENAME #><<#=TYPE#>>() { 0, 3, 4 };
list.Insert(1, 1);
list.Insert(2, 2);
for (var i = 0; i < 5; ++i)
Assert.AreEqual(i, list[i]);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericRemoveAt()
{
var list = new <#=TYPENAME #><<#=TYPE#>>() { 0, 3, 3, 1, 2 };
list.RemoveAt(1);
list.RemoveAt(1);
for (var i = 0; i < 3; ++i)
Assert.AreEqual(i, list[i]);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericRemove()
{
var list = new <#=TYPENAME #><<#=TYPE#>>() { 0, 3, 3, 1, 2 };
Assert.True(list.Remove((<#=TYPE#>)3));
Assert.True(list.Remove((<#=TYPE#>)3));
for (var i = 0; i < 3; ++i)
Assert.AreEqual(i, list[i]);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericRemoveSwapBack()
{
var list = new <#=TYPENAME #><<#=TYPE#>>() { 0, 3, 3, 2, 1 };
Assert.True(list.RemoveSwapBack((<#=TYPE#>)3));
Assert.True(list.RemoveSwapBack((<#=TYPE#>)3));
for (var i = 0; i < 3; ++i)
Assert.AreEqual(i, list[i]);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericSort()
{
var list = new <#=TYPENAME #><<#=TYPE#>>();
for (var i = 0; i < 5; ++i)
list.Add((<#=TYPE #>)(4-i));
list.Sort();
for (var i = 0; i < 5; ++i)
Assert.AreEqual(i, list[i]);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>GenericSortCustomComparer()
{
var list = new <#=TYPENAME #><<#=TYPE#>>();
for (var i = 0; i < 5; ++i)
list.Add((<#=TYPE #>)(i));
list.Sort(new DescendingComparer<<#=TYPE#>>());
for (var i = 0; i < 5; ++i)
Assert.AreEqual(4-i, list[i]);
}
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #>IndexOf()
{
var list = new <#=TYPENAME #><<#=TYPE#>>() { 123, 178 };
bool r0 = false, r1 = false, r2 = false;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
r0 = -1 != list.IndexOf((<#=TYPE#>)145);
r1 = list.Contains((<#=TYPE#>)123);
r2 = list.Contains((<#=TYPE#>)178);
});
Assert.False(r0);
Assert.True(r1);
Assert.True(r2);
}
<#
}
}
for (var size = 0; size < 3; ++size)
{
var BYTES = SIZES[size];
var TYPE = TYPES[type];
var TYPESIZE = TYPESIZES[type];
var MAXLENGTH = BYTES - 2;
var TYPENAME = String.Format("FixedList{0}Bytes<{1}>", BYTES, TYPE);
var TYPENAME_IDENTIFIER = String.Format("FixedList{0}{1}_", BYTES, new CultureInfo("en-US").TextInfo.ToTitleCase(TYPE));
var EXPECTEDCAPACITY = (BYTES - 2) / TYPESIZE;
#>
[Test]
public void <#=TYPENAME_IDENTIFIER #>HasExpectedLayout()
{
var actual = new <#=TYPENAME #>();
for (var i = 0; i < <#=EXPECTEDCAPACITY #>; ++i)
actual.Add((<#=TYPE #>)i);
unsafe
{
var e = stackalloc byte[<#=BYTES #>];
e[0] = (byte)((<#=EXPECTEDCAPACITY #> >> 0) & 0xFF);
e[1] = (byte)((<#=EXPECTEDCAPACITY #> >> 8) & 0xFF);
for (var i = 0; i < <#=EXPECTEDCAPACITY #>; ++i)
{
var s = (<#=TYPE #>)i;
UnsafeUtility.MemCpy(e + 2 + FixedList.PaddingBytes<<#=TYPE#>>() + sizeof(<#=TYPE #>) * i, &s, sizeof(<#=TYPE #>));
}
Assert.AreEqual(0, UnsafeUtility.MemCmp(e, &actual.data, <#=BYTES #>));
}
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public void <#=TYPENAME_IDENTIFIER #>HasExpectedCapacity()
{
var list = new <#=TYPENAME #>();
var expectedCapacity = list.Capacity;
for (int i = 0; i < expectedCapacity; ++i)
list.Add((<#=TYPE #>)i);
Assert.Throws<IndexOutOfRangeException>(() => { list.Add((<#=TYPE #>)expectedCapacity); });
}
class ScriptableObject<#=TYPENAME_IDENTIFIER#> : UnityEngine.ScriptableObject
{
public <#=TYPENAME#> List;
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>Serializes()
{
var a = UnityEngine.ScriptableObject.CreateInstance<ScriptableObject<#=TYPENAME_IDENTIFIER#>>();
for (int i = 0; i < a.List.Capacity; ++i)
a.List.Add((<#=TYPE #>)i);
var b = UnityEngine.Object.Instantiate(a);
CollectionAssert.AreEqual(a.List, b.List);
}
<#
if (EXPECTEDCAPACITY >= 5)
{
#>
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #>Add()
{
var list = new <#=TYPENAME #>();
var capacity = list.Capacity;
for (var i = 0; i < capacity; ++i)
{
list.Add((<#=TYPE#>)i);
Assert.AreEqual(i + 1, list.Length);
Assert.AreEqual(i, list[i]);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<IndexOutOfRangeException>(() => { list.Add(0); });
#endif
Assert.AreEqual(capacity, list.Length); // Verify length didn't change
}
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #>AddRange()
{
var list = new <#=TYPENAME #>();
var capacity = list.Capacity;
var items = stackalloc <#=TYPE#>[capacity];
for (var i = 0; i < capacity; ++i)
items[i] = (<#=TYPE#>)i;
var half = capacity / 2;
list.AddRange(items, half);
Assert.AreEqual(half, list.Length);
for (var i = 0; i < half; ++i)
Assert.AreEqual(i, list[i]);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<IndexOutOfRangeException>(() => { list.AddRange(items, capacity); });
#endif
Assert.AreEqual(half, list.Length); // Verify length didn't change
}
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #>AddNoResize()
{
var list = new <#=TYPENAME #>();
var capacity = list.Capacity;
for (var i = 0; i < capacity; ++i)
{
list.AddNoResize((<#=TYPE#>)i);
Assert.AreEqual(i + 1, list.Length);
Assert.AreEqual(i, list[i]);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<IndexOutOfRangeException>(() => { list.AddNoResize(0); });
#endif
Assert.AreEqual(capacity, list.Length); // Verify length didn't change
}
[Test]
public unsafe void <#=TYPENAME_IDENTIFIER #>AddRangeNoResize()
{
var list = new <#=TYPENAME #>();
var capacity = list.Capacity;
var items = stackalloc <#=TYPE#>[capacity];
for (var i = 0; i < capacity; ++i)
items[i] = (<#=TYPE#>)i;
var half = capacity / 2;
list.AddRangeNoResize(items, half);
Assert.AreEqual(half, list.Length);
for (var i = 0; i < half; ++i)
Assert.AreEqual(i, list[i]);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<IndexOutOfRangeException>(() => { list.AddRangeNoResize(items, capacity); });
#endif
Assert.AreEqual(half, list.Length); // Verify length didn't change
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>AddReplicate()
{
var list = new <#=TYPENAME #>();
list.AddReplicate(42, 2);
Assert.AreEqual(2, list.Length);
foreach (var item in list)
Assert.AreEqual(42, item);
list.AddReplicate(42, 3);
Assert.AreEqual(5, list.Length);
foreach (var item in list)
Assert.AreEqual(42, item);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<IndexOutOfRangeException>(() => { list.AddReplicate(42, 1000); });
#endif
Assert.AreEqual(5, list.Length); // Verify length didn't change
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>InsertRangeWithBeginEnd()
{
var list = new <#=TYPENAME #>() { 0, 3, 4 };
list.InsertRangeWithBeginEnd(1, 3);
list[1] = 1;
list[2] = 2;
for (var i = 0; i < 5; ++i)
Assert.AreEqual(i, list[i]);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>InsertRange()
{
var list = new <#=TYPENAME #>() { 0, 3, 4 };
Assert.AreEqual(3, list.Length);
list.InsertRange(1, 2);
Assert.AreEqual(5, list.Length);
list[1] = 1;
list[2] = 2;
Assert.DoesNotThrow(() => list.InsertRange(1, 0));
Assert.AreEqual(5, list.Length);
for (var i = 0; i < 5; ++i)
Assert.AreEqual(i, list[i]);
}
private static void Expected(ref <#=TYPENAME #> container, int expectedLength, int[] expected)
{
Assert.AreEqual(expectedLength == 0, container.IsEmpty);
Assert.AreEqual(container.Length, expectedLength);
for (var i = 0; i < container.Length; ++i)
{
Assert.AreEqual(expected[i], container[i]);
}
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>RemoveAt()
{
var list = new <#=TYPENAME #>() { 0, 3, 3, 1, 2 };
list.RemoveAt(1);
list.RemoveAt(1);
Expected(ref list, 3, new int[] { 0, 1, 2 });
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>Remove()
{
var list = new <#=TYPENAME #>() { 0, 3, 3, 1, 2 };
Assert.True(list.Remove((<#=TYPE#>)3));
Assert.True(list.Remove((<#=TYPE#>)3));
Expected(ref list, 3, new int[] { 0, 1, 2 });
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>RemoveSwapBack()
{
var list = new <#=TYPENAME #>() { 0, 3, 3, 2, 1 };
Assert.True(list.RemoveSwapBack((<#=TYPE#>)3));
Assert.True(list.RemoveSwapBack((<#=TYPE#>)3));
Expected(ref list, 3, new int[] { 0, 1, 2 });
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>RemoveRange()
{
var list = new <#=TYPENAME #>() { 0, 3, 3, 1, 2 };
list.RemoveRange(1, 2);
Expected(ref list, 3, new int[] { 0, 1, 2 });
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>RemoveAtSwapBack()
{
var list = new <#=TYPENAME #>() { 0, 3, 3, 1, 2 };
list.RemoveAtSwapBack(1);
list.RemoveAtSwapBack(1);
Expected(ref list, 3, new int[] { 0, 1, 3 });
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>RemoveRangeSwapBack()
{
var list = new <#=TYPENAME #>() { 0, 3, 3, 1, 2 };
list.RemoveRangeSwapBack(1, 2);
Expected(ref list, 3, new int[] { 0, 1, 2 });
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>Insert()
{
var list = new <#=TYPENAME #>() { 0, 3, 4 };
list.Insert(1, 1);
list.Insert(2, 2);
for (var i = 0; i < 5; ++i)
Assert.AreEqual(i, list[i]);
}
[Test]
public void <#=TYPENAME_IDENTIFIER #>Sort()
{
var list = new <#=TYPENAME #>();
for (var i = 0; i < 5; ++i)
list.Add((<#=TYPE #>)(4-i));
list.Sort();
for (var i = 0; i < 5; ++i)
Assert.AreEqual(i, list[i]);
}
<#
}
foreach (var OTHERBYTES in SIZES)
{
if (OTHERBYTES != BYTES)
{
var OTHERCAPACITY = (OTHERBYTES - 2) / TYPESIZE;
var OTHERTYPENAME = String.Format("FixedList{0}Bytes<{1}>", OTHERBYTES, TYPE);
var OTHERTYPENAME_IDENTIFIER = String.Format("_FixedList{0}{1}", OTHERBYTES, new CultureInfo("en-US").TextInfo.ToTitleCase(TYPE));
#>
[Test]
public void <#=TYPENAME_IDENTIFIER #>To<#=OTHERTYPENAME_IDENTIFIER #>()
{
var a = new <#=TYPENAME #>();
for (var i = 0; i < <#=EXPECTEDCAPACITY #>; ++i)
a.Add((<#=TYPE #>)i);
<#
if (EXPECTEDCAPACITY <= OTHERCAPACITY)
{
WriteLine(" var b = new {0}(a);", OTHERTYPENAME);
WriteLine(" for (var i = 0; i < {0}; ++i)", EXPECTEDCAPACITY);
WriteLine(" Assert.AreEqual(({0})i, b[i]);", TYPE);
}
else
WriteLine(
"#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG\n Assert.Throws<IndexOutOfRangeException>(() => {{ var b = new {0}(a); }} );\n#endif",
OTHERTYPENAME);
#>
}
<#
}
}
}
}
}
#>
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 775a8d1badc640e45a6030c3822a83d7
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,85 @@
using System;
using System.Globalization;
using System.Threading;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using System.Text;
using Unity.Burst;
// change this to change the core type under test
using FixedStringN = Unity.Collections.FixedString128Bytes;
namespace FixedStringTests
{
[BurstCompile]
internal class FixedStringBurstTests
{
[BurstCompile]
static int BurstAppendFn(ref FixedStringN fs, in FixedString32Bytes other)
{
fs.Append(in other);
return fs.Length;
}
delegate int BurstAppendDelegate(ref FixedStringN a, in FixedString32Bytes b);
[Test]
public void TestBurstAppend()
{
var fp = BurstCompiler.CompileFunctionPointer<BurstAppendDelegate>(BurstAppendFn);
var invoke = fp.Invoke;
FixedStringN a = new FixedStringN("Hello ");
FixedString32Bytes b = new FixedString32Bytes("World");
var len = invoke(ref a, b);
Assert.AreEqual(11, len);
Assert.AreEqual("Hello World", a.ToString());
}
const int kMatchesLiteral = 1 << 0;
const int kDiffersFromLiteral = 1 << 1;
const int kMatchesNull = 1 << 2;
const int kMatchesOverCapacityLiteral = 1 << 3;
const int kWasBurstCompiled = 1 << 4;
[BurstDiscard]
static void ClearIfManaged(ref bool wasBurstCompiled) => wasBurstCompiled = false;
[BurstCompile(CompileSynchronously = true)]
static int BurstCompareWithManagedStringFn(ref FixedString32Bytes fs)
{
var wasBurstCompiled = true;
ClearIfManaged(ref wasBurstCompiled);
var flags = 0;
if (fs == "Hello")
flags |= kMatchesLiteral;
if (fs != "World")
flags |= kDiffersFromLiteral;
if (fs == null)
flags |= kMatchesNull;
if (fs == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
flags |= kMatchesOverCapacityLiteral;
if (wasBurstCompiled)
flags |= kWasBurstCompiled;
return flags;
}
delegate int BurstCompareWithManagedStringDelegate(ref FixedString32Bytes fs);
[Test]
public void TestBurstCompareWithManagedString()
{
var fp = BurstCompiler.CompileFunctionPointer<BurstCompareWithManagedStringDelegate>(BurstCompareWithManagedStringFn);
var invoke = fp.Invoke;
var hello = new FixedString32Bytes("Hello");
Assert.AreEqual(kMatchesLiteral | kDiffersFromLiteral | kWasBurstCompiled, invoke(ref hello));
var empty = new FixedString32Bytes();
Assert.AreEqual(kDiffersFromLiteral | kMatchesNull | kWasBurstCompiled, invoke(ref empty));
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: bb7e2d0f4a7b4c32b50c2d10849628f2
timeCreated: 1591124402
@@ -0,0 +1,416 @@
using System;
using System.Globalization;
using System.Threading;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using System.Text;
// change this to change the core type under test
using FixedStringN = Unity.Collections.FixedString128Bytes;
namespace Unity.Collections.Tests
{
[TestFixture("en-US")]
[TestFixture("da-DK")]
internal class FixedStringCultureTests
{
CultureInfo testCulture;
CultureInfo backupCulture;
public FixedStringCultureTests(string culture)
{
testCulture = CultureInfo.CreateSpecificCulture(culture);
}
[SetUp]
public virtual void Setup()
{
backupCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = testCulture;
}
[TearDown]
public virtual void TearDown()
{
Thread.CurrentThread.CurrentCulture = backupCulture;
}
[TestCase("red", 0, 0, ParseError.Syntax)]
[TestCase("-red", 0, 0, ParseError.Syntax)]
[TestCase("+red", 0, 0, ParseError.Syntax)]
[TestCase("0", 1, 0, ParseError.None)]
[TestCase("+0", 2, 0, ParseError.None)]
[TestCase("-0", 2, 0, ParseError.None)]
[TestCase("-1", 2, -1, ParseError.None)]
[TestCase("100", 3, 100, ParseError.None)]
[TestCase("+100", 4, 100, ParseError.None)]
[TestCase("-100", 4, -100, ParseError.None)]
[TestCase("100.50", 3, 100, ParseError.None)]
[TestCase("-100ab", 4, -100, ParseError.None)]
[TestCase("2147483647", 10, 2147483647, ParseError.None)]
[TestCase("+2147483647", 11, 2147483647, ParseError.None)]
[TestCase("-2147483648", 11, -2147483648, ParseError.None)]
[TestCase("2147483648", 10, 0, ParseError.Overflow)]
[TestCase("-2147483649", 11, 0, ParseError.Overflow)]
[TestCase("2147483648000", 13, 0, ParseError.Overflow)]
[TestCase("-2147483649000", 14, 0, ParseError.Overflow)]
public void FixedStringNParseIntWorks(String a, int expectedOffset, int expectedOutput, ParseError expectedResult)
{
FixedStringN aa = new FixedStringN(a);
int offset = 0;
int output = 0;
var result = aa.Parse(ref offset, ref output);
Assert.AreEqual(expectedResult, result);
Assert.AreEqual(expectedOffset, offset);
if (result == ParseError.None)
{
Assert.AreEqual(expectedOutput, output);
}
}
[TestCase("red", 0, 0u, ParseError.Syntax)]
[TestCase("-red", 0, 0u, ParseError.Syntax)]
[TestCase("+red", 0, 0u, ParseError.Syntax)]
[TestCase("0", 1, 0u, ParseError.None)]
[TestCase("+0", 2, 0u, ParseError.None)]
[TestCase("-0", 2, 0u, ParseError.None)]
[TestCase("-1", 2, 0u, ParseError.Overflow)]
[TestCase("100", 3, 100u, ParseError.None)]
[TestCase("+100", 4, 100u, ParseError.None)]
[TestCase("-100", 4, 0u, ParseError.Overflow)]
[TestCase("100.50", 3, 100u, ParseError.None)]
[TestCase("-100.50", 4, 0u, ParseError.Overflow)]
[TestCase("100ab", 3, 100u, ParseError.None)]
[TestCase("-100ab", 4, 0u, ParseError.Overflow)]
[TestCase("2147483647", 10, 2147483647u, ParseError.None)]
[TestCase("-2147483648", 11, 0u, ParseError.Overflow)]
[TestCase("2147483648", 10, 2147483648u, ParseError.None)]
[TestCase("-2147483649", 11, 0u, ParseError.Overflow)]
[TestCase("4294967295", 10, 4294967295u, ParseError.None)]
[TestCase("+4294967295", 11, 4294967295u, ParseError.None)]
[TestCase("4294967296", 10, 0u, ParseError.Overflow)]
[TestCase("2147483648000", 13, 0u, ParseError.Overflow)]
[TestCase("-2147483649000", 14, 0u, ParseError.Overflow)]
public void FixedStringNParseUIntWorks(String a, int expectedOffset, uint expectedOutput, ParseError expectedResult)
{
FixedStringN aa = new FixedStringN(a);
int offset = 0;
uint output = 0;
var result = aa.Parse(ref offset, ref output);
Assert.AreEqual(expectedResult, result);
Assert.AreEqual(expectedOffset, offset);
if (result == ParseError.None)
{
Assert.AreEqual(expectedOutput, output);
}
}
[TestCase("red", 0, ParseError.Syntax)]
[TestCase("-red", 0, ParseError.Syntax)]
[TestCase("+red", 0, ParseError.Syntax)]
[TestCase("0", 1, ParseError.None)]
[TestCase("-1", 2, ParseError.None)]
[TestCase("-0", 2, ParseError.None)]
[TestCase("100", 3, ParseError.None)]
[TestCase("+100", 4, ParseError.None)]
[TestCase("-100", 4, ParseError.None)]
[TestCase("100.50", 6, ParseError.None)]
[TestCase("2147483648", 10, ParseError.None)]
[TestCase("-2147483649", 11, ParseError.None)]
[TestCase("-10E10", 6, ParseError.None)]
[TestCase("-10E-10", 7, ParseError.None)]
[TestCase("-10E+10", 7, ParseError.None)]
[TestCase("+10E10", 6, ParseError.None)]
[TestCase("+10E-10", 7, ParseError.None)]
[TestCase("+10E+10", 7, ParseError.None)]
[TestCase("10E-40", 6, ParseError.Underflow)]
[TestCase("10E+40", 6, ParseError.Overflow)]
// These tests are highly inconsistent among .NET versions. All 6 cases below parse correctly in
// .NET 5 however, so once we have updated they should be tried again.
//[TestCase("-nan", 4, ParseError.None)]
//[TestCase("+nan", 4, ParseError.None)]
//[TestCase("nan", 3, ParseError.None)]
//[TestCase("-infinity", 9, ParseError.None)]
//[TestCase("+infinity", 9, ParseError.None)]
//[TestCase("infinity", 8, ParseError.None)]
[TestCase("1000001", 7, ParseError.None)]
[TestCase("10000001", 8, ParseError.None)]
[TestCase("100000001", 9, ParseError.None)]
[TestCase("1000000001", 10, ParseError.None)]
[TestCase("10000000001", 11, ParseError.None)]
[TestCase("100000000001", 12, ParseError.None)]
public void FixedStringNParseFloat(String unlocalizedString, int expectedOffset, ParseError expectedResult)
{
var localizedDecimalSeparator = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
var localizedString = unlocalizedString.Replace('.', localizedDecimalSeparator);
float expectedOutput = 0;
try { expectedOutput = Single.Parse(localizedString); } catch {}
FixedStringN nativeLocalizedString = new FixedStringN(localizedString);
int offset = 0;
float output = 0;
var result = nativeLocalizedString.Parse(ref offset, ref output, localizedDecimalSeparator);
Assert.AreEqual(expectedResult, result);
Assert.AreEqual(expectedOffset, offset);
if (result == ParseError.None)
{
Assert.AreEqual(expectedOutput, output);
}
}
// While .NET 5 supports all combinations and capitalizations of "nan", "-nan", and "+nan",
// the implementation in Unity currently only supports "NaN" specifically
[Test]
public void FixedStringNParseFloatNan()
{
FixedStringN aa = new FixedStringN("NaN");
int offset = 0;
float output = 0;
var result = aa.Parse(ref offset, ref output);
Assert.AreEqual(ParseError.None, result);
Assert.IsTrue(Single.IsNaN(output));
}
// While .NET 5 supports all combinations and capitalizations of "infinity", "-infinity", and "+infinity",
// the mono implementation in Unity currently only supports "Infinity" and "-Infinity" specifically
// (not even "+Infinity")
[Test]
public void FixedStringNParseFloatInfinity()
{
FixedStringN aa = new FixedStringN("Infinity");
int offset = 0;
float output = 0;
var result = aa.Parse(ref offset, ref output);
Assert.AreEqual(ParseError.None, result);
Assert.IsTrue(Single.IsPositiveInfinity(output));
}
[Test]
public void FixedStringNParseFloatNegativeInfinity()
{
FixedStringN aa = new FixedStringN("-Infinity");
int offset = 0;
float output = 0;
var result = aa.Parse(ref offset, ref output);
Assert.AreEqual(ParseError.None, result);
Assert.IsTrue(Single.IsNegativeInfinity(output));
}
[TestCase(-2147483648)]
[TestCase(-100)]
[TestCase(-1)]
[TestCase(0)]
[TestCase(1)]
[TestCase(100)]
[TestCase(2147483647)]
public void FixedStringNFormatInt(int input)
{
var expectedOutput = input.ToString();
FixedStringN aa = new FixedStringN();
var result = aa.Append(input);
Assert.AreEqual(FormatError.None, result);
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[TestCase(-9223372036854775808L)]
[TestCase(-100L)]
[TestCase(-1L)]
[TestCase(0L)]
[TestCase(1L)]
[TestCase(100L)]
[TestCase(9223372036854775807L)]
public void FixedStringNFormatLong(long input)
{
var expectedOutput = input.ToString();
FixedStringN aa = new FixedStringN();
var result = aa.Append(input);
Assert.AreEqual(FormatError.None, result);
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[TestCase(0U)]
[TestCase(1U)]
[TestCase(100U)]
[TestCase(4294967295U)]
public void FixedStringNFormatUInt(uint input)
{
var expectedOutput = input.ToString();
FixedStringN aa = new FixedStringN();
var result = aa.Append(input);
Assert.AreEqual(FormatError.None, result);
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[TestCase(0UL)]
[TestCase(1UL)]
[TestCase(100UL)]
[TestCase(18446744073709551615UL)]
public void FixedStringNFormatULong(ulong input)
{
var expectedOutput = input.ToString();
FixedStringN aa = new FixedStringN();
var result = aa.Append(input);
Assert.AreEqual(FormatError.None, result);
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[TestCase(Single.NaN, FormatError.None)]
[TestCase(Single.PositiveInfinity, FormatError.None)]
[TestCase(Single.NegativeInfinity, FormatError.None)]
[TestCase(0.0f, FormatError.None)]
[TestCase(-1.0f, FormatError.None)]
[TestCase(100.0f, FormatError.None)]
[TestCase(-100.0f, FormatError.None)]
[TestCase(100.5f, FormatError.None)]
[TestCase(0.001005f, FormatError.None)]
[TestCase(0.0001f, FormatError.None)]
[TestCase(0.00001f, FormatError.None)]
[TestCase(0.000001f, FormatError.None)]
[TestCase(-1E10f, FormatError.None)]
[TestCase(-1E-10f, FormatError.None)]
[TestCase(3.402823E+38f, FormatError.None)]
public void FixedStringNFormatFloat(float input, FormatError expectedResult)
{
var localizedDecimalSeparator = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
var expectedOutput = input.ToString();
FixedStringN aa = new FixedStringN();
var result = aa.Append(input, localizedDecimalSeparator);
Assert.AreEqual(expectedResult, result);
if (result == FormatError.None)
{
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
}
[TestCase(-2147483648)]
[TestCase(-100)]
[TestCase(-1)]
[TestCase(0)]
[TestCase(1)]
[TestCase(100)]
[TestCase(2147483647)]
public void FixedStringNAppendInt(int input)
{
var expectedOutput = "foo" + input.ToString();
FixedStringN aa = "foo";
var result = aa.Append(input);
Assert.AreEqual(FormatError.None, result);
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[TestCase(-9223372036854775808L)]
[TestCase(-100L)]
[TestCase(-1L)]
[TestCase(0L)]
[TestCase(1L)]
[TestCase(100L)]
[TestCase(9223372036854775807L)]
public void FixedStringNAppendLong(long input)
{
var expectedOutput = "foo" + input.ToString();
FixedStringN aa = "foo";
var result = aa.Append(input);
Assert.AreEqual(FormatError.None, result);
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[TestCase(0U)]
[TestCase(1U)]
[TestCase(100U)]
[TestCase(4294967295U)]
public void FixedStringNAppendUInt(uint input)
{
var expectedOutput = "foo" + input.ToString();
FixedStringN aa = "foo";
var result = aa.Append(input);
Assert.AreEqual(FormatError.None, result);
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[TestCase(0UL)]
[TestCase(1UL)]
[TestCase(100UL)]
[TestCase(18446744073709551615UL)]
public void FixedStringNAppendULong(ulong input)
{
var expectedOutput = "foo" + input.ToString();
FixedStringN aa = "foo";
var result = aa.Append(input);
Assert.AreEqual(FormatError.None, result);
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[TestCase(Single.NaN, FormatError.None)]
[TestCase(Single.PositiveInfinity, FormatError.None)]
[TestCase(Single.NegativeInfinity, FormatError.None)]
[TestCase(0.0f, FormatError.None)]
[TestCase(-1.0f, FormatError.None)]
[TestCase(100.0f, FormatError.None)]
[TestCase(-100.0f, FormatError.None)]
[TestCase(100.5f, FormatError.None)]
[TestCase(0.001005f, FormatError.None)]
[TestCase(0.0001f, FormatError.None)]
[TestCase(0.00001f, FormatError.None)]
[TestCase(0.000001f, FormatError.None)]
[TestCase(-1E10f, FormatError.None)]
[TestCase(-1E-10f, FormatError.None)]
public void FixedStringNAppendFloat(float input, FormatError expectedResult)
{
var localizedDecimalSeparator = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
var expectedOutput = "foo" + input.ToString();
FixedStringN aa = "foo";
var result = aa.Append(input, localizedDecimalSeparator);
Assert.AreEqual(expectedResult, result);
if (result == FormatError.None)
{
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
}
[Test]
public void FixedStringNFormatNegativeZero()
{
float input = -0.0f;
var expectedOutput = input.ToString(CultureInfo.InvariantCulture);
FixedStringN aa = new FixedStringN();
var result = aa.Append(input);
Assert.AreEqual(FormatError.None, result);
var actualOutput = aa.ToString();
Assert.AreEqual(expectedOutput, actualOutput);
}
[TestCase("en-US")]
[TestCase("da-DK")]
public void FixedStringNParseFloatLocale(String locale)
{
var original = CultureInfo.CurrentCulture;
try
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(locale);
var localizedDecimalSeparator = Convert.ToChar(Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator);
float value = 1.5f;
FixedStringN native = new FixedStringN();
native.Append(value, localizedDecimalSeparator);
var nativeResult = native.ToString();
var managedResult = value.ToString();
Assert.AreEqual(managedResult, nativeResult);
}
finally
{
Thread.CurrentThread.CurrentCulture = original;
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e63bf9a80e1c4f6fa05404f9afe1bb32
timeCreated: 1591118624
@@ -0,0 +1,577 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// t4 Samples/Packages/com.unity.collections/Unity.Collections.Tests/FixedStringSizedTests.tt
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.Tests;
using UnityEngine;
namespace Unity.Collections.Tests
{
internal class FixedStringSizedTests
{
class ScriptableObjectFixedString32Bytes : UnityEngine.ScriptableObject
{
public FixedString32Bytes String;
}
[Test]
public void FixedString32BytesSerializes()
{
var a = UnityEngine.ScriptableObject.CreateInstance<ScriptableObjectFixedString32Bytes>();
a.String = "Hello World";
var b = UnityEngine.Object.Instantiate(a);
Assert.AreEqual(a.String, b.String);
}
[TestCase("ooooooooooooooooooooooooooooo", FormatError.None, TestName="FixedString32AtMaximumSizeWorks_Almost")]
[TestCase("oooooooooooooooooooooooooooooo", FormatError.Overflow, TestName="FixedString32AtMaximumSizeWorks_Over")]
public void FixedString32BytesAtMaximumSizeWorks(String a, FormatError expectedError)
{
FixedString32Bytes aa = default;
aa.Junk();
var error = aa.Append(a);
Assert.AreEqual(expectedError, error);
if (expectedError == FormatError.None)
aa.AssertNullTerminated();
else
Assert.AreEqual(0, aa.Length);
}
[Test]
public unsafe void FixedString32BytesToFixedList()
{
FixedString32Bytes a = default;
a.Junk();
a.Append("0123");
ref var aList = ref a.AsFixedList();
Assert.IsFalse(aList.IsEmpty);
Assert.AreEqual(4, aList.Length);
Assert.AreEqual(a.Capacity + 1, aList.Capacity);
Assert.AreEqual('0', aList[0]);
Assert.AreEqual('1', aList[1]);
Assert.AreEqual('2', aList[2]);
Assert.AreEqual('3', aList[3]);
aList.Add((byte)'4');
Assert.AreEqual("01234", a);
// because we modified it as a FixedList, it will not be null terminated!
Assert.AreNotEqual(0, a.GetUnsafePtr()[a.Length]);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public unsafe void FixedString32BytesEqualsStringNoGC(string a)
{
FixedString32Bytes b = a;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
b.Equals(a);
});
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString32BytesToFixedString64Works(String a)
{
var b = new FixedString32Bytes(a);
var c = new FixedString64Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString32BytesToFixedString128Works(String a)
{
var b = new FixedString32Bytes(a);
var c = new FixedString128Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString32BytesToFixedString512Works(String a)
{
var b = new FixedString32Bytes(a);
var c = new FixedString512Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString32BytesToFixedString4096Works(String a)
{
var b = new FixedString32Bytes(a);
var c = new FixedString4096Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
class ScriptableObjectFixedString64Bytes : UnityEngine.ScriptableObject
{
public FixedString64Bytes String;
}
[Test]
public void FixedString64BytesSerializes()
{
var a = UnityEngine.ScriptableObject.CreateInstance<ScriptableObjectFixedString64Bytes>();
a.String = "Hello World";
var b = UnityEngine.Object.Instantiate(a);
Assert.AreEqual(a.String, b.String);
}
[TestCase("ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", FormatError.None, TestName="FixedString64AtMaximumSizeWorks_Almost")]
[TestCase("oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", FormatError.Overflow, TestName="FixedString64AtMaximumSizeWorks_Over")]
public void FixedString64BytesAtMaximumSizeWorks(String a, FormatError expectedError)
{
FixedString64Bytes aa = default;
aa.Junk();
var error = aa.Append(a);
Assert.AreEqual(expectedError, error);
if (expectedError == FormatError.None)
aa.AssertNullTerminated();
else
Assert.AreEqual(0, aa.Length);
}
[Test]
public unsafe void FixedString64BytesToFixedList()
{
FixedString64Bytes a = default;
a.Junk();
a.Append("0123");
ref var aList = ref a.AsFixedList();
Assert.IsFalse(aList.IsEmpty);
Assert.AreEqual(4, aList.Length);
Assert.AreEqual(a.Capacity + 1, aList.Capacity);
Assert.AreEqual('0', aList[0]);
Assert.AreEqual('1', aList[1]);
Assert.AreEqual('2', aList[2]);
Assert.AreEqual('3', aList[3]);
aList.Add((byte)'4');
Assert.AreEqual("01234", a);
// because we modified it as a FixedList, it will not be null terminated!
Assert.AreNotEqual(0, a.GetUnsafePtr()[a.Length]);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public unsafe void FixedString64BytesEqualsStringNoGC(string a)
{
FixedString64Bytes b = a;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
b.Equals(a);
});
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString64BytesToFixedString32Works(String a)
{
var b = new FixedString64Bytes(a);
var c = new FixedString32Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString64BytesToFixedString128Works(String a)
{
var b = new FixedString64Bytes(a);
var c = new FixedString128Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString64BytesToFixedString512Works(String a)
{
var b = new FixedString64Bytes(a);
var c = new FixedString512Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString64BytesToFixedString4096Works(String a)
{
var b = new FixedString64Bytes(a);
var c = new FixedString4096Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
class ScriptableObjectFixedString128Bytes : UnityEngine.ScriptableObject
{
public FixedString128Bytes String;
}
[Test]
public void FixedString128BytesSerializes()
{
var a = UnityEngine.ScriptableObject.CreateInstance<ScriptableObjectFixedString128Bytes>();
a.String = "Hello World";
var b = UnityEngine.Object.Instantiate(a);
Assert.AreEqual(a.String, b.String);
}
[TestCase("ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", FormatError.None, TestName="FixedString128AtMaximumSizeWorks_Almost")]
[TestCase("oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", FormatError.Overflow, TestName="FixedString128AtMaximumSizeWorks_Over")]
public void FixedString128BytesAtMaximumSizeWorks(String a, FormatError expectedError)
{
FixedString128Bytes aa = default;
aa.Junk();
var error = aa.Append(a);
Assert.AreEqual(expectedError, error);
if (expectedError == FormatError.None)
aa.AssertNullTerminated();
else
Assert.AreEqual(0, aa.Length);
}
[Test]
public unsafe void FixedString128BytesToFixedList()
{
FixedString128Bytes a = default;
a.Junk();
a.Append("0123");
ref var aList = ref a.AsFixedList();
Assert.IsFalse(aList.IsEmpty);
Assert.AreEqual(4, aList.Length);
Assert.AreEqual(a.Capacity + 1, aList.Capacity);
Assert.AreEqual('0', aList[0]);
Assert.AreEqual('1', aList[1]);
Assert.AreEqual('2', aList[2]);
Assert.AreEqual('3', aList[3]);
aList.Add((byte)'4');
Assert.AreEqual("01234", a);
// because we modified it as a FixedList, it will not be null terminated!
Assert.AreNotEqual(0, a.GetUnsafePtr()[a.Length]);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public unsafe void FixedString128BytesEqualsStringNoGC(string a)
{
FixedString128Bytes b = a;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
b.Equals(a);
});
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString128BytesToFixedString32Works(String a)
{
var b = new FixedString128Bytes(a);
var c = new FixedString32Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString128BytesToFixedString64Works(String a)
{
var b = new FixedString128Bytes(a);
var c = new FixedString64Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString128BytesToFixedString512Works(String a)
{
var b = new FixedString128Bytes(a);
var c = new FixedString512Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString128BytesToFixedString4096Works(String a)
{
var b = new FixedString128Bytes(a);
var c = new FixedString4096Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
class ScriptableObjectFixedString512Bytes : UnityEngine.ScriptableObject
{
public FixedString512Bytes String;
}
[Test]
public void FixedString512BytesSerializes()
{
var a = UnityEngine.ScriptableObject.CreateInstance<ScriptableObjectFixedString512Bytes>();
a.String = "Hello World";
var b = UnityEngine.Object.Instantiate(a);
Assert.AreEqual(a.String, b.String);
}
[TestCase("ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", FormatError.None, TestName="FixedString512AtMaximumSizeWorks_Almost")]
[TestCase("oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", FormatError.Overflow, TestName="FixedString512AtMaximumSizeWorks_Over")]
public void FixedString512BytesAtMaximumSizeWorks(String a, FormatError expectedError)
{
FixedString512Bytes aa = default;
aa.Junk();
var error = aa.Append(a);
Assert.AreEqual(expectedError, error);
if (expectedError == FormatError.None)
aa.AssertNullTerminated();
else
Assert.AreEqual(0, aa.Length);
}
[Test]
public unsafe void FixedString512BytesToFixedList()
{
FixedString512Bytes a = default;
a.Junk();
a.Append("0123");
ref var aList = ref a.AsFixedList();
Assert.IsFalse(aList.IsEmpty);
Assert.AreEqual(4, aList.Length);
Assert.AreEqual(a.Capacity + 1, aList.Capacity);
Assert.AreEqual('0', aList[0]);
Assert.AreEqual('1', aList[1]);
Assert.AreEqual('2', aList[2]);
Assert.AreEqual('3', aList[3]);
aList.Add((byte)'4');
Assert.AreEqual("01234", a);
// because we modified it as a FixedList, it will not be null terminated!
Assert.AreNotEqual(0, a.GetUnsafePtr()[a.Length]);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public unsafe void FixedString512BytesEqualsStringNoGC(string a)
{
FixedString512Bytes b = a;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
b.Equals(a);
});
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString512BytesToFixedString32Works(String a)
{
var b = new FixedString512Bytes(a);
var c = new FixedString32Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString512BytesToFixedString64Works(String a)
{
var b = new FixedString512Bytes(a);
var c = new FixedString64Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString512BytesToFixedString128Works(String a)
{
var b = new FixedString512Bytes(a);
var c = new FixedString128Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString512BytesToFixedString4096Works(String a)
{
var b = new FixedString512Bytes(a);
var c = new FixedString4096Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
class ScriptableObjectFixedString4096Bytes : UnityEngine.ScriptableObject
{
public FixedString4096Bytes String;
}
[Test]
public void FixedString4096BytesSerializes()
{
var a = UnityEngine.ScriptableObject.CreateInstance<ScriptableObjectFixedString4096Bytes>();
a.String = "Hello World";
var b = UnityEngine.Object.Instantiate(a);
Assert.AreEqual(a.String, b.String);
}
[TestCase("ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", FormatError.None, TestName="FixedString4096AtMaximumSizeWorks_Almost")]
[TestCase("oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo", FormatError.Overflow, TestName="FixedString4096AtMaximumSizeWorks_Over")]
public void FixedString4096BytesAtMaximumSizeWorks(String a, FormatError expectedError)
{
FixedString4096Bytes aa = default;
aa.Junk();
var error = aa.Append(a);
Assert.AreEqual(expectedError, error);
if (expectedError == FormatError.None)
aa.AssertNullTerminated();
else
Assert.AreEqual(0, aa.Length);
}
[Test]
public unsafe void FixedString4096BytesToFixedList()
{
FixedString4096Bytes a = default;
a.Junk();
a.Append("0123");
ref var aList = ref a.AsFixedList();
Assert.IsFalse(aList.IsEmpty);
Assert.AreEqual(4, aList.Length);
Assert.AreEqual(a.Capacity + 1, aList.Capacity);
Assert.AreEqual('0', aList[0]);
Assert.AreEqual('1', aList[1]);
Assert.AreEqual('2', aList[2]);
Assert.AreEqual('3', aList[3]);
aList.Add((byte)'4');
Assert.AreEqual("01234", a);
// because we modified it as a FixedList, it will not be null terminated!
Assert.AreNotEqual(0, a.GetUnsafePtr()[a.Length]);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public unsafe void FixedString4096BytesEqualsStringNoGC(string a)
{
FixedString4096Bytes b = a;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
b.Equals(a);
});
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString4096BytesToFixedString32Works(String a)
{
var b = new FixedString4096Bytes(a);
var c = new FixedString32Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString4096BytesToFixedString64Works(String a)
{
var b = new FixedString4096Bytes(a);
var c = new FixedString64Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString4096BytesToFixedString128Works(String a)
{
var b = new FixedString4096Bytes(a);
var c = new FixedString128Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString4096BytesToFixedString512Works(String a)
{
var b = new FixedString4096Bytes(a);
var c = new FixedString512Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 0a06298414d1430487a2bc2bde42fba6
timeCreated: 1591116341
@@ -0,0 +1,124 @@
<#/*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.Tests/FixedStringSizedTests.tt
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.Tests;
using UnityEngine;
namespace Unity.Collections.Tests
{
internal class FixedStringSizedTests
{
<#
var SIZES = new int[] {32,64,128,512,4096};
foreach(var BYTES in SIZES)
{
// 2 bytes ushort + 1 byte space for null termination
var ALMOST_TOO_BIG = new String('o', BYTES - 3);
var TOO_BIG = new String('o', BYTES - 2);
#>
class ScriptableObjectFixedString<#=BYTES#>Bytes : UnityEngine.ScriptableObject
{
public FixedString<#=BYTES#>Bytes String;
}
[Test]
public void FixedString<#=BYTES#>BytesSerializes()
{
var a = UnityEngine.ScriptableObject.CreateInstance<ScriptableObjectFixedString<#=BYTES#>Bytes>();
a.String = "Hello World";
var b = UnityEngine.Object.Instantiate(a);
Assert.AreEqual(a.String, b.String);
}
[TestCase("<#=ALMOST_TOO_BIG#>", FormatError.None, TestName="FixedString<#=BYTES#>AtMaximumSizeWorks_Almost")]
[TestCase("<#=TOO_BIG#>", FormatError.Overflow, TestName="FixedString<#=BYTES#>AtMaximumSizeWorks_Over")]
public void FixedString<#=BYTES#>BytesAtMaximumSizeWorks(String a, FormatError expectedError)
{
FixedString<#=BYTES#>Bytes aa = default;
aa.Junk();
var error = aa.Append(a);
Assert.AreEqual(expectedError, error);
if (expectedError == FormatError.None)
aa.AssertNullTerminated();
else
Assert.AreEqual(0, aa.Length);
}
[Test]
public unsafe void FixedString<#=BYTES#>BytesToFixedList()
{
FixedString<#=BYTES#>Bytes a = default;
a.Junk();
a.Append("0123");
ref var aList = ref a.AsFixedList();
Assert.IsFalse(aList.IsEmpty);
Assert.AreEqual(4, aList.Length);
Assert.AreEqual(a.Capacity + 1, aList.Capacity);
Assert.AreEqual('0', aList[0]);
Assert.AreEqual('1', aList[1]);
Assert.AreEqual('2', aList[2]);
Assert.AreEqual('3', aList[3]);
aList.Add((byte)'4');
Assert.AreEqual("01234", a);
// because we modified it as a FixedList, it will not be null terminated!
Assert.AreNotEqual(0, a.GetUnsafePtr()[a.Length]);
}
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public unsafe void FixedString<#=BYTES#>BytesEqualsStringNoGC(string a)
{
FixedString<#=BYTES#>Bytes b = a;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
b.Equals(a);
});
}
<#
foreach(var OTHERBYTES in SIZES)
{
if (OTHERBYTES != BYTES)
{
#>
[TestCase("red")]
[TestCase("紅色", TestName="{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName="{m}(HarukiMurakami)")]
public void FixedString<#=BYTES#>BytesToFixedString<#=OTHERBYTES#>Works(String a)
{
var b = new FixedString<#=BYTES#>Bytes(a);
var c = new FixedString<#=OTHERBYTES#>Bytes(b);
String d = c.ToString();
Assert.AreEqual(a, d);
}
<#
}
}
}
#>
}
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 0be05385fc513c143a5b5249b7ad6211
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,588 @@
using System;
using System.Globalization;
using System.Threading;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using System.Text;
// change this to change the core type under test
using FixedStringN = Unity.Collections.FixedString128Bytes;
namespace Unity.Collections.Tests
{
internal static class FixedStringTestUtils
{
internal unsafe static void Junk<T>(ref this T fs)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
var bytes = fs.GetUnsafePtr();
var cap = fs.Capacity;
// Match MSVC stack init pattern
UnsafeUtility.MemSet(bytes, 0xcc, cap);
}
internal unsafe static void AssertNullTerminated<T>(this T fs)
where T : unmanaged, INativeList<byte>, IUTF8Bytes
{
Assert.AreEqual(0, fs.GetUnsafePtr()[fs.Length]);
}
}
internal class FixedStringTests
{
[Test]
public void FixedStringFormat()
{
Assert.AreEqual("1 0", FixedString.Format("{0} {1}", 1, 0));
Assert.AreEqual("0.1 1.2", FixedString.Format("{0} {1}", 0.1f, 1.2f));
Assert.AreEqual("error 500 in line 350: bubbly", FixedString.Format("error {0} in line {1}: {2}", 500, 350, "bubbly"));
}
[Test]
public void FixedStringNFormatExtension1Params()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{0}";
FixedString32Bytes arg0 = "a";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0));
Assert.AreEqual("a", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatExtension2Params()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{0} {1}";
FixedString32Bytes arg0 = "a";
FixedString32Bytes arg1 = "b";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0, arg1));
Assert.AreEqual("a b", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatExtension3Params()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{0} {1} {2}";
FixedString32Bytes arg0 = "a";
FixedString32Bytes arg1 = "b";
FixedString32Bytes arg2 = "c";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0, arg1, arg2));
Assert.AreEqual("a b c", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatExtension4Params()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{0} {1} {2} {3}";
FixedString32Bytes arg0 = "a";
FixedString32Bytes arg1 = "b";
FixedString32Bytes arg2 = "c";
FixedString32Bytes arg3 = "d";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0, arg1, arg2, arg3));
Assert.AreEqual("a b c d", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatExtension5Params()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{0} {1} {2} {3} {4}";
FixedString32Bytes arg0 = "a";
FixedString32Bytes arg1 = "b";
FixedString32Bytes arg2 = "c";
FixedString32Bytes arg3 = "d";
FixedString32Bytes arg4 = "e";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0, arg1, arg2, arg3, arg4));
Assert.AreEqual("a b c d e", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatExtension6Params()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{0} {1} {2} {3} {4} {5}";
FixedString32Bytes arg0 = "a";
FixedString32Bytes arg1 = "b";
FixedString32Bytes arg2 = "c";
FixedString32Bytes arg3 = "d";
FixedString32Bytes arg4 = "e";
FixedString32Bytes arg5 = "f";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0, arg1, arg2, arg3, arg4, arg5));
Assert.AreEqual("a b c d e f", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatExtension7Params()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{0} {1} {2} {3} {4} {5} {6}";
FixedString32Bytes arg0 = "a";
FixedString32Bytes arg1 = "b";
FixedString32Bytes arg2 = "c";
FixedString32Bytes arg3 = "d";
FixedString32Bytes arg4 = "e";
FixedString32Bytes arg5 = "f";
FixedString32Bytes arg6 = "g";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0, arg1, arg2, arg3, arg4, arg5, arg6));
Assert.AreEqual("a b c d e f g", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatExtension8Params()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{0} {1} {2} {3} {4} {5} {6} {7}";
FixedString32Bytes arg0 = "a";
FixedString32Bytes arg1 = "b";
FixedString32Bytes arg2 = "c";
FixedString32Bytes arg3 = "d";
FixedString32Bytes arg4 = "e";
FixedString32Bytes arg5 = "f";
FixedString32Bytes arg6 = "g";
FixedString32Bytes arg7 = "h";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7));
Assert.AreEqual("a b c d e f g h", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatExtension9Params()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{0} {1} {2} {3} {4} {5} {6} {7} {8}";
FixedString32Bytes arg0 = "a";
FixedString32Bytes arg1 = "b";
FixedString32Bytes arg2 = "c";
FixedString32Bytes arg3 = "d";
FixedString32Bytes arg4 = "e";
FixedString32Bytes arg5 = "f";
FixedString32Bytes arg6 = "g";
FixedString32Bytes arg7 = "h";
FixedString32Bytes arg8 = "i";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8));
Assert.AreEqual("a b c d e f g h i", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatExtension10Params()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}";
FixedString32Bytes arg0 = "a";
FixedString32Bytes arg1 = "b";
FixedString32Bytes arg2 = "c";
FixedString32Bytes arg3 = "d";
FixedString32Bytes arg4 = "e";
FixedString32Bytes arg5 = "f";
FixedString32Bytes arg6 = "g";
FixedString32Bytes arg7 = "h";
FixedString32Bytes arg8 = "i";
FixedString32Bytes arg9 = "j";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9));
Assert.AreEqual("a b c d e f g h i j", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatBadFormat()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{10}";
FixedString32Bytes arg0 = "a";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{0 } ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{ 0} ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{0a} ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{012 ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{0{ ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{0{ ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{0} } ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{ {0} ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{{{0}} ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{{0} ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
format = "{0}} ";
Assert.AreEqual(FormatError.BadFormatSpecifier, aa.AppendFormat(format, arg0));
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNFormatOverflow()
{
FixedString32Bytes aa = default;
aa.Junk();
FixedStringN format = "{0}";
FixedStringN arg0 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
Assert.AreEqual(FormatError.Overflow, aa.AppendFormat(format, arg0));
}
[Test]
public void FixedStringNFormatBraces()
{
FixedStringN aa = default;
aa.Junk();
FixedStringN format = "{{0}}";
FixedString32Bytes arg0 = "42";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0));
Assert.AreEqual("{0}", aa);
aa.AssertNullTerminated();
aa = default;
format = "{{{0}}}";
arg0 = "43";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0));
Assert.AreEqual("{43}", aa);
aa.AssertNullTerminated();
aa = default;
format = "{{{0}";
arg0 = "44";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0));
Assert.AreEqual("{44", aa);
aa.AssertNullTerminated();
aa = default;
format = "{0}}}";
arg0 = "45";
Assert.AreEqual(FormatError.None, aa.AppendFormat(format, arg0));
Assert.AreEqual("45}", aa);
aa.AssertNullTerminated();
}
[Test]
public void FixedStringNAppendString()
{
FixedStringN aa = default;
Assert.AreEqual(CopyError.None, aa.CopyFrom(new FixedString32Bytes("aa")));
Assert.AreEqual("aa", aa.ToString());
Assert.AreEqual(FormatError.None, aa.Append("bb"));
Assert.AreEqual("aabb", aa.ToString());
}
[Test]
public void FixedStringRuneWorks()
{
var rune = new Unicode.Rune(0xfbad);
FixedStringN a = new FixedStringN(rune, 3);
FixedStringN b = default;
Assert.AreEqual(FormatError.None, b.Append(rune));
Assert.AreEqual(FormatError.None, b.Append(rune, 2));
Assert.AreEqual(a.ToString(), b.ToString());
}
[TestCase("Antidisestablishmentarianism")]
[TestCase("⁣🌹🌻🌷🌿🌵🌾⁣")]
public void FixedStringNCopyFromBytesWorks(String a)
{
FixedStringN aa = default;
aa.Junk();
Assert.AreEqual(CopyError.None, aa.CopyFrom(a));
Assert.AreEqual(a, aa.ToString());
aa.AssertNullTerminated();
Assert.AreEqual(FormatError.None, aa.Append("tail"));
Assert.AreEqual(a + "tail", aa.ToString());
aa.AssertNullTerminated();
}
[TestCase("red")]
[TestCase("紅色", TestName = "{m}(Chinese-Red)")]
[TestCase("George Washington")]
[TestCase("村上春樹", TestName = "{m}(HarukiMurakami)")]
public void FixedStringNToStringWorks(String a)
{
FixedStringN aa = new FixedStringN(a);
Assert.AreEqual(a, aa.ToString());
aa.AssertNullTerminated();
}
[TestCase("monkey", "monkey")]
[TestCase("yellow", "green")]
[TestCase("violet", "紅色", TestName = "{m}(Violet-Chinese-Red")]
[TestCase("绿色", "蓝色", TestName = "{m}(Chinese-Green-Blue")]
[TestCase("靛蓝色", "紫罗兰色", TestName = "{m}(Chinese-Indigo-Violet")]
[TestCase("James Monroe", "John Quincy Adams")]
[TestCase("Andrew Jackson", "村上春樹", TestName = "{m}(AndrewJackson-HarukiMurakami")]
[TestCase("三島 由紀夫", "吉本ばなな", TestName = "{m}(MishimaYukio-YoshimotoBanana")]
public void FixedStringNEqualsWorks(String a, String b)
{
FixedStringN aa = new FixedStringN(a);
FixedStringN bb = new FixedStringN(b);
Assert.AreEqual(aa.Equals(bb), a.Equals(b));
aa.AssertNullTerminated();
bb.AssertNullTerminated();
}
[Test]
public void FixedStringNForEach()
{
FixedStringN actual = "A🌕Z🌑";
FixedList32Bytes<int> expected = default;
expected.Add('A');
expected.Add(0x1F315);
expected.Add('Z');
expected.Add(0x1F311);
int index = 0;
foreach (var rune in actual)
{
Assert.AreEqual(expected[index], rune.value);
++index;
}
}
[Test]
public void FixedStringNSubstring()
{
FixedStringN a = "This is substring.";
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<ArgumentOutOfRangeException>(() => a.Substring(-8, 9));
Assert.Throws<ArgumentOutOfRangeException>(() => a.Substring(200, 9));
Assert.Throws<ArgumentOutOfRangeException>(() => a.Substring(8, -9));
#endif
{
FixedStringN b = a.Substring(8, 9);
Assert.IsTrue(b.Equals("substring"));
}
{
FixedStringN b = a.Substring(8, 100);
Assert.IsTrue(b.Equals("substring."));
}
}
[Test]
public void FixedStringNIndexOf()
{
FixedStringN a = "bookkeeper bookkeeper";
FixedStringN b = "ookkee";
Assert.AreEqual(1, a.IndexOf(b));
Assert.AreEqual(-1, b.IndexOf(a));
}
[Test]
public void FixedStringNLastIndexOf()
{
FixedStringN a = "bookkeeper bookkeeper";
FixedStringN b = "ookkee";
Assert.AreEqual(12, a.LastIndexOf(b));
Assert.AreEqual(-1, b.LastIndexOf(a));
}
[Test]
public void FixedStringNContains()
{
FixedStringN a = "bookkeeper";
FixedStringN b = "ookkee";
Assert.AreEqual(true, a.Contains(b));
}
[Test]
public void FixedStringNComparisons()
{
FixedStringN a = "apple";
FixedStringN b = "banana";
Assert.AreEqual(false, a.Equals(b));
Assert.AreEqual(true, !b.Equals(a));
{
var string40Length = new string('a', 40);
var fixedString = new FixedString64Bytes(string40Length);
Assert.AreEqual(true, string40Length == fixedString);
Assert.AreEqual(true, fixedString.Equals(string40Length));
Assert.AreEqual(true, fixedString == string40Length);
}
}
[Test]
public void FixedStringN_EqualityWithString_DoesNotThrowWhenStringExceedsCapacity()
{
var fixedString = new FixedString64Bytes("hello");
var longString = new string('a', 200);
Assert.AreEqual(false, fixedString == longString);
Assert.AreEqual(true, fixedString != longString);
Assert.AreEqual(false, longString == fixedString);
Assert.AreEqual(true, longString != fixedString);
}
[Test]
public void FixedStringN_EqualityWithString_HandlesNullString()
{
var fixedString = new FixedString64Bytes("hello");
string nullString = null;
Assert.AreEqual(false, fixedString == nullString);
Assert.AreEqual(true, fixedString != nullString);
Assert.AreEqual(false, nullString == fixedString);
Assert.AreEqual(true, nullString != fixedString);
var emptyFixed = new FixedString64Bytes();
Assert.AreEqual(true, emptyFixed == nullString);
Assert.AreEqual(false, emptyFixed != nullString);
Assert.AreEqual(true, nullString == emptyFixed);
Assert.AreEqual(false, nullString != emptyFixed);
}
[Test]
public void FixedStringN_EqualityWithString_HandlesEmbeddedNulls()
{
var fixedString = new FixedString64Bytes("A\0BB");
Assert.AreEqual(false, fixedString == "A\0C");
Assert.AreEqual(true, fixedString != "A\0C");
Assert.AreEqual(true, fixedString == "A\0BB");
Assert.AreEqual(false, fixedString != "A\0BB");
Assert.AreEqual(false, fixedString == "A\0");
Assert.AreEqual(false, "A\0C" == fixedString);
Assert.AreEqual(true, "A\0C" != fixedString);
Assert.AreEqual(true, "A\0BB" == fixedString);
}
[Test]
public void FixedStringN_EqualityWithString_MalformedUtf8IsNotEqualToReplacementCharacter()
{
var fixedString = new FixedString32Bytes("x");
fixedString[0] = 0xFF;
Assert.AreEqual(false, fixedString == "\uFFFD");
Assert.AreEqual(true, fixedString != "\uFFFD");
Assert.AreEqual(false, "\uFFFD" == fixedString);
Assert.AreEqual(true, "\uFFFD" != fixedString);
}
[Test]
public void FixedStringNSizeOf()
{
Assert.AreEqual(UnsafeUtility.SizeOf<FixedStringN>(), 128);
}
[TestCase("red", new byte[] { 3, 0, 114, 101, 100, 0 }, TestName = "{m}(red)")]
[TestCase("紅色", new byte[] { 6, 0, 231, 180, 133, 232, 137, 178, 0 }, TestName = "{m}(Chinese-Red)")]
[TestCase("црвена", new byte[] { 12, 0, 209, 134, 209, 128, 208, 178, 208, 181, 208, 189, 208, 176, 0 }, TestName = "{m}(Serbian-Red)")]
[TestCase("George Washington", new byte[] { 17, 0, 71, 101, 111, 114, 103, 101, 32, 87, 97, 115, 104, 105, 110, 103, 116, 111, 110, 0 }, TestName = "{m}(George Washington)")]
[TestCase("村上春樹", new byte[] { 12, 0, 230, 157, 145, 228, 184, 138, 230, 152, 165, 230, 168, 185, 0 }, TestName = "{m}(HarukiMurakami)")]
[TestCase("🌕🌖🌗🌘🌑🌒🌓🌔", new byte[] { 32, 0, 240, 159, 140, 149, 240, 159, 140, 150, 240, 159, 140, 151, 240, 159, 140, 152, 240, 159, 140, 145, 240, 159, 140, 146, 240, 159, 140, 147, 240, 159, 140, 148, 0 }, TestName = "{m}(MoonPhases)")]
[TestCase("𝒞𝒯𝒮𝒟𝒳𝒩𝒫𝒢", new byte[] { 32, 0, 240, 157, 146, 158, 240, 157, 146, 175, 240, 157, 146, 174, 240, 157, 146, 159, 240, 157, 146, 179, 240, 157, 146, 169, 240, 157, 146, 171, 240, 157, 146, 162, 0 }, TestName = "{m}(Cursive)")]
[TestCase("로마는 하루아침에 이루어진 것이 아니다", new byte[] { 55, 0, 235, 161, 156, 235, 167, 136, 235, 138, 148, 32, 237, 149, 152, 235, 163, 168, 236, 149, 132, 236, 185, 168, 236, 151, 144, 32, 236, 157, 180, 235, 163, 168, 236, 150, 180, 236, 167, 132, 32, 234, 178, 131, 236, 157, 180, 32, 236, 149, 132, 235, 139, 136, 235, 139, 164, 0 }, TestName = "{m}(Korean - Rome was not made overnight)")]
[TestCase("Лако ти је плитку воду замутити и будалу наљутити", new byte[] { 90, 0, 208, 155, 208, 176, 208, 186, 208, 190, 32, 209, 130, 208, 184, 32, 209, 152, 208, 181, 32, 208, 191, 208, 187, 208, 184, 209, 130, 208, 186, 209, 131, 32, 208, 178, 208, 190, 208, 180, 209, 131, 32, 208, 183, 208, 176, 208, 188, 209, 131, 209, 130, 208, 184, 209, 130, 208, 184, 32, 208, 184, 32, 208, 177, 209, 131, 208, 180, 208, 176, 208, 187, 209, 131, 32, 208, 189, 208, 176, 209, 153, 209, 131, 209, 130, 208, 184, 209, 130, 208, 184, 0 }, TestName = "{m}(Serbian-Proverb)")]
[TestCase("Үнэн үг хэлсэн хүнд ноёд өстэй, үхэр унасан хүнд ноход өстэй.", new byte[] { 110, 0, 210, 174, 208, 189, 209, 141, 208, 189, 32, 210, 175, 208, 179, 32, 209, 133, 209, 141, 208, 187, 209, 129, 209, 141, 208, 189, 32, 209, 133, 210, 175, 208, 189, 208, 180, 32, 208, 189, 208, 190, 209, 145, 208, 180, 32, 211, 169, 209, 129, 209, 130, 209, 141, 208, 185, 44, 32, 210, 175, 209, 133, 209, 141, 209, 128, 32, 209, 131, 208, 189, 208, 176, 209, 129, 208, 176, 208, 189, 32, 209, 133, 210, 175, 208, 189, 208, 180, 32, 208, 189, 208, 190, 209, 133, 208, 190, 208, 180, 32, 211, 169, 209, 129, 209, 130, 209, 141, 208, 185, 46, 0 }, TestName = "{m}(Mongolian-Proverb1)")]
unsafe public void FixedStringNLayout(String a, byte[] expected)
{
fixed (byte* expectedBytes = expected)
{
FixedStringN actual = a;
byte* actualBytes = (byte*)&actual;
Assert.AreEqual(0, UnsafeUtility.MemCmp(expectedBytes, actualBytes, expected.Length));
}
}
[TestCase("red", 'r', 'd')]
[TestCase("紅色", '紅', '色')]
[TestCase("црвена", 'ц', 'а')]
[TestCase("George Washington", 'G', 'n')]
[TestCase("村上春樹", '村', '樹')]
[TestCase("로마는 하루아침에 이루어진 것이 아니다", '로', '다')]
[TestCase("Лако ти је плитку воду замутити и будалу наљутити", 'Л', 'и')]
[TestCase("Үнэн үг хэлсэн хүнд ноёд өстэй, үхэр унасан хүнд ноход өстэй.", 'Ү', '.')]
public void FixedStringStartsEndsWithChar(String a, char starts, char ends)
{
FixedStringN actual = a;
Assert.True(actual.StartsWith(starts));
Assert.True(actual.EndsWith(ends));
}
[TestCase("red", "r", "d")]
[TestCase("紅色", "紅", "色")]
[TestCase("црвена", "црв", "ена")]
[TestCase("George Washington", "George", "Washington")]
[TestCase("村上春樹", "村上", "春樹")]
[TestCase("🌕🌖🌗🌘🌑🌒🌓🌔", "🌕🌖🌗", "🌒🌓🌔")]
[TestCase("𝒞𝒯𝒮𝒟𝒳𝒩𝒫𝒢", "𝒞𝒯𝒮", "𝒩𝒫𝒢")]
[TestCase("로마는 하루아침에 이루어진 것이 아니다", "로마는", "아니다")]
[TestCase("Лако ти је плитку воду замутити и будалу наљутити", "Лако", "наљутити")]
[TestCase("Үнэн үг хэлсэн хүнд ноёд өстэй, үхэр унасан хүнд ноход өстэй.", "Үнэн", "өстэй.")]
public void FixedStringStartsEndsWithString(String a, String starts, String ends)
{
FixedStringN actual = a;
Assert.True(actual.StartsWith((FixedStringN)starts));
Assert.True(actual.EndsWith((FixedStringN)ends));
}
[TestCase("red ", ' ', "red ", "red", "red")]
[TestCase(" red ", ' ', "red ", " red", "red")]
[TestCase(" ", ' ', "", "", "")]
public void FixedStringTrimStart(String a, char trim, String expectedStart, String expectedEnd, String expected)
{
FixedStringN actual = a;
Assert.AreEqual(expectedStart, actual.TrimStart());
Assert.AreEqual(expectedEnd, actual.TrimEnd());
Assert.AreEqual(expected, actual.Trim());
}
[TestCase(" red ", "ed ", " red", "ed")]
[TestCase("црвена", "црвена", "црвена", "црвена")]
[TestCase(" ", "", "", "")]
public void FixedStringTrimStartWithRunes(String a, String expectedStart, String expectedEnd, String expected)
{
FixedStringN actual = a;
Assert.AreEqual(expectedStart, actual.TrimStart(new Unicode.Rune[]{ ' ', 'r'}));
Assert.AreEqual(expectedEnd, actual.TrimEnd(new Unicode.Rune[] { ' ', 'r' }));
Assert.AreEqual(expected, actual.Trim(new Unicode.Rune[] { ' ', 'r' }));
}
[TestCase("Red", "red", "RED")]
[TestCase("црвена", "црвена", "црвена")]
[TestCase(" ", " ", " ")]
public void FixedStringToLowerUpperAscii(String a, String expectedLower, String expectedUpped)
{
FixedStringN actual = a;
Assert.AreEqual(expectedLower, actual.ToLowerAscii());
Assert.AreEqual(expectedUpped, actual.ToUpperAscii());
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6936a9e20fa254433b9c06424258e80c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,90 @@
using System;
using NUnit.Framework;
using Unity.Collections.Tests;
internal class GcAllocRecorderTest
{
[Test]
public void TestBeginEnd()
{
GCAllocRecorder.BeginNoGCAlloc();
GCAllocRecorder.EndNoGCAlloc();
}
// NOTE: Causing GC allocation with new requires an unused variable
#pragma warning disable 219
[Test]
public void TestNoAlloc()
{
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
var p = new int();
});
}
[Test]
public void TestAlloc()
{
Assert.Throws<AssertionException>(() =>
{
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
var p = new int[5];
});
});
}
#pragma warning restore 219
}
namespace Unity.Collections.Tests
{
internal static class GCAllocRecorder
{
static UnityEngine.Profiling.Recorder AllocRecorder;
static GCAllocRecorder()
{
AllocRecorder = UnityEngine.Profiling.Recorder.Get("GC.Alloc");
}
public static int CountGCAllocs(Action action)
{
AllocRecorder.FilterToCurrentThread();
AllocRecorder.enabled = false;
AllocRecorder.enabled = true;
action();
AllocRecorder.enabled = false;
return AllocRecorder.sampleBlockCount;
}
// NOTE: action is called twice to warmup any GC allocs that can happen due to static constructors etc.
public static void ValidateNoGCAllocs(Action action)
{
// warmup
CountGCAllocs(action);
// actual test
var count = CountGCAllocs(action);
if (count != 0)
throw new AssertionException($"Expected 0 GC allocations but there were {count}");
}
public static void BeginNoGCAlloc()
{
AllocRecorder.FilterToCurrentThread();
AllocRecorder.enabled = false;
AllocRecorder.enabled = true;
}
public static void EndNoGCAlloc()
{
AllocRecorder.enabled = false;
int count = AllocRecorder.sampleBlockCount;
if (count != 0)
throw new AssertionException($"Expected 0 GC allocations but there were {count}");
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 58905de7f0380435aa51db1472b48ca8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 41c1d83e4d34d6247b6e021d9053b364
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 15816ede41b819e439cb53115efc62b0
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,189 @@
using System;
using NUnit.Framework;
using UnityEngine.Scripting;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
using Unity.Burst;
using System.Diagnostics;
namespace Unity.Jobs.Tests.ManagedJobs
{
internal class BurstScheduleTests : JobTestsFixtureBasic
{
[BurstDiscard]
static public void TestBurstCompiled(ref bool falseIfNot)
{
falseIfNot = false;
}
[BurstCompile(CompileSynchronously = true)]
static public bool IsBurstEnabled()
{
bool burstCompiled = true;
TestBurstCompiled(ref burstCompiled);
return burstCompiled;
}
[BurstCompile(CompileSynchronously = true)]
struct SimpleIJobParallelForDefer : IJobParallelForDefer
{
public NativeArray<int> executed;
public void Execute(int index)
{
executed[0] = 1;
}
[BurstCompile(CompileSynchronously = true)]
public static int TestBurstScheduleJob(JobRunType runType, ref RewindableAllocator allocator)
{
bool burstCompiled = true;
TestBurstCompiled(ref burstCompiled);
var dummyList = new NativeList<int>(Allocator.Temp);
dummyList.Add(5);
var job = new SimpleIJobParallelForDefer() { executed = new NativeArray<int>(1, allocator.ToAllocator) };
switch (runType)
{
case JobRunType.Schedule: job.Schedule(dummyList, 1).Complete(); break;
case JobRunType.ScheduleByRef: job.ScheduleByRef(dummyList, 1).Complete(); break;
}
dummyList.Dispose();
int ret = (burstCompiled ? 2 : 0) + job.executed[0];
job.executed.Dispose();
return ret;
}
}
[TestCase(JobRunType.Schedule)]
[TestCase(JobRunType.ScheduleByRef)]
public unsafe void IJobParallelForDefer_Jobs_FromBurst(JobRunType runType)
{
if (!IsBurstEnabled())
return;
int ret = SimpleIJobParallelForDefer.TestBurstScheduleJob(runType, ref RwdAllocator);
Assert.IsTrue((ret & 2) != 0, "Job schedule site not burst compiled");
Assert.IsTrue((ret & 1) != 0, "Job with burst compiled schedule site didn't execute");
}
[BurstCompile(CompileSynchronously = true)]
struct SimpleIJobParallelForBatch : IJobParallelForBatch
{
public NativeArray<int> executed;
public void Execute(int startIndex, int count)
{
executed[0] = 1;
}
[BurstCompile(CompileSynchronously = true)]
public static int TestBurstScheduleJob(JobRunType runType, ref RewindableAllocator allocator)
{
bool burstCompiled = true;
TestBurstCompiled(ref burstCompiled);
var job = new SimpleIJobParallelForBatch() { executed = new NativeArray<int>(1, allocator.ToAllocator) };
switch (runType)
{
case JobRunType.Schedule: job.ScheduleBatch(1, 1).Complete(); break;
case JobRunType.ScheduleByRef: job.ScheduleBatchByRef(1, 1).Complete(); break;
case JobRunType.Run: job.RunBatch(1); break;
case JobRunType.RunByRef: job.RunBatchByRef(1); break;
}
int ret = (burstCompiled ? 2 : 0) + job.executed[0];
job.executed.Dispose();
return ret;
}
}
[TestCase(JobRunType.Schedule)]
[TestCase(JobRunType.ScheduleByRef)]
[TestCase(JobRunType.Run)]
[TestCase(JobRunType.RunByRef)]
public unsafe void IJobParallelForBatch_Jobs_FromBurst(JobRunType runType)
{
if (!IsBurstEnabled())
return;
int ret = SimpleIJobParallelForBatch.TestBurstScheduleJob(runType, ref RwdAllocator);
Assert.IsTrue((ret & 2) != 0, "Job schedule site not burst compiled");
Assert.IsTrue((ret & 1) != 0, "Job with burst compiled schedule site didn't execute");
}
[BurstCompile(CompileSynchronously = true)]
struct SimpleIJobFilter : IJobFilter
{
public NativeArray<int> executed;
public bool Execute(int index)
{
executed[0] = 1;
return false;
}
[BurstCompile(CompileSynchronously = true)]
public static int TestBurstScheduleJob(JobRunType runType, ref RewindableAllocator allocator)
{
bool burstCompiled = true;
TestBurstCompiled(ref burstCompiled);
var dummyList = new NativeList<int>(Allocator.Temp);
dummyList.Add(5);
var job = new SimpleIJobFilter() { executed = new NativeArray<int>(1, allocator.ToAllocator) };
switch (runType)
{
case JobRunType.Schedule:
job.ScheduleFilter(dummyList).Complete();
job.ScheduleAppend(dummyList, 1).Complete();
break;
case JobRunType.ScheduleByRef:
job.ScheduleFilterByRef(dummyList).Complete();
job.ScheduleAppendByRef(dummyList, 1).Complete();
break;
case JobRunType.Run:
job.RunFilter(dummyList);
job.RunAppend(dummyList, 1);
break;
case JobRunType.RunByRef:
job.RunFilterByRef(dummyList);
job.RunAppendByRef(dummyList, 1);
break;
}
dummyList.Dispose();
int ret = (burstCompiled ? 2 : 0) + job.executed[0];
job.executed.Dispose();
return ret;
}
}
[TestCase(JobRunType.Schedule)]
[TestCase(JobRunType.ScheduleByRef)]
[TestCase(JobRunType.Run)]
[TestCase(JobRunType.RunByRef)]
public unsafe void IJobFilter_Jobs_FromBurst(JobRunType runType)
{
if (!IsBurstEnabled())
return;
int ret = SimpleIJobFilter.TestBurstScheduleJob(runType, ref RwdAllocator);
Assert.IsTrue((ret & 2) != 0, "Job schedule site not burst compiled");
Assert.IsTrue((ret & 1) != 0, "Job with burst compiled schedule site didn't execute");
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f93f25e0a74e18d4d850b4f26fb47d7d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a3b679e57d7ee1247b545d72b8dc55d5
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6cc3f6b7ae8704a4687059d1a42efa95
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,16 @@
{
"name": "Unity.Collections.Tests.CoreCLR.InternalJobNestedPrivate",
"rootNamespace": "",
"references": [
"GUID:e0cd26848372d4e5c891c569017e11f1"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 298bc460cd9598745b3b942e70574db0
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,20 @@
using System;
using Unity.Jobs;
namespace Unity.Collections.Tests.CoreCLR.TestJobs
{
public class InternalJobNestedPrivateContainerClass
{
// Expose the Type so we can check for it in the test
public static Type TestJobType = typeof(PrivateInternalContainerClass.PrivateNestedInternalTestJob);
private class PrivateInternalContainerClass
{
internal struct PrivateNestedInternalTestJob : IJob
{
public void Execute()
{ }
}
}
}
}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1d5c25ccdf252e448adb4a314e2651ce
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,17 @@
using System;
using Unity.Jobs;
namespace Unity.Collections.Tests.CoreCLR.TestJobs
{
public class NestedPrivateTestJobContainterClass
{
// Expose the Type so we can check for it in the test
public static Type TestJobType = typeof(NestedPrivateTestJob);
struct NestedPrivateTestJob : IJob
{
public void Execute()
{}
}
}
}
@@ -0,0 +1,16 @@
{
"name": "Unity.Collections.Tests.CoreCLR.PrivateJobNested",
"rootNamespace": "",
"references": [
"GUID:e0cd26848372d4e5c891c569017e11f1"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: ef6b0e23948ec0543b9874c56d460b41
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2fd08ee07a24dee45a29e2dd37666eea
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,17 @@
using System;
using Unity.Jobs;
namespace Unity.Collections.Tests.CoreCLR.TestJobs
{
public class NestedProtectedTestJobContainterClass
{
// Expose the Type so we can check for it in the test
public static Type TestJobType = typeof(NestedProtectedTestJob);
protected struct NestedProtectedTestJob : IJob
{
public void Execute()
{}
}
}
}
@@ -0,0 +1,16 @@
{
"name": "Unity.Collections.Tests.CoreCLR.ProtectedJobNested",
"rootNamespace": "",
"references": [
"GUID:e0cd26848372d4e5c891c569017e11f1"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 309bb9a8839ee1340af783c0cbfb01bc
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5472e9c13b0d5074d9d9aa6ff60437a8
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,16 @@
{
"name": "Unity.Collections.Tests.CoreCLR.PublicJobPrivateGeneric",
"rootNamespace": "",
"references": [
"GUID:e0cd26848372d4e5c891c569017e11f1"
],
"includePlatforms": [],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f4677a7cb8f4ae241973648755879bfc
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,35 @@
using System;
using Unity.Jobs;
namespace Unity.Collections.Tests.CoreCLR.TestJobs
{
public class NestedPublicGenericTestJobContainterClass
{
// Expose the Type so we can check for it in the test
public static Type TestJobType = typeof(NestedPublicGenericTestJob<PrivateExecutor>);
public interface IExecutor
{
public abstract void Execute();
}
public struct NestedPublicGenericTestJob<TExecutor> : IJob where TExecutor : IExecutor
{
public TExecutor executor;
public void Execute()
{
executor.Execute();
}
}
struct PrivateExecutor : IExecutor
{
public void Execute(){ }
}
public void DeclareTestInstance()
{
var testJob = new NestedPublicGenericTestJob<PrivateExecutor>();
testJob.Execute();
}
}
}
@@ -0,0 +1,156 @@
using NUnit.Framework;
using System;
using Unity.Jobs;
using Unity.Collections;
using Unity.Jobs.Tests.ManagedJobs;
#pragma warning disable 0219
internal class ParallelFilterJobTests : JobTestsFixtureBasic
{
struct NativeListAddMod7Job : IJob
{
NativeList<int> list;
int produceCount;
public NativeListAddMod7Job(NativeList<int> list, int produceCount)
{
this.list = list;
this.produceCount = produceCount;
}
public void Execute()
{
for (int index = 0; index != produceCount; index++)
{
if (index % 7 == 0)
list.Add(index);
}
}
}
struct FilterMod7Job : IJobFilter
{
public bool Execute(int index)
{
return index % 7 == 0;
}
}
struct FilterAllJob : IJobFilter
{
public bool Execute(int index)
{
return true;
}
}
[Test]
public void AddElementForEach([Values] bool userFilterJob)
{
var list = new NativeList<int>(0, RwdAllocator.ToAllocator);
list.Add(-1);
list.Add(-2);
if (userFilterJob)
{
var job = new FilterMod7Job();
job.ScheduleAppend(list, 1000).Complete();
}
else
{
var job = new NativeListAddMod7Job(list, 1000);
job.Schedule().Complete();
}
int counter = 2;
for (int i = 0; i != 1000; i++)
{
if (i % 7 == 0)
{
Assert.AreEqual(i, list[counter]);
counter++;
}
}
Assert.AreEqual(-1, list[0]);
Assert.AreEqual(-2, list[1]);
Assert.AreEqual(counter, list.Length);
}
[Test]
public void FilterProduceChained()
{
var list = new NativeList<int>(3, RwdAllocator.ToAllocator);
var jobHandle = new FilterMod7Job().ScheduleAppend(list, 14);
jobHandle = new FilterAllJob().ScheduleAppend(list, 2, jobHandle);
jobHandle.Complete();
Assert.AreEqual(0, list[0]);
Assert.AreEqual(7, list[1]);
Assert.AreEqual(0, list[2]);
Assert.AreEqual(1, list[3]);
Assert.AreEqual(4, list.Length);
}
[Test]
public void FilterAppendChained()
{
var list = new NativeList<int>(3, RwdAllocator.ToAllocator);
var jobHandle = new FilterMod7Job().ScheduleAppend(list, 14);
jobHandle = new FilterAllJob().ScheduleAppend(list, 2, jobHandle);
jobHandle.Complete();
Assert.AreEqual(0, list[0]);
Assert.AreEqual(7, list[1]);
Assert.AreEqual(0, list[2]);
Assert.AreEqual(1, list[3]);
Assert.AreEqual(4, list.Length);
}
[Test]
public void FilterPreviousChained()
{
var list = new NativeList<int>(3, RwdAllocator.ToAllocator);
var jobHandle = new FilterAllJob().ScheduleAppend(list, 14);
jobHandle = new FilterMod7Job().ScheduleFilter(list, jobHandle);
jobHandle.Complete();
Assert.AreEqual(2, list.Length);
Assert.AreEqual(0, list[0]);
Assert.AreEqual(7, list[1]);
}
struct MinMaxRestrictionJob : IJobFilter
{
public NativeArray<float> array;
public MinMaxRestrictionJob(NativeArray<float> array) { this.array = array; }
public bool Execute(int index)
{
array[index] = 5;
var localArray = array;
Assert.Throws<IndexOutOfRangeException>(() => { localArray[50] = 5; });
return true;
}
}
[Test]
[Ignore("DOTS-1959 Currently thats legal, but only because filter jobs aren't implemented as parallel for right now...")]
public void AccessingWritable()
{
var list = new NativeList<int>(0, Allocator.Persistent);
var array = new NativeArray<float>(51, Allocator.Persistent);
var jobHandle = new MinMaxRestrictionJob(array).ScheduleAppend(list, 50);
new MinMaxRestrictionJob(array).ScheduleFilter(list, jobHandle).Complete();
Assert.AreEqual(50, list.Length);
list.Dispose();
array.Dispose();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 551e05d9d28513c4fb893599f9237377
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,85 @@
using System;
using NUnit.Framework;
using Unity.Collections;
using Unity.Jobs;
namespace Unity.Jobs.Tests.ManagedJobs
{
internal class JobStressTests : JobTestsFixture
{
struct JobSetIndexValue : IJobParallelFor
{
public NativeArray<int> value;
public void Execute(int index)
{
value[index] = index;
}
}
[Test]
public void StressTestParallelFor()
{
StressTestParallelForIterations(1, 5000);
}
public void StressTestParallelForIterations(int amount, int amountOfData)
{
for (var k = 0; k != amount; k++)
{
var len = UnityEngine.Random.Range(1, amountOfData);
JobSetIndexValue job1;
job1.value = CollectionHelper.CreateNativeArray<int>(len, RwdAllocator.ToAllocator);
JobSetIndexValue job2;
job2.value = CollectionHelper.CreateNativeArray<int>(len, RwdAllocator.ToAllocator);
var job1Handle = job1.Schedule(len, UnityEngine.Random.Range(1, 1024));
var job2Handle = job2.Schedule(len, UnityEngine.Random.Range(1, 1024));
job2Handle.Complete();
job1Handle.Complete();
for (var i = 0; i < len; i++)
{
Assert.AreEqual(i, job1.value[i]);
Assert.AreEqual(i, job2.value[i]);
}
}
}
struct JobSetValue : IJob
{
public int expected;
public NativeArray<int> value;
public void Execute()
{
value[0] = value[0] + 1;
}
}
[Test]
public void DeepDependencyChain()
{
var array = new NativeArray<int>(1, Allocator.Persistent);
var jobHandle = new JobHandle();
const int depth = 10000;
for (var i = 0; i < depth; i++)
{
var job = new JobSetValue
{
value = array,
expected = i
};
jobHandle = job.Schedule(jobHandle);
}
jobHandle.Complete();
Assert.AreEqual(depth, array[0]);
array.Dispose();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 36d0e1be06be93249a0ffa0c8356e69e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,736 @@
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
using Unity.Burst;
using Unity.Collections.Tests;
using UnityEngine;
[assembly: RegisterGenericJobType(typeof(Unity.Jobs.Tests.ManagedJobs.MyGenericJobDefer<int>))]
[assembly: RegisterGenericJobType(typeof(Unity.Jobs.Tests.ManagedJobs.MyGenericJobDefer<double>))]
[assembly: RegisterGenericJobType(typeof(Unity.Jobs.Tests.ManagedJobs.MyGenericJobDefer<float>))]
[assembly: RegisterGenericJobType(typeof(Unity.Jobs.Tests.ManagedJobs.GenericContainerJobDefer<NativeList<int>, int>))]
namespace Unity.Jobs.Tests.ManagedJobs
{
internal enum JobRunType
{
Schedule,
ScheduleByRef,
Run,
RunByRef,
}
[JobProducerType(typeof(IJobTestExtensions.JobTestProducer<>))]
internal interface IJobTest
{
void Execute();
}
internal interface IJobTestInherit : IJob
{
}
internal static class IJobTestExtensions
{
internal struct JobTestWrapper<T> where T : struct
{
internal T JobData;
[NativeDisableContainerSafetyRestriction]
internal NativeArray<byte> ProducerResourceToClean;
}
internal struct JobTestProducer<T> where T : struct, IJobTest
{
internal static readonly SharedStatic<IntPtr> s_JobReflectionData = SharedStatic<IntPtr>.GetOrCreate<JobTestProducer<T>>();
[BurstDiscard]
internal static void Initialize()
{
if (s_JobReflectionData.Data == IntPtr.Zero)
s_JobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(JobTestWrapper<T>), typeof(T), (ExecuteJobFunction)Execute);
}
public delegate void ExecuteJobFunction(ref JobTestWrapper<T> jobWrapper, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex);
public unsafe static void Execute(ref JobTestWrapper<T> jobWrapper, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex)
{
jobWrapper.JobData.Execute();
}
}
public static void EarlyJobInit<T>()
where T : struct, IJobTest
{
JobTestProducer<T>.Initialize();
}
static IntPtr GetReflectionData<T>()
where T : struct, IJobTest
{
JobTestProducer<T>.Initialize();
var reflectionData = JobTestProducer<T>.s_JobReflectionData.Data;
CollectionHelper.CheckReflectionDataCorrect<T>(reflectionData);
return reflectionData;
}
public static unsafe JobHandle ScheduleTest<T>(this T jobData, NativeArray<byte> dataForProducer, JobHandle dependsOn = new JobHandle()) where T : struct, IJobTest
{
JobTestWrapper<T> jobTestWrapper = new JobTestWrapper<T>
{
JobData = jobData,
ProducerResourceToClean = dataForProducer
};
var scheduleParams = new JobsUtility.JobScheduleParameters(
UnsafeUtility.AddressOf(ref jobTestWrapper),
GetReflectionData<T>(),
dependsOn,
ScheduleMode.Parallel
);
return JobsUtility.Schedule(ref scheduleParams);
}
}
[JobProducerType(typeof(IJobTestInheritProducerExtensions.JobTestProducer<>))]
internal interface IJobTestInheritWithProducer : IJob
{
void Execute(bool empty);
}
internal static class IJobTestInheritProducerExtensions
{
internal struct JobTestWrapper<T> where T : struct
{
internal T JobData;
internal byte Empty;
}
internal struct JobTestProducer<T> where T : struct, IJobTestInheritWithProducer
{
internal static readonly SharedStatic<IntPtr> jobReflectionData = SharedStatic<IntPtr>.GetOrCreate<JobTestProducer<T>>();
[BurstDiscard]
internal static void Initialize()
{
if (jobReflectionData.Data == IntPtr.Zero)
jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(JobTestWrapper<T>), typeof(T), (ExecuteJobFunction)Execute);
}
public delegate void ExecuteJobFunction(ref JobTestWrapper<T> jobWrapper, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex);
public unsafe static void Execute(ref JobTestWrapper<T> jobWrapper, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex)
{
jobWrapper.JobData.Execute(jobWrapper.Empty != 0);
}
}
public static void EarlyJobInit<T>()
where T : struct, IJobTestInheritWithProducer
{
JobTestProducer<T>.Initialize();
}
static IntPtr GetReflectionData<T>()
where T : struct, IJobTestInheritWithProducer
{
JobTestProducer<T>.Initialize();
var reflectionData = JobTestProducer<T>.jobReflectionData.Data;
CollectionHelper.CheckReflectionDataCorrect<T>(reflectionData);
return reflectionData;
}
unsafe public static JobHandle Schedule<T>(this T jobData, bool empty, JobHandle dependsOn = new JobHandle()) where T : struct, IJobTestInheritWithProducer
{
JobTestWrapper<T> jobTestWrapper = new JobTestWrapper<T>
{
JobData = jobData,
Empty = (byte)(empty ? 1 : 0)
};
var scheduleParams = new JobsUtility.JobScheduleParameters(
UnsafeUtility.AddressOf(ref jobTestWrapper),
GetReflectionData<T>(),
dependsOn,
ScheduleMode.Parallel
);
return JobsUtility.Schedule(ref scheduleParams);
}
}
internal struct MyGenericResizeJob<T> : IJob where T : unmanaged
{
public int m_ListLength;
public NativeList<T> m_GenericList;
public void Execute()
{
m_GenericList.Resize(m_ListLength, NativeArrayOptions.UninitializedMemory);
}
}
internal struct MyGenericJobDefer<T> : IJobParallelForDefer where T: unmanaged
{
public T m_Value;
[NativeDisableParallelForRestriction]
public NativeList<T> m_GenericList;
public void Execute(int index)
{
m_GenericList[index] = m_Value;
}
}
internal struct GenericContainerResizeJob<T, U> : IJob
where T : unmanaged, INativeList<U>
where U : unmanaged
{
public int m_ListLength;
public T m_GenericList;
public void Execute()
{
m_GenericList.Length = m_ListLength;
}
}
internal struct GenericContainerJobDefer<T, U> : IJobParallelForDefer
where T : unmanaged, INativeList<U>
where U : unmanaged
{
public U m_Value;
[NativeDisableParallelForRestriction]
public T m_GenericList;
public void Execute(int index)
{
m_GenericList[index] = m_Value;
}
}
internal class JobTests : JobTestsFixture
{
public void ScheduleGenericContainerJob<T, U>(T container, U value)
where T : unmanaged, INativeList<U>
where U : unmanaged
{
var j0 = new GenericContainerResizeJob<T, U>();
var length = 5;
j0.m_ListLength = length;
j0.m_GenericList = container;
var handle0 = j0.Schedule();
var j1 = new GenericContainerJobDefer<T, U>();
j1.m_Value = value;
j1.m_GenericList = j0.m_GenericList;
INativeList<U> iList = j0.m_GenericList;
j1.Schedule((NativeList<U>)iList, 1, handle0).Complete();
Assert.AreEqual(length, j1.m_GenericList.Length);
for (int i = 0; i != j1.m_GenericList.Length; i++)
Assert.AreEqual(value, j1.m_GenericList[i]);
}
[Test]
public void ValidateContainerSafetyInGenericJob_ContainerIsGenericParameter()
{
var list = new NativeList<int>(1, RwdAllocator.ToAllocator);
ScheduleGenericContainerJob(list, 5);
}
public void GenericScheduleJobPair<T>(T value) where T : unmanaged
{
var j0 = new MyGenericResizeJob<T>();
var length = 5;
j0.m_ListLength = length;
j0.m_GenericList = new NativeList<T>(1, RwdAllocator.ToAllocator);
var handle0 = j0.Schedule();
var j1 = new MyGenericJobDefer<T>();
j1.m_Value = value;
j1.m_GenericList = j0.m_GenericList;
j1.Schedule(j0.m_GenericList, 1, handle0).Complete();
Assert.AreEqual(length, j1.m_GenericList.Length);
for (int i = 0; i != j1.m_GenericList.Length; i++)
Assert.AreEqual(value, j1.m_GenericList[i]);
}
[Test]
public void ScheduleGenericJobPairFloat()
{
GenericScheduleJobPair(10f);
}
[Test]
public void ScheduleGenericJobPairDouble()
{
GenericScheduleJobPair<double>(10.0);
}
[Test]
public void ScheduleGenericJobPairInt()
{
GenericScheduleJobPair(20);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
[Test]
public void SchedulingGenericJobUnsafelyThrows()
{
var j0 = new MyGenericResizeJob<int>();
var length = 5;
j0.m_ListLength = length;
j0.m_GenericList = new NativeList<int>(1, RwdAllocator.ToAllocator);
var handle0 = j0.Schedule();
var j1 = new MyGenericJobDefer<int>();
j1.m_Value = 6;
j1.m_GenericList = j0.m_GenericList;
Assert.Throws<InvalidOperationException>(()=>j1.Schedule(j0.m_GenericList, 1).Complete());
handle0.Complete();
}
#endif
struct DontReferenceThisTypeOutsideOfThisTest { public int v; }
[Test]
[TestRequiresCollectionChecks]
public void SchedulingGenericJobFromGenericContextUnsafelyThrows()
{
var list = new NativeList<DontReferenceThisTypeOutsideOfThisTest>(1, RwdAllocator.ToAllocator);
ScheduleGenericJobUnsafely(list, new DontReferenceThisTypeOutsideOfThisTest { v = 5 });
}
void ScheduleGenericJobUnsafely<T, U>(T container, U value)
where T : unmanaged, INativeList<U>
where U : unmanaged
{
var j0 = new GenericContainerResizeJob<T, U>();
var length = 5;
j0.m_ListLength = length;
j0.m_GenericList = container;
var handle0 = j0.Schedule();
var j1 = new GenericContainerJobDefer<T, U>();
j1.m_Value = value;
j1.m_GenericList = j0.m_GenericList;
INativeList<U> iList = j0.m_GenericList;
Assert.Throws<InvalidOperationException>(()=>j1.Schedule((NativeList<U>)iList, 1).Complete());
handle0.Complete(); // complete this so we can dispose the nativelist
}
/*
* these two tests used to test that a job that inherited from both IJob and IJobParallelFor would work as expected
* but that's probably crazy.
*/
/*[Test]
public void Scheduling()
{
var job = data.Schedule();
job.Complete();
ExpectOutputSumOfInput0And1();
}*/
/*[Test]
public void Scheduling_With_Dependencies()
{
data.input0 = input0;
data.input1 = input1;
data.output = output2;
var job1 = data.Schedule();
// Schedule job2 with dependency against the first job
data.input0 = output2;
data.input1 = input2;
data.output = output;
var job2 = data.Schedule(job1);
// Wait for completion
job2.Complete();
ExpectOutputSumOfInput0And1And2();
}*/
[Test]
public void ForEach_Scheduling_With_Dependencies()
{
data.input0 = input0;
data.input1 = input1;
data.output = output2;
var job1 = data.Schedule(output.Length, 1);
// Schedule job2 with dependency against the first job
data.input0 = output2;
data.input1 = input2;
data.output = output;
var job2 = data.Schedule(output.Length, 1, job1);
// Wait for completion
job2.Complete();
ExpectOutputSumOfInput0And1And2();
}
struct EmptyComputeParallelForJob : IJobParallelFor
{
public void Execute(int i)
{
}
}
[Test]
public void ForEach_Scheduling_With_Zero_Size()
{
var test = new EmptyComputeParallelForJob();
var job = test.Schedule(0, 1);
job.Complete();
}
[Test]
public void Deallocate_Temp_NativeArray_From_Job()
{
TestDeallocateNativeArrayFromJob(RwdAllocator.ToAllocator);
}
[Test]
public void Deallocate_Persistent_NativeArray_From_Job()
{
TestDeallocateNativeArrayFromJob(Allocator.Persistent);
}
private void TestDeallocateNativeArrayFromJob(Allocator label)
{
var tempNativeArray = CollectionHelper.CreateNativeArray<int>(expectedInput0, label);
var copyAndDestroyJob = new CopyAndDestroyNativeArrayParallelForJob
{
input = tempNativeArray,
output = output
};
// NativeArray can safely be accessed before scheduling
Assert.AreEqual(10, tempNativeArray.Length);
tempNativeArray[0] = tempNativeArray[0];
var job = copyAndDestroyJob.Schedule(copyAndDestroyJob.input.Length, 1);
job.Complete();
// Need to dispose because the allocator may be Allocator.Persistent.
tempNativeArray.Dispose();
Assert.AreEqual(expectedInput0, copyAndDestroyJob.output.ToArray());
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
public struct NestedDeallocateStruct
{
public NativeArray<int> input;
}
public struct TestNestedDeallocate : IJob
{
public NestedDeallocateStruct nested;
public NativeArray<int> output;
public void Execute()
{
for (int i = 0; i < nested.input.Length; ++i)
output[i] = nested.input[i];
}
}
[Test]
public void TestNestedDeallocateOnJobCompletion()
{
var tempNativeArray = CollectionHelper.CreateNativeArray<int>(10, RwdAllocator.ToAllocator);
var outNativeArray = CollectionHelper.CreateNativeArray<int>(10, RwdAllocator.ToAllocator);
for (int i = 0; i < 10; i++)
tempNativeArray[i] = i;
var job = new TestNestedDeallocate
{
nested = new NestedDeallocateStruct() { input = tempNativeArray },
output = outNativeArray
};
var handle = job.Schedule();
handle.Complete();
RwdAllocator.Rewind();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
// Ensure released safety handle indicating invalid buffer
Assert.Throws<ObjectDisposedException>(() => { AtomicSafetyHandle.CheckExistsAndThrow(NativeArrayUnsafeUtility.GetAtomicSafetyHandle(tempNativeArray)); });
Assert.Throws<ObjectDisposedException>(() => { AtomicSafetyHandle.CheckExistsAndThrow(NativeArrayUnsafeUtility.GetAtomicSafetyHandle(job.nested.input)); });
#endif
}
public struct TestJobProducerJob : IJobTest
{
public NativeArray<int> jobStructData;
public void Execute()
{
}
}
[Test]
public void TestJobProducerCleansUp()
{
var tempNativeArray = CollectionHelper.CreateNativeArray<int>(10, RwdAllocator.ToAllocator);
var tempNativeArray2 = CollectionHelper.CreateNativeArray<byte>(16, RwdAllocator.ToAllocator);
var job = new TestJobProducerJob
{
jobStructData = tempNativeArray,
};
var handle = job.ScheduleTest(tempNativeArray2);
handle.Complete();
RwdAllocator.Rewind();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
// Check job data
Assert.Throws<ObjectDisposedException>(() => { AtomicSafetyHandle.CheckExistsAndThrow(NativeArrayUnsafeUtility.GetAtomicSafetyHandle(tempNativeArray)); });
Assert.Throws<ObjectDisposedException>(() => { AtomicSafetyHandle.CheckExistsAndThrow(NativeArrayUnsafeUtility.GetAtomicSafetyHandle(job.jobStructData)); });
// Check job producer
Assert.Throws<ObjectDisposedException>(() => { AtomicSafetyHandle.CheckExistsAndThrow(NativeArrayUnsafeUtility.GetAtomicSafetyHandle(tempNativeArray2)); });
#endif
}
public struct CopyJob : IJob
{
public NativeList<int> List1;
public NativeList<int> List2;
public void Execute()
{
List1 = List2;
}
}
[Test]
public unsafe void TestContainerCopy_EnsureSafetyHandlesCopyAndDisposeProperly()
{
var list1 = new NativeList<int>(10, RwdAllocator.ToAllocator);
var list2 = new NativeList<int>(10, RwdAllocator.ToAllocator);
list1.Add(1);
list2.Add(2);
var job = new CopyJob
{
List1 = list1,
List2 = list2
};
job.Schedule().Complete();
list1.Dispose();
list2.Dispose();
}
#endif
struct LargeJobParallelForDefer : IJobParallelForDefer
{
public FixedString4096Bytes StrA;
public FixedString4096Bytes StrB;
public FixedString4096Bytes StrC;
public FixedString4096Bytes StrD;
[NativeDisableParallelForRestriction]
public NativeArray<int> TotalLengths;
[ReadOnly]
public NativeList<float> Unused; // Schedule() from NativeList.Length requires that the list be passed into the job
public void Execute(int index)
{
TotalLengths[0] = StrA.Length + StrB.Length + StrC.Length + StrD.Length;
}
}
public enum IterationCountMode
{
List, Pointer
}
[Test]
public unsafe void IJobParallelForDefer_LargeJobStruct_ScheduleRefWorks(
[Values(IterationCountMode.List, IterationCountMode.Pointer)] IterationCountMode countMode)
{
using(var lengths = CollectionHelper.CreateNativeArray<int>(1, RwdAllocator.ToAllocator))
{
var dummyList = new NativeList<float>(RwdAllocator.ToAllocator);
dummyList.Add(5.0f);
var job = new LargeJobParallelForDefer
{
StrA = "A",
StrB = "BB",
StrC = "CCC",
StrD = "DDDD",
TotalLengths = lengths,
Unused = dummyList,
};
if (countMode == IterationCountMode.List)
{
Assert.DoesNotThrow(() => job.ScheduleByRef(dummyList, 1).Complete());
}
else if (countMode == IterationCountMode.Pointer)
{
var lengthArray = CollectionHelper.CreateNativeArray<int>(1, RwdAllocator.ToAllocator);
lengthArray[0] = 1;
Assert.DoesNotThrow(() => job.ScheduleByRef((int*)lengthArray.GetUnsafePtr(), 1).Complete());
}
}
}
[BurstCompile(CompileSynchronously = true)]
public struct InheritJob : IJobTestInherit
{
public NativeList<int> List1;
public NativeList<int> List2;
public void Execute()
{
List1[0] = List2[0];
}
}
[Test]
public void InheritInterfaceJobWorks()
{
var l1 = new NativeList<int>(4, RwdAllocator.ToAllocator);
l1.Add(3);
var l2 = new NativeList<int>(4, RwdAllocator.ToAllocator);
l2.Add(17);
var job = new InheritJob { List1 = l1, List2 = l2 };
job.Schedule().Complete();
Assert.IsTrue(l1[0] == 17);
l2.Dispose();
l1.Dispose();
}
[BurstCompile(CompileSynchronously = true)]
public struct InheritWithProducerJob : IJobTestInheritWithProducer
{
public NativeList<int> List1;
public NativeList<int> List2;
public void Execute()
{
List2[0] = List1[0];
}
public void Execute(bool empty)
{
List1[0] = List2[0];
}
}
[Test]
public void InheritInterfaceWithProducerJobWorks()
{
var l1 = new NativeList<int>(4, RwdAllocator.ToAllocator);
l1.Add(3);
var l2 = new NativeList<int>(4, RwdAllocator.ToAllocator);
l2.Add(17);
var job = new InheritWithProducerJob { List1 = l1, List2 = l2 };
job.Schedule(false).Complete();
Assert.IsTrue(l1[0] == 17);
l1[0] = 3;
job.Schedule().Complete();
Assert.IsTrue(l2[0] == 3);
l2.Dispose();
l1.Dispose();
}
// EarlyJobInit is generated for all jobs in assemblies which in refrerence Unity.Collections. Depening on the jobs accesability modifier (public, private, internal)
// these generated might be inaccessable at their callsite in CreateJobReflectionData this causes issues on CoreCLR which enforces accesability correctnes at runtime.
// Here we test for those failuers. Errors are produced at script compile time (before the test runs) so we capture all the logs from startup using JobTestsLogLogger
// and check them for any errors containing known problematic job types each defined in thier own assembly since the compiler only emits one error message per assembly
static readonly Type[] k_JobsTypesToTest = { Collections.Tests.CoreCLR.TestJobs.NestedPrivateTestJobContainterClass.TestJobType,
Collections.Tests.CoreCLR.TestJobs.NestedProtectedTestJobContainterClass.TestJobType,
Collections.Tests.CoreCLR.TestJobs.NestedPublicGenericTestJobContainterClass.TestJobType,
Collections.Tests.CoreCLR.TestJobs.InternalJobNestedPrivateContainerClass.TestJobType};
[TestCaseSource(nameof(k_JobsTypesToTest))]
public void CheckGeneratedEarlyJobInitAccess(Type jobType)
{
#if !UNITY_EDITOR
JobTestsLogLogger.StopCapture();
foreach (var l in JobTestsLogLogger.logs)
{
if (l.logType == LogType.Exception)
{
Assert.False(l.message.Contains(GetFriendlyName(jobType)), $"Encountered an exception containing one of our known problematic types {GetFriendlyName(jobType)}");
}
}
#endif
}
static string GetFriendlyName(Type type)
{
if (!type.IsGenericType)
return type.FullName;
var name = type.GetGenericTypeDefinition().FullName;
name += "<";
foreach (var t in type.GetGenericArguments())
{
name += GetFriendlyName(t);
}
name += ">";
return name;
}
}
// I'm not completely convinced by this like its OK but do we need in playmode tests too its quite heavy and it gets added everywhere we probably don't want that
#if !UNITY_EDITOR
static internal class JobTestsLogLogger
{
public struct SavedLog
{
public string message;
public string callstack;
public LogType logType;
}
static List<SavedLog> _logs = new List<SavedLog>();
public static List<SavedLog> logs{ get{ return _logs; } }
static void OnLog(string condition, string stacktrace, LogType type)
{
lock (_logs)
{
_logs.Add(new SavedLog { message = "Log " + condition, callstack = stacktrace, logType = type });
}
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void InitializeEarly()
{
StartCapture();
}
public static void StartCapture()
{
Application.logMessageReceived += OnLog;
}
public static void StopCapture()
{
Application.logMessageReceived -= OnLog;
}
}
#endif
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8693443c8d9368d4b8b9f2beea09d699
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,167 @@
using NUnit.Framework;
using Unity.Collections;
using Unity.Jobs;
namespace Unity.Jobs.Tests.ManagedJobs
{
internal class JobTestsFixtureBasic
{
AllocatorHelper<RewindableAllocator> m_AllocatorHelper;
protected ref RewindableAllocator RwdAllocator => ref m_AllocatorHelper.Allocator;
[OneTimeSetUp]
public virtual void OneTimeSetUp()
{
m_AllocatorHelper = new AllocatorHelper<RewindableAllocator>(Allocator.Persistent);
m_AllocatorHelper.Allocator.Initialize(128 * 1024, true);
}
[OneTimeTearDown]
public virtual void OneTimeTearDown()
{
m_AllocatorHelper.Allocator.Dispose();
m_AllocatorHelper.Dispose();
}
[TearDown]
public void Teardown()
{
RwdAllocator.Rewind();
// This is test only behavior for determinism. Rewind twice such that all
// tests start with an allocator containing only one memory block.
RwdAllocator.Rewind();
}
}
internal class JobTestsFixture : JobTestsFixtureBasic
{
/*
* this used to test both, and maybe it should again, but we have to make GetExecuteMethod() work with
* multiple interfaces, hopefully in a non-global way
*/
public struct SumDataParallelForJob : /*IJob,*/ IJobParallelFor
{
[ReadOnly] public NativeArray<int> input0;
[ReadOnly] public NativeArray<int> input1;
public NativeArray<int> output;
/* public void Execute()
{
for (var i = 0; i < output.Length; ++i)
output[i] = input0[i] + input1[i];
}*/
public void Execute(int i)
{
output[i] = input0[i] + input1[i];
}
}
public struct CopyAndDestroyNativeArrayParallelForJob : IJobParallelFor
{
[ReadOnlyAttribute]
public NativeArray<int> input;
public NativeArray<int> output;
public void Execute(int i)
{
output[i] = input[i];
}
}
public SumDataParallelForJob data;
public int[] expectedInput0;
public NativeArray<int> input0;
public NativeArray<int> input1;
public NativeArray<int> input2;
public NativeArray<int> output;
public NativeArray<int> output2;
[SetUp]
public void Init()
{
expectedInput0 = new int[10];
input0 = new NativeArray<int>(10, Allocator.Persistent);
input1 = new NativeArray<int>(10, Allocator.Persistent);
input2 = new NativeArray<int>(10, Allocator.Persistent);
output = new NativeArray<int>(10, Allocator.Persistent);
output2 = new NativeArray<int>(10, Allocator.Persistent);
for (var i = 0; i < output.Length; i++)
{
expectedInput0[i] = i;
input0[i] = i;
input1[i] = 10 * i;
input2[i] = 100 * i;
output[i] = 0;
output2[i] = 0;
}
data.input0 = input0;
data.input1 = input1;
data.output = output;
}
public void ExpectOutputSumOfInput0And1()
{
for (var i = 0; i != output.Length; i++)
Assert.AreEqual(input0[i] + input1[i], output[i]);
}
public void ExpectOutputSumOfInput0And1And2()
{
for (var i = 0; i != output.Length; i++)
Assert.AreEqual(input0[i] + input1[i] + input2[i], output[i]);
}
[TearDown]
public void Cleanup()
{
try
{
input0.Dispose();
}
catch
{
}
try
{
input1.Dispose();
}
catch
{
}
try
{
input2.Dispose();
}
catch
{
}
try
{
output.Dispose();
}
catch
{
}
try
{
output2.Dispose();
}
catch
{
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 69135939d4cd2cf4fbecfe92b80f882a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,111 @@
using NUnit.Framework;
using Unity.Collections;
using Unity.Jobs;
namespace Unity.Jobs.Tests.ManagedJobs
{
internal class JobTests_CombineDependencies : JobTestsFixtureBasic
{
struct ArrayJob1 : IJob
{
public NativeArray<int> data;
public void Execute()
{
data[0] = data[0] + 1;
}
}
struct ArrayJob2 : IJob
{
public NativeArray<int> a;
public NativeArray<int> b;
public void Execute()
{
a[0] = a[0] + 100;
b[0] = b[0] + 100;
}
}
[Test]
public void CombineDependenciesWorks()
{
var arrayA = new NativeArray<int>(2, Allocator.Persistent);
var arrayB = new NativeArray<int>(2, Allocator.Persistent);
var jobA = new ArrayJob1 {data = arrayA};
var jobAHandle = jobA.Schedule();
var jobB = new ArrayJob1 {data = arrayB};
var jobBHandle = jobB.Schedule();
var combinedHandle = JobHandle.CombineDependencies(jobAHandle, jobBHandle);
var job2 = new ArrayJob2
{
a = arrayA,
b = arrayB
};
job2.Schedule(combinedHandle).Complete();
for (int i = 0; i < arrayA.Length; ++i)
{
Assert.AreEqual(arrayA[0], arrayB[0]);
}
arrayA.Dispose();
arrayB.Dispose();
}
public void DeepCombineDependencies(int depth, int arraySize)
{
var arrays = new NativeArray<int>[arraySize];
for (var i = 0; i < arrays.Length; i++)
{
arrays[i] = new NativeArray<int>(1, Allocator.Persistent);
arrays[i][0] = 0;
}
var handles = new NativeArray<JobHandle>(arrays.Length, Allocator.Persistent);
var previousJobHandle = new JobHandle();
for (var i = 0; i < depth; i++)
{
for (var a = 0; a != arrays.Length; a++)
{
var job = new ArrayJob1 {data = arrays[a]};
handles[a] = job.Schedule(previousJobHandle);
}
var combinedHandle = JobHandle.CombineDependencies(handles);
var job2 = new ArrayJob2
{
a = arrays[0],
b = arrays[1]
};
previousJobHandle = job2.Schedule(combinedHandle);
}
previousJobHandle.Complete();
Assert.AreEqual(100 * depth + depth, arrays[0][0]);
Assert.AreEqual(100 * depth + depth, arrays[1][0]);
for (var i = 2; i < arrays.Length; i++)
Assert.AreEqual(depth, arrays[i][0]);
for (var a = 0; a != arrays.Length; a++)
arrays[a].Dispose();
handles.Dispose();
}
[Test]
public void DeepCombineDependenciesWorks()
{
DeepCombineDependencies(5, 21);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ecbee97f2678c1747802e50945a31f1d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,200 @@
using System;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
using Unity.Jobs.Tests.ManagedJobs;
internal class NativeListDeferredArrayTests : JobTestsFixtureBasic
{
private bool JobsDebuggerWasEnabled;
struct AliasJob : IJob
{
public NativeArray<int> array;
public NativeList<int> list;
public void Execute()
{
}
}
struct SetListLengthJob : IJob
{
public int ResizeLength;
public NativeList<int> list;
public void Execute()
{
list.Resize(ResizeLength, NativeArrayOptions.UninitializedMemory);
}
}
struct SetArrayValuesJobParallel : IJobParallelForDefer
{
public NativeArray<int> array;
public void Execute(int index)
{
array[index] = array.Length;
}
}
struct GetArrayValuesJobParallel : IJobParallelForDefer
{
[ReadOnly]
public NativeArray<int> array;
public void Execute(int index)
{
}
}
struct ParallelForWithoutList : IJobParallelForDefer
{
public void Execute(int index)
{
}
}
[SetUp]
public void NativeListDeferredArrayTestsSetup()
{
// Many ECS tests will only pass if the Jobs Debugger enabled;
// force it enabled for all tests, and restore the original value at teardown.
JobsDebuggerWasEnabled = JobsUtility.JobDebuggerEnabled;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
JobsUtility.JobDebuggerEnabled = true;
#endif
}
[Test]
public void ResizedListToDeferredJobArray([Values(0, 1, 2, 3, 4, 5, 6, 42, 97, 1023)] int length)
{
var list = new NativeList<int>(RwdAllocator.ToAllocator);
var setLengthJob = new SetListLengthJob { list = list, ResizeLength = length };
var jobHandle = setLengthJob.Schedule();
var setValuesJob = new SetArrayValuesJobParallel { array = list.AsDeferredJobArray() };
setValuesJob.Schedule(list, 3, jobHandle).Complete();
Assert.AreEqual(length, list.Length);
for (int i = 0; i != list.Length; i++)
Assert.AreEqual(length, list[i]);
}
[Test]
public unsafe void DeferredParallelForFromIntPtr()
{
int length = 10;
var lengthValue = CollectionHelper.CreateNativeArray<int>(1, RwdAllocator.ToAllocator);
lengthValue[0] = length;
var array = CollectionHelper.CreateNativeArray<int>(length, RwdAllocator.ToAllocator);
var setValuesJob = new SetArrayValuesJobParallel { array = array };
setValuesJob.Schedule((int*)lengthValue.GetUnsafePtr(), 3).Complete();
for (int i = 0; i != array.Length; i++)
Assert.AreEqual(length, array[i]);
}
[Test]
public void ResizeListBeforeSchedule([Values(5)] int length)
{
var list = new NativeList<int>(RwdAllocator.ToAllocator);
var setLengthJob = new SetListLengthJob { list = list, ResizeLength = length }.Schedule();
var setValuesJob = new SetArrayValuesJobParallel { array = list.AsDeferredJobArray() };
setLengthJob.Complete();
setValuesJob.Schedule(list, 3).Complete();
Assert.AreEqual(length, list.Length);
for (int i = 0; i != list.Length; i++)
Assert.AreEqual(length, list[i]);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
[Test]
public void ResizedListToDeferredJobArray()
{
var list = new NativeList<int>(RwdAllocator.ToAllocator);
list.Add(1);
var array = list.AsDeferredJobArray();
#pragma warning disable 0219 // assigned but its value is never used
Assert.Throws<IndexOutOfRangeException>(() => { var value = array[0]; });
#pragma warning restore 0219
Assert.AreEqual(0, array.Length);
}
[Test]
public void ResizeListWhileJobIsRunning()
{
var list = new NativeList<int>(RwdAllocator.ToAllocator);
list.Resize(42, NativeArrayOptions.UninitializedMemory);
var setValuesJob = new GetArrayValuesJobParallel { array = list.AsDeferredJobArray() };
var jobHandle = setValuesJob.Schedule(list, 3);
Assert.Throws<InvalidOperationException>(() => list.Resize(1, NativeArrayOptions.UninitializedMemory));
jobHandle.Complete();
}
[Test]
public void AliasArrayThrows()
{
var list = new NativeList<int>(RwdAllocator.ToAllocator);
var aliasJob = new AliasJob { list = list, array = list.AsDeferredJobArray() };
Assert.Throws<InvalidOperationException>(() => aliasJob.Schedule());
}
[Test]
public void DeferredListMustExistInJobData()
{
var list = new NativeList<int>(RwdAllocator.ToAllocator);
var job = new ParallelForWithoutList();
Assert.Throws<InvalidOperationException>(() => job.Schedule(list, 64));
}
[Test]
public void DeferredListCantBeDeletedWhileJobIsRunning()
{
var list = new NativeList<int>(RwdAllocator.ToAllocator);
list.Resize(42, NativeArrayOptions.UninitializedMemory);
var setValuesJob = new GetArrayValuesJobParallel { array = list.AsDeferredJobArray() };
var jobHandle = setValuesJob.Schedule(list, 3);
Assert.Throws<InvalidOperationException>(() => list.Dispose());
jobHandle.Complete();
}
[Test]
public void DeferredArrayCantBeAccessedOnMainthread()
{
var list = new NativeList<int>(RwdAllocator.ToAllocator);
list.Add(1);
var defer = list.AsDeferredJobArray();
Assert.AreEqual(0, defer.Length);
Assert.Throws<IndexOutOfRangeException>(() => defer[0] = 5);
}
#endif
[TearDown]
public void TearDown()
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
JobsUtility.JobDebuggerEnabled = JobsDebuggerWasEnabled;
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5b263730bb62fa74190582398189b6f9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.Tests;
internal class ListExtensionsTests : CollectionsTestCommonBase
{
[Test]
public void ListExtensions_RemoveSwapBack_Item()
{
var list = new List<char>(new[] { 'a', 'b', 'c', 'd' });
Assert.True(list.RemoveSwapBack('b'));
CollectionAssert.AreEqual(new[] { 'a', 'd', 'c', }, list);
Assert.True(list.RemoveSwapBack('c'));
CollectionAssert.AreEqual(new[] { 'a', 'd' }, list);
Assert.False(list.RemoveSwapBack('z'));
CollectionAssert.AreEqual(new[] { 'a', 'd' }, list);
Assert.True(list.RemoveSwapBack('a'));
CollectionAssert.AreEqual(new[] { 'd' }, list);
Assert.True(list.RemoveSwapBack('d'));
CollectionAssert.IsEmpty(list);
Assert.False(list.RemoveSwapBack('d'));
CollectionAssert.IsEmpty(list);
}
[Test]
public void ListExtensions_RemoveSwapBack_Predicate()
{
var list = new List<char>(new[] { 'a', 'b', 'c', 'd' });
Assert.True(list.RemoveSwapBack(c => c == 'b'));
CollectionAssert.AreEqual(new[] { 'a', 'd', 'c', }, list);
Assert.True(list.RemoveSwapBack(c => c == 'c'));
CollectionAssert.AreEqual(new[] { 'a', 'd' }, list);
Assert.False(list.RemoveSwapBack(c => c == 'z'));
CollectionAssert.AreEqual(new[] { 'a', 'd' }, list);
Assert.True(list.RemoveSwapBack(c => c == 'a'));
CollectionAssert.AreEqual(new[] { 'd' }, list);
Assert.True(list.RemoveSwapBack(c => c == 'd'));
CollectionAssert.IsEmpty(list);
Assert.False(list.RemoveSwapBack(c => c == 'd'));
CollectionAssert.IsEmpty(list);
}
// https://unity3d.atlassian.net/browse/DOTSR-1432
[Test]
public void ListExtensions_RemoveAtSwapBack()
{
var list = new List<char>(new[] { 'a', 'b', 'c', 'd' });
list.RemoveAtSwapBack(1);
CollectionAssert.AreEqual(new[] { 'a', 'd', 'c', }, list);
list.RemoveAtSwapBack(2);
CollectionAssert.AreEqual(new[] { 'a', 'd' }, list);
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAtSwapBack(12));
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAtSwapBack(-5));
list.RemoveAtSwapBack(0);
CollectionAssert.AreEqual(new[] { 'd' }, list);
list.RemoveAtSwapBack(0);
CollectionAssert.IsEmpty(list);
Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAtSwapBack(0));
}
[Test]
public void ListExtensions_ToNativeList()
{
var list = new List<int>(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });
var native = list.ToNativeList(Allocator.Persistent);
for (int i = 0; i < native.Length; ++i)
{
Assert.AreEqual(i, native[i]);
}
native.Dispose();
}
[Test]
public void ListExtensions_ToNativeArray()
{
var list = new List<int>(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });
var native = list.ToNativeArray(Allocator.Persistent);
for (int i = 0; i < native.Length; ++i)
{
Assert.AreEqual(i, native[i]);
}
native.Dispose();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c4e229e46ae5ef544bcc4d2bd131ddab
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,575 @@
using System;
using System.Collections.Generic;
using NUnit.Framework;
using Unity.Collections;
using Unity.Collections.Tests;
using Unity.Jobs;
using Assert = FastAssert;
internal class MathTests : CollectionsTestCommonBase
{
[Test]
public void Tests()
{
Assert.AreEqual(0, CollectionHelper.Log2Floor(1));
Assert.AreEqual(1, CollectionHelper.Log2Floor(2));
Assert.AreEqual(1, CollectionHelper.Log2Floor(3));
Assert.AreEqual(2, CollectionHelper.Log2Floor(4));
Assert.AreEqual(3, CollectionHelper.Log2Floor(15));
Assert.AreEqual(4, CollectionHelper.Log2Floor(16));
Assert.AreEqual(4, CollectionHelper.Log2Floor(19));
Assert.AreEqual(30, CollectionHelper.Log2Floor(int.MaxValue));
Assert.AreEqual(16, CollectionHelper.Log2Floor(1 << 16));
Assert.AreEqual(-1, CollectionHelper.Log2Floor(0));
}
}
internal class NativeArraySortTests : CollectionsTestCommonBase
{
[Test]
public void SortNativeArray_RandomInts_ReturnSorted([Values(0, 1, 10, 1000, 10000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<int> array = new NativeArray<int>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = random.NextInt(int.MinValue, int.MaxValue);
}
array.Sort();
int min = int.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
[Test]
public void SortNativeArray_SortedInts_ReturnSorted([Values(0, 1, 10, 1000, 10000)] int size)
{
NativeArray<int> array = new NativeArray<int>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = i;
}
array.Sort();
int min = int.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
[Test]
public void SortNativeArray_RandomBytes_ReturnSorted([Values(0, 1, 10, 1000, 10000, 100000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<byte> array = new NativeArray<byte>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = (byte)random.NextInt(byte.MinValue, byte.MinValue);
}
array.Sort();
int min = int.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
[Test]
public void SortNativeArray_RandomShorts_ReturnSorted([Values(0, 1, 10, 1000, 10000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<short> array = new NativeArray<short>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = (short)random.NextInt(short.MinValue, short.MaxValue);
}
array.Sort();
int min = int.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
[Test]
public void SortNativeArray_RandomFloats_ReturnSorted([Values(0, 1, 10, 1000, 10000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<float> array = new NativeArray<float>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = (float)random.NextDouble();
}
array.Sort();
float min = float.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
struct ComparableType : IComparable<ComparableType>
{
public int value;
public int CompareTo(ComparableType other) => value.CompareTo(other.value);
}
[Test]
public void SortNativeArray_RandomComparableType_ReturnSorted([Values(0, 1, 10, 1000, 10000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<ComparableType> array = new NativeArray<ComparableType>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = new ComparableType
{
value = random.NextInt(int.MinValue, int.MaxValue)
};
}
array.Sort();
int min = int.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i.value);
min = i.value;
}
array.Dispose();
}
struct NonComparableType
{
public int value;
}
struct NonComparableTypeComparator : IComparer<NonComparableType>
{
public int Compare(NonComparableType lhs, NonComparableType rhs)
{
return lhs.value.CompareTo(rhs.value);
}
}
[Test]
public void SortNativeArray_RandomNonComparableType_ReturnSorted([Values(0, 1, 10, 1000, 10000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<NonComparableType> array = new NativeArray<NonComparableType>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = new NonComparableType
{
value = random.NextInt(int.MinValue, int.MaxValue)
};
}
array.Sort(new NonComparableTypeComparator());
int min = int.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i.value);
min = i.value;
}
array.Dispose();
}
[Test]
public void SortNativeSlice_ReturnSorted()
{
var random = new Unity.Mathematics.Random(1);
NativeArray<int> array = new NativeArray<int>(1000, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; ++i)
{
array[i] = random.NextInt(int.MinValue, int.MaxValue);
}
var slice = new NativeSlice<int>(array, 200, 600);
slice.Sort();
int min = int.MinValue;
foreach (var i in slice)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
[Test]
public void SortNativeSlice_DoesNotChangeArrayBeyondLimits()
{
var random = new Unity.Mathematics.Random(1);
NativeArray<int> array = new NativeArray<int>(1000, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; ++i)
{
array[i] = random.NextInt(int.MinValue, int.MaxValue);
}
var backupArray = new NativeArray<int>(array.Length, Allocator.Persistent);
backupArray.CopyFrom(array);
var slice = new NativeSlice<int>(array, 200, 600);
slice.Sort();
for (var i = 0; i < 200; ++i)
{
Assert.AreEqual(backupArray[i], array[i]);
}
for (var i = 800; i < 1000; ++i)
{
Assert.AreEqual(backupArray[i], array[i]);
}
array.Dispose();
backupArray.Dispose();
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public void SortNativeSlice_WithCustomStride_ThrowsInvalidOperationException()
{
var random = new Unity.Mathematics.Random(1);
NativeArray<int> array = new NativeArray<int>(10, Allocator.Persistent);
for (int i = 0; i < array.Length; ++i)
{
array[i] = random.NextInt(int.MinValue, int.MaxValue);
}
var slice = new NativeSlice<int>(array, 2, 6);
var sliceWithCustomStride = slice.SliceWithStride<short>();
Assert.DoesNotThrow(() => slice.Sort());
Assert.Throws<InvalidOperationException>(() => sliceWithCustomStride.Sort());
array.Dispose();
}
}
internal class NativeSliceTests : CollectionsTestCommonBase
{
[Test]
public void NativeSlice_CopyTo()
{
NativeArray<int> array = new NativeArray<int>(1000, Allocator.Persistent);
for (int i = 0; i < array.Length; ++i)
{
array[i] = i;
}
var copyToArray = new int[600];
for (int i = 0; i < copyToArray.Length; ++i)
{
copyToArray[i] = 0x12345678;
}
var slice = new NativeSlice<int>(array, 200, 600);
slice.CopyTo(copyToArray);
for (var i = 0; i < 600; ++i)
{
Assert.AreEqual(copyToArray[i], array[i + 200]);
}
array.Dispose();
}
[Test]
public void NativeSlice_CopyFrom()
{
NativeArray<int> array = new NativeArray<int>(1000, Allocator.Persistent);
for (int i = 0; i < array.Length; ++i)
{
array[i] = i;
}
var copyFromArray = new int[600];
for (int i = 0; i < copyFromArray.Length; ++i)
{
copyFromArray[i] = 0x12345678;
}
var slice = new NativeSlice<int>(array, 200, 600);
slice.CopyFrom(copyFromArray);
for (var i = 0; i < 600; ++i)
{
Assert.AreEqual(slice[i], 0x12345678);
}
array.Dispose();
}
[Test]
public void SortJobNativeArray_RandomInts_ReturnSorted([Values(0, 1, 10, 1000, 10000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<int> array = new NativeArray<int>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = random.NextInt(int.MinValue, int.MaxValue);
}
array.SortJob().Schedule().Complete();
int min = int.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
[Test]
public void SortJobNativeArray_SortedInts_ReturnSorted([Values(0, 1, 10, 1000, 10000)] int size)
{
NativeArray<int> array = new NativeArray<int>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = i;
}
array.SortJob().Schedule().Complete();
int min = int.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
[Test]
public void SortJobNativeArray_RandomBytes_ReturnSorted([Values(0, 1, 10, 1000, 10000, 100000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<byte> array = new NativeArray<byte>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = (byte)random.NextInt(byte.MinValue, byte.MinValue);
}
array.SortJob().Schedule().Complete();
int min = int.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
struct DescendingComparer<T> : IComparer<T> where T : IComparable<T>
{
public int Compare(T x, T y) => y.CompareTo(x);
}
[Test]
public void SortJobNativeArray_RandomBytes_ReturnSorted_Descending([Values(0, 1, 10, 1000, 10000, 100000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<byte> array = new NativeArray<byte>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = (byte)random.NextInt(byte.MinValue, byte.MinValue);
}
array.SortJob(new DescendingComparer<byte>()).Schedule().Complete();
int max = int.MaxValue;
foreach (var i in array)
{
Assert.GreaterOrEqual(max, i);
max = i;
}
array.Dispose();
}
[Test]
public void SortJobNativeArray_RandomShorts_ReturnSorted([Values(0, 1, 10, 1000, 10000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<short> array = new NativeArray<short>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = (short)random.NextInt(short.MinValue, short.MaxValue);
}
array.SortJob().Schedule().Complete();
int min = int.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
[Test]
public void SortNativeArrayByJob_RandomShorts_ReturnSorted_Descending([Values(0, 1, 10, 1000, 10000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<short> array = new NativeArray<short>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = (short)random.NextInt(short.MinValue, short.MaxValue);
}
array.SortJob(new DescendingComparer<short>()).Schedule().Complete();
int max = int.MaxValue;
foreach (var i in array)
{
Assert.GreaterOrEqual(max, i);
max = i;
}
array.Dispose();
}
[Test]
public void SortJobNativeArray_RandomFloats_ReturnSorted([Values(0, 1, 10, 1000, 10000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<float> array = new NativeArray<float>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = (float)random.NextDouble();
}
array.SortJob().Schedule().Complete();
float min = float.MinValue;
foreach (var i in array)
{
Assert.LessOrEqual(min, i);
min = i;
}
array.Dispose();
}
[Test]
public void SortJobNativeArray_RandomFloats_ReturnSorted_Descending([Values(0, 1, 10, 1000, 10000)] int size)
{
var random = new Unity.Mathematics.Random(1);
NativeArray<float> array = new NativeArray<float>(size, Allocator.Persistent);
Assert.IsTrue(array.IsCreated);
for (int i = 0; i < array.Length; i++)
{
array[i] = (float)random.NextDouble();
}
array.SortJob(new DescendingComparer<float>()).Schedule().Complete();
float max = float.MaxValue;
foreach (var i in array)
{
Assert.GreaterOrEqual(max, i);
max = i;
}
array.Dispose();
}
struct FilterOdd : IJobFilter
{
public bool Execute(int index) => index % 2 == 0;
}
[Test]
public void SortJobNativeList_UseInPreviousJob()
{
var rng = new Unity.Mathematics.Random(123);
NativeList<int> indices = new NativeList<int>(10, Allocator.TempJob);
for (int i = 0; i < 10; i++)
{
indices.Add(rng.NextInt(100));
}
var handle = new FilterOdd().ScheduleFilter(indices);
var sortJob = indices.SortJobDefer(new DescendingComparer<int>());
handle = sortJob.Schedule(handle);
handle.Complete();
float max = float.MaxValue;
foreach (var i in indices)
{
Assert.IsTrue(0 == (i & 1));
Assert.GreaterOrEqual(max, i);
max = i;
}
indices.Dispose();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e882b40f28163514db4c9a34dbf1d6a5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,272 @@
using System;
using NUnit.Framework;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.Tests;
using Unity.Jobs;
using Unity.Collections.LowLevel.Unsafe;
internal class NativeArrayTests : CollectionsTestFixture
{
[Test]
public unsafe void NativeArray_IndexOf_Int()
{
var container = new NativeArray<int>(10, Allocator.Persistent);
container[0] = 123;
container[1] = 789;
bool r0 = false, r1 = false, r2 = false;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
r0 = -1 != container.IndexOf(456);
r1 = container.Contains(123);
r2 = container.Contains(789);
});
Assert.False(r0);
Assert.False(-1 != NativeArrayExtensions.IndexOf(container.AsReadOnlySpan(), 456));
Assert.True(r1);
Assert.True(NativeArrayExtensions.Contains(container.AsReadOnlySpan(), 123));
Assert.True(r2);
Assert.True(NativeArrayExtensions.Contains(container.AsReadOnlySpan(), 789));
container.Dispose();
}
[Test]
public unsafe void NativeArray_IndexOf_FixedString128()
{
var container = new NativeArray<FixedString128Bytes>(10, Allocator.Persistent);
container[0] = new FixedString128Bytes("123");
container[1] = new FixedString128Bytes("789");
bool r0 = false, r1 = false, r2 = false;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
r0 = -1 != container.IndexOf(new FixedString128Bytes("456"));
r1 = container.Contains(new FixedString128Bytes("123"));
r2 = container.Contains(new FixedString128Bytes("789"));
});
Assert.False(r0);
Assert.False(-1 != NativeArrayExtensions.IndexOf(container.AsReadOnlySpan(), new FixedString128Bytes("456")));
Assert.True(r1);
Assert.True(NativeArrayExtensions.Contains(container.AsReadOnlySpan(), new FixedString128Bytes("123")));
Assert.True(r2);
Assert.True(NativeArrayExtensions.Contains(container.AsReadOnlySpan(), new FixedString128Bytes("789")));
container.Dispose();
}
[Test]
public void NativeArray_DisposeJob()
{
var container = new NativeArray<int>(1, Allocator.Persistent);
Assert.True(container.IsCreated);
Assert.DoesNotThrow(() => { container[0] = 1; });
var disposeJob = container.Dispose(default);
Assert.False(container.IsCreated);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
Assert.Throws<ObjectDisposedException>(
() => { container[0] = 2; });
#endif
disposeJob.Complete();
}
[BurstCompile(CompileSynchronously = true)]
struct NativeArrayPokeJob : IJob
{
NativeArray<int> array;
public NativeArrayPokeJob(NativeArray<int> array) { this.array = array; }
public void Execute()
{
array[0] = 1;
}
}
[Test]
[TestRequiresCollectionChecks]
public void NativeArray_DisposeJobWithMissingDependencyThrows()
{
var array = new NativeArray<int>(1, Allocator.Persistent);
var deps = new NativeArrayPokeJob(array).Schedule();
Assert.Throws<InvalidOperationException>(() => { array.Dispose(default); });
deps.Complete();
array.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void NativeArray_DisposeJobCantBeScheduled()
{
var array = new NativeArray<int>(1, Allocator.Persistent);
var deps = array.Dispose(default);
Assert.Throws<InvalidOperationException>(() => { new NativeArrayPokeJob(array).Schedule(deps); });
deps.Complete();
}
[Test]
unsafe public void NativeArray_ConvertExistingDataToNativeArray()
{
AllocatorManager.Initialize();
var allocatorHelper = new AllocatorHelper<RewindableAllocator>(AllocatorManager.Persistent);
allocatorHelper.Allocator.Initialize(64 * 1024);
var nativeList = new NativeList<int>(allocatorHelper.Allocator.Handle);
for(int i = 0; i < 20; i++)
{
nativeList.Add(i);
}
var nativeArray = CollectionHelper.ConvertExistingDataToNativeArray<int>(nativeList.GetUnsafePtr(), nativeList.Length, allocatorHelper.Allocator.Handle);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var listSafety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref nativeList);
NativeArrayUnsafeUtility.SetAtomicSafetyHandle<int>(ref nativeArray, listSafety);
#endif
for (int i = 0; i < 20; i++)
{
Assert.AreEqual(nativeArray[i], i);
}
nativeArray.Dispose();
allocatorHelper.Allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
[Test]
unsafe public void NativeArray_ConvertExistingDataToNativeArray_SetTempMemoryHandle()
{
var nativeList = new NativeList<int>(Allocator.Temp);
for (int i = 0; i < 20; i++)
{
nativeList.Add(i);
}
var nativeArray = CollectionHelper.ConvertExistingDataToNativeArray<int>(nativeList.GetUnsafePtr(), nativeList.Length, Allocator.Temp, true);
for (int i = 0; i < 20; i++)
{
Assert.AreEqual(nativeArray[i], i);
}
nativeArray.Dispose();
}
[Test]
unsafe public void NativeArray_ConvertExistingNativeListToNativeArray()
{
AllocatorManager.Initialize();
var allocatorHelper = new AllocatorHelper<RewindableAllocator>(AllocatorManager.Persistent);
allocatorHelper.Allocator.Initialize(64 * 1024);
var nativeList = new NativeList<int>(allocatorHelper.Allocator.Handle);
for (int i = 0; i < 20; i++)
{
nativeList.Add(i);
}
var nativeArray = CollectionHelper.ConvertExistingNativeListToNativeArray<int>(ref nativeList, nativeList.Length, allocatorHelper.Allocator.Handle);
for (int i = 0; i < 20; i++)
{
Assert.AreEqual(nativeArray[i], i);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var listSafety = NativeListUnsafeUtility.GetAtomicSafetyHandle(ref nativeList);
var arraySafety = CollectionHelper.GetNativeArraySafetyHandle(ref nativeArray);
Assert.AreEqual(listSafety, arraySafety);
#endif
nativeArray.Dispose();
allocatorHelper.Allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
[Ignore("Wait for DOTS-7576 trunk PR in")]
[Test]
public void NativeArray_CustomAllocator_DisposeException()
{
AllocatorManager.Initialize();
var allocatorHelper = new AllocatorHelper<CustomAllocatorTests.CountingAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize();
var nativeArray = CollectionHelper.CreateNativeArray<int>(100, allocator.ToAllocator, NativeArrayOptions.UninitializedMemory);
nativeArray[0] = 0xFE;
var nativeList = new NativeList<int>(allocator.ToAllocator);
for (int i = 0; i < 50; i++)
{
nativeList.Add(i);
}
Assert.IsTrue(allocator.WasUsed);
Assert.Throws<InvalidOperationException>(() => nativeArray.Dispose());
CollectionHelper.Dispose(nativeArray);
nativeList.Dispose();
allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
public struct SimpleTestJob : IJob
{
public int ElementValue;
[WriteOnly]
public NativeArray<int> Result;
public void Execute()
{
for (int i = 0; i < Result.Length; ++i)
Result[i] = ElementValue;
}
}
[Ignore("Wait for DOTS-7576 trunk PR in")]
[Test]
public void NativeArray_CustomAllocator_DisposeHandleException()
{
AllocatorManager.Initialize();
var allocatorHelper = new AllocatorHelper<CustomAllocatorTests.CountingAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize();
var nativeArray = CollectionHelper.CreateNativeArray<int>(100, allocator.ToAllocator, NativeArrayOptions.UninitializedMemory);
SimpleTestJob job = new SimpleTestJob()
{
ElementValue = 0xFE,
Result = nativeArray
};
var jobHandle = job.Schedule();
jobHandle.Complete();
Assert.IsTrue(allocator.WasUsed);
Assert.Throws<InvalidOperationException>(() => nativeArray.Dispose(jobHandle));
CollectionHelper.Dispose(nativeArray);
allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4994f8a9b786efc419e89e1e7146cdc6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,868 @@
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Collections.Tests;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.TestTools;
using System.Text.RegularExpressions;
using Assert = FastAssert;
internal class NativeBitArrayTests : CollectionsTestFixture
{
[Test]
public void NativeBitArray_Init()
{
var container = new NativeBitArray(0, Allocator.Persistent, NativeArrayOptions.ClearMemory);
Assert.True(container.IsCreated);
Assert.True(container.IsEmpty);
Assert.DoesNotThrow(() => container.Dispose());
}
[Test]
public void NativeBitArray_Get_Set_Long()
{
var numBits = 256;
var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
Assert.False(test.IsSet(123));
test.Set(123, true);
Assert.True(test.IsSet(123));
Assert.False(test.TestAll(0, numBits));
Assert.False(test.TestNone(0, numBits));
Assert.True(test.TestAny(0, numBits));
Assert.AreEqual(1, test.CountBits(0, numBits));
Assert.False(test.TestAll(0, 122));
Assert.True(test.TestNone(0, 122));
Assert.False(test.TestAny(0, 122));
test.Clear();
Assert.False(test.IsSet(123));
Assert.AreEqual(0, test.CountBits(0, numBits));
test.SetBits(40, true, 4);
Assert.AreEqual(4, test.CountBits(0, numBits));
test.SetBits(0, true, numBits);
Assert.False(test.TestNone(0, numBits));
Assert.True(test.TestAll(0, numBits));
test.SetBits(0, false, numBits);
Assert.True(test.TestNone(0, numBits));
Assert.False(test.TestAll(0, numBits));
test.SetBits(123, true, 7);
Assert.True(test.TestAll(123, 7));
test.Clear();
test.SetBits(64, true, 64);
Assert.AreEqual(false, test.IsSet(63));
Assert.AreEqual(true, test.TestAll(64, 64));
Assert.AreEqual(false, test.IsSet(128));
Assert.AreEqual(64, test.CountBits(64, 64));
Assert.AreEqual(64, test.CountBits(0, numBits));
test.Clear();
test.SetBits(65, true, 62);
Assert.AreEqual(false, test.IsSet(64));
Assert.AreEqual(true, test.TestAll(65, 62));
Assert.AreEqual(false, test.IsSet(127));
Assert.AreEqual(62, test.CountBits(64, 64));
Assert.AreEqual(62, test.CountBits(0, numBits));
test.Clear();
test.SetBits(66, true, 64);
Assert.AreEqual(false, test.IsSet(65));
Assert.AreEqual(true, test.TestAll(66, 64));
Assert.AreEqual(false, test.IsSet(130));
Assert.AreEqual(64, test.CountBits(66, 64));
Assert.AreEqual(64, test.CountBits(0, numBits));
test.Dispose();
}
[Test]
public void NativeBitArray_Get_Set_Short()
{
var numBits = 31;
var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
Assert.False(test.IsSet(13));
test.Set(13, true);
Assert.True(test.IsSet(13));
Assert.False(test.TestAll(0, numBits));
Assert.False(test.TestNone(0, numBits));
Assert.True(test.TestAny(0, numBits));
Assert.AreEqual(1, test.CountBits(0, numBits));
Assert.False(test.TestAll(0, 12));
Assert.True(test.TestNone(0, 12));
Assert.False(test.TestAny(0, 12));
test.Clear();
Assert.False(test.IsSet(13));
Assert.AreEqual(0, test.CountBits(0, numBits));
test.SetBits(4, true, 4);
Assert.AreEqual(4, test.CountBits(0, numBits));
test.SetBits(0, true, numBits);
Assert.False(test.TestNone(0, numBits));
Assert.True(test.TestAll(0, numBits));
test.SetBits(0, false, numBits);
Assert.True(test.TestNone(0, numBits));
Assert.False(test.TestAll(0, numBits));
test.SetBits(13, true, 7);
Assert.True(test.TestAll(13, 7));
test.Clear();
test.SetBits(4, true, 4);
Assert.AreEqual(false, test.IsSet(3));
Assert.AreEqual(true, test.TestAll(4, 4));
Assert.AreEqual(false, test.IsSet(18));
Assert.AreEqual(4, test.CountBits(4, 4));
Assert.AreEqual(4, test.CountBits(0, numBits));
test.Clear();
test.SetBits(5, true, 2);
Assert.AreEqual(false, test.IsSet(4));
Assert.AreEqual(true, test.TestAll(5, 2));
Assert.AreEqual(false, test.IsSet(17));
Assert.AreEqual(2, test.CountBits(4, 4));
Assert.AreEqual(2, test.CountBits(0, numBits));
test.Clear();
test.SetBits(6, true, 4);
Assert.AreEqual(false, test.IsSet(5));
Assert.AreEqual(true, test.TestAll(6, 4));
Assert.AreEqual(false, test.IsSet(10));
Assert.AreEqual(4, test.CountBits(6, 4));
Assert.AreEqual(4, test.CountBits(0, numBits));
test.Dispose();
}
[Test]
public void NativeBitArray_Get_Set_Tiny()
{
var numBits = 7;
var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
Assert.False(test.IsSet(3));
test.Set(3, true);
Assert.True(test.IsSet(3));
Assert.False(test.TestAll(0, numBits));
Assert.False(test.TestNone(0, numBits));
Assert.True(test.TestAny(0, numBits));
Assert.AreEqual(1, test.CountBits(0, numBits));
Assert.False(test.TestAll(0, 2));
Assert.True(test.TestNone(0, 2));
Assert.False(test.TestAny(0, 2));
test.Clear();
Assert.False(test.IsSet(3));
Assert.AreEqual(0, test.CountBits(0, numBits));
test.SetBits(3, true, 4);
Assert.AreEqual(4, test.CountBits(0, numBits));
test.SetBits(0, true, numBits);
Assert.False(test.TestNone(0, numBits));
Assert.True(test.TestAll(0, numBits));
test.SetBits(0, false, numBits);
Assert.True(test.TestNone(0, numBits));
Assert.False(test.TestAll(0, numBits));
test.Dispose();
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public unsafe void NativeBitArray_Throws()
{
var numBits = 256;
Assert.Throws<ArgumentException>(() => { new NativeBitArray(numBits, Allocator.None); });
using (var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory))
{
Assert.DoesNotThrow(() => { test.TestAll(0, numBits); });
Assert.DoesNotThrow(() => { test.TestAny(numBits - 1, numBits); });
Assert.Throws<ArgumentException>(() => { test.IsSet(-1); });
Assert.Throws<ArgumentException>(() => { test.IsSet(numBits); });
Assert.Throws<ArgumentException>(() => { test.TestAny(0, 0); });
Assert.Throws<ArgumentException>(() => { test.TestAny(numBits, 1); });
Assert.Throws<ArgumentException>(() => { test.TestAny(numBits - 1, 0); });
// GetBits numBits must be 1-64.
Assert.Throws<ArgumentException>(() => { test.GetBits(0, 0); });
Assert.Throws<ArgumentException>(() => { test.GetBits(0, 65); });
Assert.DoesNotThrow(() => { test.GetBits(63, 2); });
}
}
void GetBitsTest(ref NativeBitArray test, int pos, int numBits)
{
test.SetBits(pos, true, numBits);
Assert.AreEqual(numBits, test.CountBits(0, test.Length));
Assert.AreEqual(0xfffffffffffffffful >> (64 - numBits), test.GetBits(pos, numBits));
test.Clear();
}
[Test]
public void NativeBitArray_GetBits()
{
var numBits = 256;
var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
GetBitsTest(ref test, 0, 5);
GetBitsTest(ref test, 1, 3);
GetBitsTest(ref test, 0, 63);
GetBitsTest(ref test, 0, 64);
GetBitsTest(ref test, 1, 63);
GetBitsTest(ref test, 1, 64);
GetBitsTest(ref test, 62, 5);
GetBitsTest(ref test, 127, 3);
GetBitsTest(ref test, 250, 6);
GetBitsTest(ref test, 254, 2);
test.Dispose();
}
static void SetBitsTest(ref NativeBitArray test, int pos, ulong value, int numBits)
{
test.SetBits(pos, value, numBits);
if (value != test.GetBits(pos, numBits))
throw new Exception("Assert.Equals(value, test.GetBits(pos, numBits)) failed");
test.Clear();
}
[Test]
public void NativeBitArray_SetBits()
{
var numBits = 256;
var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
SetBitsTest(ref test, 0, 16, 5);
SetBitsTest(ref test, 1, 7, 3);
SetBitsTest(ref test, 1, 32, 64);
SetBitsTest(ref test, 62, 6, 5);
SetBitsTest(ref test, 127, 1, 3);
SetBitsTest(ref test, 60, 0xaa, 8);
test.Dispose();
}
static void CopyBitsTest(ref NativeBitArray test, int dstPos, int srcPos, int numBits)
{
for (int pos = 0; pos < test.Length; pos += 64)
{
test.SetBits(pos, 0xaaaaaaaaaaaaaaaaul, 64);
}
test.SetBits(srcPos, true, numBits);
test.Copy(dstPos, srcPos, numBits);
Assert.AreEqual(true, test.TestAll(dstPos, numBits));
for (int pos = 0; pos < test.Length; ++pos)
{
if ((pos >= dstPos && pos < dstPos + numBits) ||
(pos >= srcPos && pos < srcPos + numBits))
{
Assert.AreEqual(true, test.IsSet(pos));
}
else
{
Assert.AreEqual((0 != (pos & 1)), test.IsSet(pos));
}
}
test.Clear();
}
static void CopyBitsTests(ref NativeBitArray test)
{
CopyBitsTest(ref test, 1, 16, 12); // short up to 64-bits copy
CopyBitsTest(ref test, 1, 80, 63); // short up to 64-bits copy
CopyBitsTest(ref test, 1, 11, 12); // short up to 64-bits copy overlapped
CopyBitsTest(ref test, 11, 1, 12); // short up to 64-bits copy overlapped
CopyBitsTest(ref test, 1, 16, 76); // short up to 128-bits copy
CopyBitsTest(ref test, 1, 80, 127); // short up to 128-bits copy
CopyBitsTest(ref test, 1, 11, 76); // short up to 128-bits copy overlapped
CopyBitsTest(ref test, 11, 1, 76); // short up to 128-bits copy overlapped
CopyBitsTest(ref test, 1, 81, 255); // long copy aligned
CopyBitsTest(ref test, 8, 0, 255); // long copy overlapped aligned
CopyBitsTest(ref test, 1, 80, 255); // long copy unaligned
CopyBitsTest(ref test, 80, 1, 255); // long copy overlapped unaligned
}
[Test]
public void NativeBitArray_Copy()
{
var numBits = 512;
var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
CopyBitsTests(ref test);
test.Dispose();
}
[Test]
public void UnsafeBitArray_Resize()
{
var test = new NativeBitArray(1, Allocator.Persistent, NativeArrayOptions.ClearMemory);
Assert.AreEqual(1, test.Length);
Assert.AreEqual(64, test.Capacity);
test.SetCapacity(200); // expand
Assert.AreEqual(1, test.Length);
Assert.AreEqual(256, test.Capacity);
test.Resize(100, NativeArrayOptions.ClearMemory);
Assert.True(test.TestNone(0, test.Length));
// prepare survival test
test.Set(0, true);
test.Set(99, true);
Assert.True(test.IsSet(0));
Assert.True(test.TestNone(1, 98));
Assert.True(test.IsSet(99));
test.SetCapacity(1000); // expand
Assert.AreEqual(100, test.Length);
Assert.AreEqual(1024, test.Capacity);
// test resize survival
Assert.True(test.IsSet(0));
Assert.True(test.TestNone(1, 98));
Assert.True(test.IsSet(99));
// manual clear
test.Resize(1);
test.Set(0, false);
test.SetCapacity(200); // truncate capacity
Assert.AreEqual(1, test.Length);
Assert.AreEqual(256, test.Capacity);
test.Resize(512, NativeArrayOptions.ClearMemory); // resize
Assert.AreEqual(512, test.Length);
Assert.AreEqual(512, test.Capacity);
Assert.True(test.TestNone(0, test.Length));
CopyBitsTests(ref test);
test.Resize(256); // truncate length
Assert.AreEqual(256, test.Length);
Assert.AreEqual(512, test.Capacity);
test.TrimExcess();
Assert.AreEqual(256, test.Length);
Assert.AreEqual(256, test.Capacity);
test.Dispose();
}
[Test]
public unsafe void NativeBitArray_CopyBetweenBitArrays()
{
var numBits = 512;
var str = new FixedString128Bytes("aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ");
var test0 = NativeBitArrayUnsafeUtility.ConvertExistingDataToNativeBitArray(&str.bytes.offset0000, 64, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle ash = CollectionHelper.CreateSafetyHandle(Allocator.Temp);
NativeBitArrayUnsafeUtility.SetAtomicSafetyHandle(ref test0, ash);
#endif
var test1 = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
var test2 = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
for (int pos = 0; pos < test0.Length; pos += 64)
{
test1.SetBits(pos, 0x5555555555555555ul, 64);
test2.SetBits(pos, 0xaaaaaaaaaaaaaaaaul, 64);
}
test1.Copy(1, ref test0, 205, 211);
test1.Copy(214, ref test0, 0, 205);
test2.Copy(205, ref test1, 1, 211);
test2.Copy(0, ref test1, 214, 205);
test0.Copy(0, ref test2, 0, 512);
Assert.AreEqual(str, "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ");
test0.Dispose();
test1.Dispose();
test2.Dispose();
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public unsafe void NativeBitArray_Copy_Throws()
{
var numBits = 512;
var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
Assert.Throws<ArgumentException>(() => { CopyBitsTest(ref test, 0, numBits - 1, 16); }); // short up to 64-bits copy out of bounds
Assert.Throws<ArgumentException>(() => { CopyBitsTest(ref test, numBits - 1, 0, 16); }); // short up to 64-bits copy out of bounds
Assert.Throws<ArgumentException>(() => { CopyBitsTest(ref test, 0, numBits - 1, 80); }); // short up to 128-bits copy out of bounds
Assert.Throws<ArgumentException>(() => { CopyBitsTest(ref test, numBits - 1, 0, 80); }); // short up to 128-bits copy out of bounds
Assert.Throws<ArgumentException>(() => { CopyBitsTest(ref test, 1, numBits - 7, 127); }); // long copy aligned
Assert.Throws<ArgumentException>(() => { CopyBitsTest(ref test, numBits - 7, 1, 127); }); // long copy aligned
Assert.Throws<ArgumentException>(() => { CopyBitsTest(ref test, 2, numBits - 1, 127); }); // long copy unaligned
Assert.Throws<ArgumentException>(() => { CopyBitsTest(ref test, numBits - 1, 2, 127); }); // long copy unaligned
test.Dispose();
}
[Test]
public unsafe void NativeBitArray_Find()
{
var numBits = 512;
using (var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory))
{
test.SetBits(0, true, 11);
for (var i = 0; i < 256; ++i)
{
Assert.AreEqual(11, test.Find(0, i + 1));
}
for (var j = 0; j < 64; ++j)
{
for (var i = 0; i < 256; ++i)
{
var numBitsToFind = 7 + i;
var pos = 37 + j;
test.SetBits(0, true, test.Length);
test.SetBits(pos, false, numBitsToFind);
Assert.AreEqual(pos, test.Find(0, numBitsToFind)); //, $"{j}/{i}: pos {pos}, numBitsToFind {numBitsToFind}");
Assert.AreEqual(pos, test.Find(pos, numBitsToFind)); //, $"{j}/{i}:pos {pos}, numBitsToFind {numBitsToFind}");
Assert.AreEqual(pos, test.Find(0, numBitsToFind)); //, $"{j}/{i}: pos {pos}, numBitsToFind {numBitsToFind}");
Assert.AreEqual(pos, test.Find(pos, numBitsToFind)); //, $"{j}/{i}: pos {pos}, numBitsToFind {numBitsToFind}");
Assert.IsTrue(test.TestNone(test.Find(0, numBitsToFind), numBitsToFind));
Assert.AreEqual(int.MaxValue, test.Find(pos + 1, numBitsToFind)); //, $"{j}/{i}: pos {pos}, numBitsToFind {numBitsToFind}");
}
}
}
}
[Test]
public unsafe void NativeBitArray_Find_With_Begin_End()
{
var numBits = 512;
using (var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory))
{
Assert.AreEqual(0, test.Find(0, 2, 1));
Assert.AreEqual(1, test.Find(1, 2, 1));
test.SetBits(0, true, 6);
Assert.AreEqual(int.MaxValue, test.Find(0, 2, 1));
for (var j = 0; j < 64; ++j)
{
for (var i = 0; i < 256; ++i)
{
var numBitsToFind = 7 + i;
var padding = 11;
var begin = 37 + j;
var end = begin + padding + numBitsToFind;
var count = end - begin;
test.Clear();
test.SetBits(begin, true, count);
test.SetBits(begin + padding + 1, false, numBitsToFind - 1);
Assert.AreEqual(begin + padding + 1, test.Find(begin, count, numBitsToFind - 1)); //, $"{j}/{i}: begin {begin}, end {end}, count {count}, numBitsToFind {numBitsToFind}");
Assert.AreEqual(int.MaxValue, test.Find(begin, count, numBitsToFind)); //, $"{j}/{i}: begin {begin}, end {end}, count {count}, numBitsToFind {numBitsToFind}");
}
}
}
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public unsafe void NativeBitArray_Find_Throws()
{
var numBits = 512;
using (var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory))
{
Assert.Throws<ArgumentException>(() => { test.Find(0, 0, 1); }); // empty range
Assert.Throws<ArgumentException>(() => { test.Find(0, 1, 0); }); // zero bits
Assert.Throws<ArgumentException>(() => { test.Find(0, 1, 2); }); // numBits is larger than range
Assert.Throws<ArgumentException>(() => { test.Find(10, 0, 0); }); // empty range, numBits is less than 1
Assert.Throws<ArgumentException>(() => { test.Find(1, 10, -2); }); // numBits can't be negative
}
}
[Test]
public void NativeBitArray_AsNativeArray_Byte()
{
var numBits = 64;
var test0 = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
var test1 = test0.AsNativeArray<byte>();
Assert.AreEqual(numBits / 8, test1.Length);
test1[0] = 0x10;
test1[1] = 0x32;
test1[2] = 0x54;
test1[3] = 0x76;
test1[4] = 0x98;
test1[5] = 0xba;
test1[6] = 0xdc;
test1[7] = 0xfe;
for (var i = 0; i < 16; ++i)
{
NUnit.Framework.Assert.AreEqual(i, test0.GetBits(i * 4, 4));
}
test1.Dispose();
test0.Dispose();
}
[Test]
public void NativeBitArray_AsNativeArray_Uint()
{
var numBits = 64;
var test0 = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
var test1 = test0.AsNativeArray<uint>();
Assert.AreEqual(numBits / 32, test1.Length);
test1[0] = 0x76543210;
test1[1] = 0xfedcba98;
for (var i = 0; i < 16; ++i)
{
NUnit.Framework.Assert.AreEqual(i, test0.GetBits(i * 4, 4));
}
test1.Dispose();
test0.Dispose();
}
[Test]
public void NativeBitArray_AsNativeArray_Ulong()
{
var numBits = 64;
var test0 = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
var test1 = test0.AsNativeArray<ulong>();
Assert.AreEqual(numBits / 64, test1.Length);
test1[0] = 0xfedcba9876543210;
for (var i = 0; i < 16; ++i)
{
NUnit.Framework.Assert.AreEqual(i, test0.GetBits(i * 4, 4));
}
test1.Dispose();
test0.Dispose();
}
[StructLayout(LayoutKind.Explicit, Size = 16)]
internal struct SizeMismatch128
{
}
[StructLayout(LayoutKind.Explicit, Size=7)]
internal struct SizeMismatch56
{
}
[Test]
[TestRequiresDotsDebugOrCollectionChecks]
public void NativeBitArray_AsNativeArray_ThrowsOnSizeMismatch()
{
var numBits = 64;
var test0 = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
Assert.Throws<InvalidOperationException>(() => { test0.AsNativeArray<SizeMismatch128>(); });
Assert.Throws<InvalidOperationException>(() => { test0.AsNativeArray<SizeMismatch56>(); });
test0.Dispose();
}
// Burst error BC1071: Unsupported assert type
// [BurstCompile(CompileSynchronously = true)]
struct NativeBitArrayTestReadOnly : IJob
{
public NativeBitArray.ReadOnly reader;
public void Execute()
{
var rd = reader;
Assert.True(reader.IsSet(7));
Assert.AreEqual(1, reader.CountBits(0, reader.Length));
}
}
[Test]
[TestRequiresCollectionChecks]
public void NativeBitArray_ReadOnly()
{
var numBits = 256;
var reader = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
reader.Set(7, true);
var readerJob = new NativeBitArrayTestReadOnly { reader = reader.AsReadOnly() }.Schedule();
var from = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
Assert.Throws<InvalidOperationException>(() => { reader.Copy(7, ref from, 30, 10); } /* attempt to write into reader after job is scheduled */);
from.Dispose();
reader.Dispose(readerJob);
readerJob.Complete();
}
[Test]
[TestRequiresCollectionChecks]
public void NativeBitArray_UseAfterFree_UsesCustomOwnerTypeName()
{
var numBits = 256;
var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
SetBitsTest(ref test, 0, 16, 5);
test.Dispose();
NUnit.Framework.Assert.That(() => test.IsSet(0),
Throws.Exception.TypeOf<ObjectDisposedException>()
.With.Message.Contains($"The {test.GetType()} has been deallocated"));
}
[Test]
[TestRequiresCollectionChecks]
public void NativeBitArray_AtomicSafetyHandle_AllocatorTemp_UniqueStaticSafetyIds()
{
var numBits = 256;
var test = new NativeBitArray(numBits, Allocator.Temp, NativeArrayOptions.ClearMemory);
// All collections that use Allocator.Temp share the same core AtomicSafetyHandle.
// This test verifies that containers can proceed to assign unique static safety IDs to each
// AtomicSafetyHandle value, which will not be shared by other containers using Allocator.Temp.
var test0 = new NativeBitArray(numBits, Allocator.Temp, NativeArrayOptions.ClearMemory);
var test1 = new NativeBitArray(numBits, Allocator.Temp, NativeArrayOptions.ClearMemory);
SetBitsTest(ref test0, 0, 16, 5);
test0.Dispose();
NUnit.Framework.Assert.That(() => test0.IsSet(0),
Throws.Exception.With.TypeOf<ObjectDisposedException>()
.With.Message.Contains($"The {test0.GetType()} has been deallocated"));
SetBitsTest(ref test1, 0, 16, 5);
test1.Dispose();
NUnit.Framework.Assert.That(() => test1.IsSet(0),
Throws.Exception.With.TypeOf<ObjectDisposedException>()
.With.Message.Contains($"The {test1.GetType()} has been deallocated"));
}
[BurstCompile(CompileSynchronously = true)]
struct NativeBitArrayCreateAndUseAfterFreeBurst : IJob
{
public void Execute()
{
var numBits = 256;
var test = new NativeBitArray(numBits, Allocator.Temp, NativeArrayOptions.ClearMemory);
SetBitsTest(ref test, 0, 16, 5);
test.Dispose();
SetBitsTest(ref test, 0, 16, 5);
}
}
[Test]
[TestRequiresCollectionChecks]
public void NativeBitArray_CreateAndUseAfterFreeInBurstJob_UsesCustomOwnerTypeName()
{
// Make sure this isn't the first container of this type ever created, so that valid static safety data exists
var numBits = 256;
var test = new NativeBitArray(numBits, Allocator.Persistent, NativeArrayOptions.ClearMemory);
test.Dispose();
var job = new NativeBitArrayCreateAndUseAfterFreeBurst
{
};
// Two things:
// 1. This exception is logged, not thrown; thus, we use LogAssert to detect it.
// 2. Calling write operation after container.Dispose() emits an unintuitive error message. For now, all this test cares about is whether it contains the
// expected type name.
job.Run();
LogAssert.Expect(LogType.Exception,
new Regex($"InvalidOperationException: The {Regex.Escape(test.GetType().ToString())} has been declared as \\[ReadOnly\\] in the job, but you are writing to it"));
}
void findWithPattern(ref NativeBitArray test, byte pattern, int numBits)
{
for (int pos = 0; pos < test.Length; pos += 8)
{
test.SetBits(pos, pattern, 8);
}
var bitCount = math.countbits((int)pattern);
var numEmptyBits = test.Length - (test.Length / 8 * bitCount);
for (int i = 0; i < numEmptyBits; i += numBits)
{
var pos = test.Find(0, numBits);
Assert.AreNotEqual(int.MaxValue, pos, $"{i}");
test.SetBits(pos, true, numBits);
}
Assert.True(test.TestAll(0, test.Length));
}
[Test]
public void NativeBitArray_FindWithPattern()
{
var test = new NativeBitArray(512, Allocator.Persistent, NativeArrayOptions.ClearMemory);
// Separated test for some more interesting patterns
findWithPattern(ref test, 0x81, 1);
findWithPattern(ref test, 0x81, 2);
findWithPattern(ref test, 0x81, 3);
findWithPattern(ref test, 0x81, 6);
findWithPattern(ref test, 0x88, 3);
findWithPattern(ref test, 0x99, 2);
findWithPattern(ref test, 0xaa, 1);
findWithPattern(ref test, 0xc3, 1);
findWithPattern(ref test, 0xc3, 2);
findWithPattern(ref test, 0xc3, 4);
findWithPattern(ref test, 0xe7, 1);
findWithPattern(ref test, 0xe7, 2);
// Test all patterns
for (int i = 0; i < 256; i++)
{
findWithPattern(ref test, (byte)i, 1);
}
test.Dispose();
}
[Test]
public void NativeBitArray_FindInTinyBitArray()
{
var test = new NativeBitArray(3, Allocator.Persistent, NativeArrayOptions.ClearMemory);
Assert.AreEqual(3, test.Length);
test.SetBits(0, 0x55, test.Length);
Assert.AreEqual(1, test.Find(0, 1));
Assert.AreEqual(1, test.Find(0, test.Length, 1));
test.SetBits(1, true, 1);
Assert.True(test.TestAll(0, test.Length));
Assert.AreEqual(int.MaxValue, test.Find(0, test.Length, 1));
test.Dispose();
}
[Test]
public void NativeBitArray_FindLastUnsetBit([NUnit.Framework.Range(1, 64)] int numBits)
{
using (var bits = new NativeBitArray(numBits, Allocator.Persistent))
{
// Set all bits to one then unset a single bit to find.
for (int i = 0; i < numBits; ++i)
{
bits.SetBits(0, true, numBits);
bits.Set(i, false);
Assert.AreEqual(i, bits.Find(0, 1));
}
}
}
[Test]
public void NativeBitArray_CustomAllocatorTest()
{
AllocatorManager.Initialize();
var allocatorHelper = new AllocatorHelper<CustomAllocatorTests.CountingAllocator>(AllocatorManager.Persistent);
allocatorHelper.Allocator.Initialize();
using (var bitset = new NativeBitArray(1, allocatorHelper.Allocator.Handle))
{
}
Assert.IsTrue(allocatorHelper.Allocator.WasUsed);
allocatorHelper.Allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
[BurstCompile]
struct BurstedCustomAllocatorJob : IJob
{
[NativeDisableUnsafePtrRestriction]
public unsafe CustomAllocatorTests.CountingAllocator* Allocator;
public void Execute()
{
unsafe
{
using (var container = new NativeBitArray(1, Allocator->Handle))
{
}
}
}
}
[Test]
public unsafe void NativeBitArray_BurstedCustomAllocatorTest()
{
AllocatorManager.Initialize();
var allocatorHelper = new AllocatorHelper<CustomAllocatorTests.CountingAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocatorHelper.Allocator.Initialize();
var allocatorPtr = (CustomAllocatorTests.CountingAllocator*)UnsafeUtility.AddressOf<CustomAllocatorTests.CountingAllocator>(ref allocator);
unsafe
{
var handle = new BurstedCustomAllocatorJob {Allocator = allocatorPtr}.Schedule();
handle.Complete();
}
Assert.IsTrue(allocator.WasUsed);
allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1ddc4d01f93629947903155de21d90ff
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,66 @@
using Unity.Burst;
using Unity.Jobs;
using NUnit.Framework;
using Unity.Collections;
#pragma warning disable 0649
internal class NativeContainerTests_ValidateTypes : NativeContainerTests_ValidateTypesFixture
{
enum MyTestEnum
{
HellWorld
}
struct Vector3
{
public float x, y, z;
}
struct Matrix4x4
{
public float m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15;
}
[BurstCompile(CompileSynchronously = true)]
struct StructWithVariousStructsAndValueTypesJob : IJob
{
[ReadOnly]
public NativeArray<float> nativeArrayRO;
public NativeArray<float> nativeArrayRW;
#pragma warning disable 0169 // field is never used
Vector3 vec3;
float floatVal;
Matrix4x4 matrix;
int intValue;
byte byteValue;
short shortValue;
MyTestEnum myEnum;
#pragma warning restore 0169 // field is never used
public void Execute() {}
}
[BurstCompile(CompileSynchronously = true)]
struct StructEmptyJob : IJob
{
public void Execute() {}
}
[Test]
public void Scheduling_With_Supported_Types()
{
var temp1 = CollectionHelper.CreateNativeArray<float>(1, CommonRwdAllocator.Handle);
var temp2 = CollectionHelper.CreateNativeArray<float>(1, CommonRwdAllocator.Handle);
var types = new StructWithVariousStructsAndValueTypesJob();
types.nativeArrayRO = temp1;
types.nativeArrayRW = temp2;
types.Schedule().Complete();
new StructEmptyJob().Schedule().Complete();
temp1.Dispose();
temp2.Dispose();
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: ca1581892ffd54eadb405c6eb1c0ce36
timeCreated: 1485127824
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,26 @@
using Unity.Jobs;
using NUnit.Framework;
using System;
using Unity.Collections.Tests;
internal class NativeContainerTests_ValidateTypesFixture : CollectionsTestCommonBase
{
protected static void CheckNativeContainerReflectionException<T>(string expected) where T : unmanaged, IJob
{
var exc = Assert.Catch<InvalidOperationException>(() => { new T().Schedule(); });
Assert.AreEqual(expected, exc.Message);
}
protected static void CheckNativeContainerReflectionExceptionParallelFor<T>(string expected) where T : unmanaged, IJobParallelFor
{
var exc = Assert.Catch<InvalidOperationException>(() => { new T().Schedule(5, 1); });
Assert.AreEqual(expected, exc.Message);
}
protected static void CheckNativeContainerReflectionException<T>() where T : unmanaged, IJob
{
var exc = Assert.Catch<InvalidOperationException>(() => { new T().Schedule(); });
string expected = string.Format("{0}.value is not a value type. Job structs may not contain any reference types.", typeof(T).Name);
Assert.AreEqual(expected, exc.Message);
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: c8a96cba3114f4a3e91b0546fdcd0397
timeCreated: 1485127824
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,45 @@
using Unity.Jobs;
using NUnit.Framework;
using Unity.Burst;
using Unity.Collections;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
internal class NativeContainderTests_ValidateTypes_JobDebugger : NativeContainerTests_ValidateTypesFixture
{
[BurstCompile(CompileSynchronously = true)]
struct WriteOnlyHashMapParallelForJob : IJobParallelFor
{
[WriteOnly]
NativeParallelHashMap<int, int> value;
public void Execute(int index) {}
}
[BurstCompile(CompileSynchronously = true)]
struct ReadWriteMultiHashMapParallelForJob : IJobParallelFor
{
NativeParallelMultiHashMap<int, int> value;
public void Execute(int index) {}
}
[BurstCompile(CompileSynchronously = true)]
struct DeallocateOnJobCompletionOnUnsupportedType : IJob
{
[DeallocateOnJobCompletion]
NativeList<float> value;
public void Execute() {}
}
[Test]
public void ValidatedUnsupportedTypes()
{
CheckNativeContainerReflectionExceptionParallelFor<WriteOnlyHashMapParallelForJob>("WriteOnlyHashMapParallelForJob.value is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.");
CheckNativeContainerReflectionException<DeallocateOnJobCompletionOnUnsupportedType>("DeallocateOnJobCompletionOnUnsupportedType.value uses [DeallocateOnJobCompletion] but the native container does not support deallocation of the memory from a job.");
// ReadWrite against atomic write only container
CheckNativeContainerReflectionExceptionParallelFor<ReadWriteMultiHashMapParallelForJob>("ReadWriteMultiHashMapParallelForJob.value is not declared [ReadOnly] in a IJobParallelFor job. The container does not support parallel writing. Please use a more suitable container type.");
}
}
#endif
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 4af3ca04cfb2f4b2e91ba58bc5adc6af
timeCreated: 1485127823
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cfd952b600713ff42a2db6d5c8228f8c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,558 @@
using System;
using NUnit.Framework;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Collections.NotBurstCompatible;
using Unity.Jobs;
using Unity.Collections.Tests;
internal class NativeHashSetTests: CollectionsTestFixture
{
static void ExpectedCount<T>(ref NativeHashSet<T> container, int expected)
where T : unmanaged, IEquatable<T>
{
Assert.AreEqual(expected == 0, container.IsEmpty);
Assert.AreEqual(expected, container.Count);
}
[Test]
public void NativeHashSet_IsEmpty()
{
var container = new NativeHashSet<int>(0, Allocator.Persistent);
Assert.IsTrue(container.IsEmpty);
container.Add(0);
Assert.IsFalse(container.IsEmpty);
Assert.AreNotEqual(0, container.Capacity);
ExpectedCount(ref container, 1);
container.Remove(0);
Assert.IsTrue(container.IsEmpty);
container.Add(0);
container.Clear();
Assert.IsTrue(container.IsEmpty);
container.Dispose();
}
[Test]
public void NativeHashSet_Capacity()
{
var container = new NativeHashSet<int>(0, Allocator.Persistent);
Assert.IsTrue(container.IsEmpty);
container.Capacity = 10;
Assert.AreNotEqual(0, container.Capacity);
container.Dispose();
}
[Test]
public void NativeHashSet_CapacityAtLeastCount()
{
var container = new NativeHashSet<int>(0, Allocator.Persistent);
for (int i = 0; i < 300; i++)
container.Add(i);
container.Capacity = 3;
Assert.IsTrue(container.Capacity >= container.Count);
container.Dispose();
}
[Test]
public void NativeHashSet_RemoveOnEmptyMap_DoesNotThrow()
{
var container = new NativeHashSet<int>(0, Allocator.Temp);
Assert.DoesNotThrow(() => container.Remove(0));
Assert.DoesNotThrow(() => container.Remove(-425196));
container.Dispose();
}
[Test]
public void NativeHashSet_Collisions()
{
var container = new NativeHashSet<int>(16, Allocator.Temp);
Assert.IsFalse(container.Contains(0), "Contains on empty hash map did not fail");
ExpectedCount(ref container, 0);
// Make sure inserting values work
for (int i = 0; i < 8; ++i)
{
Assert.IsTrue(container.TryAdd(i), "Failed to add value");
}
ExpectedCount(ref container, 8);
// The bucket size is capacity * 2, adding that number should result in hash collisions
for (int i = 0; i < 8; ++i)
{
Assert.IsTrue(container.TryAdd(i + 32), "Failed to add value with potential hash collision");
}
// Make sure reading the inserted values work
for (int i = 0; i < 8; ++i)
{
Assert.IsTrue(container.Contains(i), "Failed get value from hash set");
}
for (int i = 0; i < 8; ++i)
{
Assert.IsTrue(container.Contains(i + 32), "Failed get value from hash set");
}
container.Dispose();
}
[Test]
public void NativeHashSet_SameKey()
{
using var container = new NativeHashSet<int>(4, Allocator.Persistent);
Assert.DoesNotThrow(() => container.Add(0));
Assert.IsFalse(container.Add(0)); // Nuance: This version of Add does not throw (but will eventually)!
Assert.IsFalse(container.TryAdd(0));
Assert.IsTrue(container.Contains(0));
}
[Test]
public void NativeHashSet_CanBeReadFromJob()
{
using (var hashSet = new NativeHashSet<int>(1, CommonRwdAllocator.Handle))
using (var result = new NativeReference<int>(CommonRwdAllocator.Handle))
{
hashSet.Add(42);
new ReadHashSetJob
{
Input = hashSet.AsReadOnly(),
Output = result,
}.Run();
Assert.AreEqual(42, result.Value);
}
}
struct TempHashSet : IJob
{
public void Execute()
{
using (var stringList = new NativeList<FixedString32Bytes>(10, Allocator.Persistent) { "Hello", ",", "World", "!" })
{
var container = new NativeHashSet<FixedString128Bytes>(50, Allocator.Temp);
var seen = new NativeArray<int>(stringList.Length, Allocator.Temp);
foreach (var str in stringList)
{
container.Add(str);
}
foreach (var value in container)
{
int index = stringList.IndexOf(value);
Assert.AreEqual(stringList[index], value.ToString());
seen[index] = seen[index] + 1;
}
for (int i = 0; i < stringList.Length; i++)
{
Assert.AreEqual(1, seen[i], $"Incorrect value count {stringList[i]}");
}
}
}
}
[Test]
public void NativeHashSet_TempHashSetInJob()
{
new TempHashSet { }.Schedule().Complete();
}
struct ReadHashSetJob : IJob
{
[ReadOnly]
public NativeHashSet<int>.ReadOnly Input;
public NativeReference<int> Output;
public void Execute()
{
Output.Value = Input.ToNativeArray(Allocator.Temp)[0];
foreach (var value in Input)
{
Assert.AreEqual(42, value);
}
}
}
[Test]
public void NativeHashSet_ForEach_FixedStringInHashMap()
{
using (var stringList = new NativeList<FixedString32Bytes>(10, Allocator.Persistent) { "Hello", ",", "World", "!" })
{
var container = new NativeHashSet<FixedString128Bytes>(50, Allocator.Temp);
var seen = new NativeArray<int>(stringList.Length, Allocator.Temp);
foreach (var str in stringList)
{
container.Add(str);
}
foreach (var value in container)
{
int index = stringList.IndexOf(value);
Assert.AreEqual(stringList[index], value.ToString());
seen[index] = seen[index] + 1;
}
for (int i = 0; i < stringList.Length; i++)
{
Assert.AreEqual(1, seen[i], $"Incorrect value count {stringList[i]}");
}
}
}
[Test]
public void NativeHashSet_ForEach([Values(10, 1000)]int n)
{
var seen = new NativeArray<int>(n, Allocator.Temp);
using (var container = new NativeHashSet<int>(32, CommonRwdAllocator.Handle))
{
for (int i = 0; i < n; i++)
{
container.Add(i);
}
var count = 0;
foreach (var item in container)
{
Assert.True(container.Contains(item));
seen[item] = seen[item] + 1;
++count;
}
Assert.AreEqual(container.Count, count);
for (int i = 0; i < n; i++)
{
Assert.AreEqual(1, seen[i], $"Incorrect item count {i}");
}
}
}
struct NativeHashSet_ForEach_Job : IJob
{
[ReadOnly]
public NativeHashSet<int>.ReadOnly Input;
[ReadOnly]
public int Num;
public void Execute()
{
var seen = new NativeArray<int>(Num, Allocator.Temp);
var count = 0;
foreach (var item in Input)
{
Assert.True(Input.Contains(item));
seen[item] = seen[item] + 1;
++count;
}
Assert.AreEqual(Input.Count, count);
for (int i = 0; i < Num; i++)
{
Assert.AreEqual(1, seen[i], $"Incorrect item count {i}");
}
seen.Dispose();
}
}
[Test]
public void NativeHashSet_ForEach_From_Job([Values(10, 1000)] int n)
{
using (var container = new NativeHashSet<int>(32, CommonRwdAllocator.Handle))
{
for (int i = 0; i < n; i++)
{
container.Add(i);
}
new NativeHashSet_ForEach_Job
{
Input = container.AsReadOnly(),
Num = n,
}.Run();
}
}
struct NativeHashSet_Write_Job : IJob
{
public NativeHashSet<int> Input;
public void Execute()
{
Input.Clear();
}
}
[Test]
public void NativeHashSet_Write_From_Job()
{
using (var container = new NativeHashSet<int>(32, CommonRwdAllocator.Handle))
{
container.Add(0);
Assert.IsFalse(container.IsEmpty);
new NativeHashSet_Write_Job
{
Input = container,
}.Run();
Assert.IsTrue(container.IsEmpty);
}
}
[Test]
[TestRequiresCollectionChecks]
public void NativeHashSet_ForEach_Throws_When_Modified()
{
using (var container = new NativeHashSet<int>(32, CommonRwdAllocator.Handle))
{
container.Add(0);
container.Add(1);
container.Add(2);
container.Add(3);
container.Add(4);
container.Add(5);
container.Add(6);
container.Add(7);
container.Add(8);
container.Add(9);
Assert.Throws<ObjectDisposedException>(() =>
{
foreach (var item in container)
{
container.Add(10);
}
});
Assert.Throws<ObjectDisposedException>(() =>
{
foreach (var item in container)
{
container.Remove(1);
}
});
}
}
struct ForEachIterator : IJob
{
[ReadOnly]
public NativeHashSet<int>.Enumerator Iter;
public void Execute()
{
while (Iter.MoveNext())
{
}
}
}
[Test]
[TestRequiresCollectionChecks]
public void NativeHashSet_ForEach_Throws_Job_Iterator()
{
using (var container = new NativeHashSet<int>(32, CommonRwdAllocator.Handle))
{
var jobHandle = new ForEachIterator
{
Iter = container.GetEnumerator()
}.Schedule();
Assert.Throws<InvalidOperationException>(() => { container.Add(1); });
jobHandle.Complete();
}
}
[Test]
public void NativeHashSet_EIU_ExceptWith_Empty()
{
var setA = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { };
var setB = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { };
setA.ExceptWith(setB);
ExpectedCount(ref setA, 0);
setA.Dispose();
setB.Dispose();
}
[Test]
public void NativeHashSet_EIU_ExceptWith_AxB()
{
var setA = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 };
var setB = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { 3, 4, 5, 6, 7, 8 };
setA.ExceptWith(setB);
ExpectedCount(ref setA, 3);
Assert.True(setA.Contains(0));
Assert.True(setA.Contains(1));
Assert.True(setA.Contains(2));
setA.Dispose();
setB.Dispose();
}
[Test]
public void NativeHashSet_EIU_ExceptWith_BxA()
{
var setA = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 };
var setB = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { 3, 4, 5, 6, 7, 8 };
setB.ExceptWith(setA);
ExpectedCount(ref setB, 3);
Assert.True(setB.Contains(6));
Assert.True(setB.Contains(7));
Assert.True(setB.Contains(8));
setA.Dispose();
setB.Dispose();
}
[Test]
public void NativeHashSet_EIU_IntersectWith_Empty()
{
var setA = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { };
var setB = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { };
setA.IntersectWith(setB);
ExpectedCount(ref setA, 0);
setA.Dispose();
setB.Dispose();
}
[Test]
public void NativeHashSet_EIU_IntersectWith()
{
var setA = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 };
var setB = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { 3, 4, 5, 6, 7, 8 };
setA.IntersectWith(setB);
ExpectedCount(ref setA, 3);
Assert.True(setA.Contains(3));
Assert.True(setA.Contains(4));
Assert.True(setA.Contains(5));
setA.Dispose();
setB.Dispose();
}
[Test]
public void NativeHashSet_EIU_UnionWith_Empty()
{
var setA = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { };
var setB = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { };
setA.UnionWith(setB);
ExpectedCount(ref setA, 0);
setA.Dispose();
setB.Dispose();
}
[Test]
public void NativeHashSet_EIU_UnionWith()
{
var setA = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 };
var setB = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { 3, 4, 5, 6, 7, 8 };
setA.UnionWith(setB);
ExpectedCount(ref setA, 9);
Assert.True(setA.Contains(0));
Assert.True(setA.Contains(1));
Assert.True(setA.Contains(2));
Assert.True(setA.Contains(3));
Assert.True(setA.Contains(4));
Assert.True(setA.Contains(5));
Assert.True(setA.Contains(6));
Assert.True(setA.Contains(7));
Assert.True(setA.Contains(8));
setA.Dispose();
setB.Dispose();
}
[Test]
public void NativeHashSet_ToArray()
{
using (var set = new NativeHashSet<int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 })
{
var array = set.ToArray();
Array.Sort(array);
for (int i = 0, num = set.Count; i < num; i++)
{
Assert.AreEqual(array[i], i);
}
}
}
[Test]
public void NativeHashSet_CustomAllocatorTest()
{
AllocatorManager.Initialize();
var allocatorHelper = new AllocatorHelper<CustomAllocatorTests.CountingAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize();
using (var container = new NativeHashSet<int>(1, allocator.Handle))
{
}
FastAssert.IsTrue(allocator.WasUsed);
allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
[BurstCompile]
struct BurstedCustomAllocatorJob : IJob
{
[NativeDisableUnsafePtrRestriction]
public unsafe CustomAllocatorTests.CountingAllocator* Allocator;
public void Execute()
{
unsafe
{
using (var container = new NativeHashSet<int>(1, Allocator->Handle))
{
}
}
}
}
[Test]
public unsafe void NativeHashSet_BurstedCustomAllocatorTest()
{
AllocatorManager.Initialize();
var allocatorHelper = new AllocatorHelper<CustomAllocatorTests.CountingAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize();
var allocatorPtr = (CustomAllocatorTests.CountingAllocator*)UnsafeUtility.AddressOf<CustomAllocatorTests.CountingAllocator>(ref allocator);
unsafe
{
var handle = new BurstedCustomAllocatorJob {Allocator = allocatorPtr }.Schedule();
handle.Complete();
}
FastAssert.IsTrue(allocator.WasUsed);
allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f92c32975f7059949a65dedf00f850c5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 53aefa1beff7b494badc217b913bb5b0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,240 @@
<#/*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 NUnit.Framework;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Collections.Tests;
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// t4 Packages/com.unity.collections/Unity.Collections.Tests/NativeHashSetTests.tt
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
internal class NativeHashSetTestsGenerated : CollectionsTestFixture
{
<#
{
foreach (var ContainerType in new[] {
( "NativeHashSet" ),
( "UnsafeHashSet" ),
}) {
#>
static void ExpectedCount<T>(ref <#=ContainerType#><T> container, int expected)
where T : unmanaged, IEquatable<T>
{
Assert.AreEqual(expected == 0, container.IsEmpty);
Assert.AreEqual(expected, container.Count);
}
<#
foreach (var OtherContainerType in new[] {
( "NativeHashSet" ),
( "UnsafeHashSet" ),
( "NativeParallelHashSet" ),
( "UnsafeParallelHashSet" ),
( "NativeList" ),
( "UnsafeList" ),
}) {
#>
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_ExceptWith_Empty()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { };
var other = new <#=OtherContainerType#><int>(8, CommonRwdAllocator.Handle) { };
container.ExceptWith(other);
ExpectedCount(ref container, 0);
container.Dispose();
other.Dispose();
}
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_ExceptWith_AxB()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 };
var other = new <#=OtherContainerType#><int>(8, CommonRwdAllocator.Handle) { 3, 4, 5, 6, 7, 8 };
container.ExceptWith(other);
ExpectedCount(ref container, 3);
Assert.True(container.Contains(0));
Assert.True(container.Contains(1));
Assert.True(container.Contains(2));
container.Dispose();
other.Dispose();
}
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_IntersectWith_Empty()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { };
var other = new <#=OtherContainerType#><int>(8, CommonRwdAllocator.Handle) { };
container.IntersectWith(other);
ExpectedCount(ref container, 0);
container.Dispose();
other.Dispose();
}
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_IntersectWith()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 };
var other = new <#=OtherContainerType#><int>(8, CommonRwdAllocator.Handle) { 3, 4, 5, 6, 7, 8 };
container.IntersectWith(other);
ExpectedCount(ref container, 3);
Assert.True(container.Contains(3));
Assert.True(container.Contains(4));
Assert.True(container.Contains(5));
container.Dispose();
other.Dispose();
}
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_UnionWith_Empty()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { };
var other = new <#=OtherContainerType#><int>(8, CommonRwdAllocator.Handle) { };
container.UnionWith(other);
ExpectedCount(ref container, 0);
container.Dispose();
other.Dispose();
}
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_UnionWith()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 };
var other = new <#=OtherContainerType#><int>(8, CommonRwdAllocator.Handle) { 3, 4, 5, 6, 7, 8 };
container.UnionWith(other);
ExpectedCount(ref container, 9);
Assert.True(container.Contains(0));
Assert.True(container.Contains(1));
Assert.True(container.Contains(2));
Assert.True(container.Contains(3));
Assert.True(container.Contains(4));
Assert.True(container.Contains(5));
Assert.True(container.Contains(6));
Assert.True(container.Contains(7));
Assert.True(container.Contains(8));
container.Dispose();
other.Dispose();
}
<#}#>
<#
foreach (var OtherContainerType in new[] {
( "FixedList32Bytes" ),
( "FixedList64Bytes" ),
( "FixedList128Bytes" ),
( "FixedList512Bytes" ),
( "FixedList4096Bytes" ),
}) {
#>
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_ExceptWith_Empty()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { };
var other = new <#=OtherContainerType#><int>() { };
container.ExceptWith(other);
ExpectedCount(ref container, 0);
container.Dispose();
}
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_ExceptWith_AxB()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 };
var other = new <#=OtherContainerType#><int>() { 3, 4, 5, 6, 7, 8 };
container.ExceptWith(other);
ExpectedCount(ref container, 3);
Assert.True(container.Contains(0));
Assert.True(container.Contains(1));
Assert.True(container.Contains(2));
container.Dispose();
}
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_IntersectWith_Empty()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { };
var other = new <#=OtherContainerType#><int>() { };
container.IntersectWith(other);
ExpectedCount(ref container, 0);
container.Dispose();
}
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_IntersectWith()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 };
var other = new <#=OtherContainerType#><int>() { 3, 4, 5, 6, 7, 8 };
container.IntersectWith(other);
ExpectedCount(ref container, 3);
Assert.True(container.Contains(3));
Assert.True(container.Contains(4));
Assert.True(container.Contains(5));
container.Dispose();
}
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_UnionWith_Empty()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { };
var other = new <#=OtherContainerType#><int>() { };
container.UnionWith(other);
ExpectedCount(ref container, 0);
container.Dispose();
}
[Test]
public void <#=ContainerType#>_<#=OtherContainerType#>_EIU_UnionWith()
{
var container = new <#=ContainerType#><int>(8, CommonRwdAllocator.Handle) { 0, 1, 2, 3, 4, 5 };
var other = new <#=OtherContainerType#><int>() { 3, 4, 5, 6, 7, 8 };
container.UnionWith(other);
ExpectedCount(ref container, 9);
Assert.True(container.Contains(0));
Assert.True(container.Contains(1));
Assert.True(container.Contains(2));
Assert.True(container.Contains(3));
Assert.True(container.Contains(4));
Assert.True(container.Contains(5));
Assert.True(container.Contains(6));
Assert.True(container.Contains(7));
Assert.True(container.Contains(8));
container.Dispose();
}
<#}}}#>
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: bead43d474a87b742a2b136a8b41e26b
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,727 @@
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.NotBurstCompatible;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Collections.Tests;
using Unity.Jobs;
using UnityEngine;
using UnityEngine.TestTools;
using System.Text.RegularExpressions;
internal class NativeListTests : CollectionsTestFixture
{
static void ExpectedLength<T>(ref NativeList<T> container, int expected)
where T : unmanaged
{
Assert.AreEqual(expected == 0, container.IsEmpty);
Assert.AreEqual(expected, container.Length);
Assert.AreEqual(expected, container.Count);
}
[Test]
[TestRequiresCollectionChecks]
public void NullListThrow()
{
var list = new NativeList<int>();
Assert.Throws<NullReferenceException>(() => list[0] = 5);
Assert.Throws<ObjectDisposedException>(
() => list.Add(1));
}
[Test]
public void NativeList_CountAndLength_AreEqual()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Length = 3;
Assume.That(list.Length, Is.EqualTo(3));
Assert.That(list.Length, Is.EqualTo(list.Count));
list.Count = 5;
Assume.That(list.Length, Is.EqualTo(5));
Assert.That(list.Length, Is.EqualTo(list.Count));
list.Dispose();
}
[Test]
public void NativeList_Allocate_Deallocate_Read_Write()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Add(1);
list.Add(2);
ExpectedLength(ref list, 2);
Assert.AreEqual(1, list[0]);
Assert.AreEqual(2, list[1]);
list.Dispose();
}
[Test]
public void NativeArrayFromNativeList()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Add(42);
list.Add(2);
NativeArray<int> array = list.AsArray();
Assert.AreEqual(2, array.Length);
Assert.AreEqual(42, array[0]);
Assert.AreEqual(2, array[1]);
list.Dispose();
}
[Test]
[UnityPlatform(RuntimePlatform.WindowsEditor)] //some unnamed platforms don't have enough memory to run this test
public void NativeArrayFromNativeList_MaxCapacity()
{
var list = new NativeList<int>(NativeList<int>.MaxCapacity, Allocator.Persistent);
Assert.AreEqual(NativeList<int>.MaxCapacity, list.Capacity);
list.Length = list.Capacity;
Assert.AreEqual(NativeList<int>.MaxCapacity, list.Length);
NativeArray<int> array = list.AsArray();
Assert.AreEqual(NativeList<int>.MaxCapacity, array.Length);
list.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void NativeArrayFromNativeListInvalidatesOnAdd()
{
var list = new NativeList<int>(Allocator.Persistent);
// This test checks that adding an element without reallocation invalidates the native array
// (length changes)
list.Capacity = 2;
list.Add(42);
NativeArray<int> array = list.AsArray();
list.Add(1000);
ExpectedLength(ref list, 2);
Assert.Throws<ObjectDisposedException>(
() => { array[0] = 1; });
list.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void NativeArrayFromNativeListInvalidatesOnCapacityChange()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Add(42);
NativeArray<int> array = list.AsArray();
ExpectedLength(ref list, 1);
list.Capacity = 10;
//Assert.AreEqual(1, array.Length); - temporarily commenting out updated assert checks to ensure editor version promotion succeeds
Assert.Throws<ObjectDisposedException>(
() => { array[0] = 1; });
list.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void NativeArrayFromNativeListInvalidatesOnDispose()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Add(42);
NativeArray<int> array = list.AsArray();
list.Dispose();
Assert.Throws<ObjectDisposedException>(
() => { array[0] = 1; });
Assert.Throws<ObjectDisposedException>(
() => { list[0] = 1; });
}
[Test]
public void NativeArrayFromNativeListMayDeallocate()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Add(42);
NativeArray<int> array = list.AsArray();
Assert.DoesNotThrow(() => { array.Dispose(); });
list.Dispose();
}
[Test]
public void CopiedNativeListIsKeptInSync()
{
var list = new NativeList<int>(Allocator.Persistent);
var listCpy = list;
list.Add(42);
Assert.AreEqual(42, listCpy[0]);
Assert.AreEqual(42, list[0]);
Assert.AreEqual(1, listCpy.Length);
ExpectedLength(ref list, 1);
list.Dispose();
}
[Test]
public void NativeList_CopyFrom_Managed()
{
var list = new NativeList<float>(4, Allocator.Persistent);
var ar = new float[] { 0, 1, 2, 3, 4, 5, 6, 7 };
list.CopyFromNBC(ar);
ExpectedLength(ref list, 8);
for (int i = 0; i < list.Length; ++i)
{
Assert.AreEqual(i, list[i]);
}
list.Dispose();
}
[Test]
public void NativeList_CopyFrom_OtherContainers()
{
var list = new NativeList<int>(4, Allocator.Persistent);
{
var container = new NativeArray<int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7 }, Allocator.Persistent);
list.CopyFrom(container);
ExpectedLength(ref list, 8);
for (int i = 0; i < list.Length; ++i)
{
Assert.AreEqual(i, list[i]);
}
container.Dispose();
}
list.Add(123);
{
var container = new NativeList<int>(32, Allocator.Persistent) { 0, 1, 2, 3, 4, 5, 6, 7 };
list.CopyFrom(container);
ExpectedLength(ref list, 8);
for (int i = 0; i < list.Length; ++i)
{
Assert.AreEqual(i, list[i]);
}
container.Dispose();
}
list.Add(345);
{
var container = new UnsafeList<int>(32, Allocator.Persistent) { 0, 1, 2, 3, 4, 5, 6, 7 };
list.CopyFrom(container);
ExpectedLength(ref list, 8);
for (int i = 0; i < list.Length; ++i)
{
Assert.AreEqual(i, list[i]);
}
container.Dispose();
}
list.Add(789);
{
var container = new UnsafeList<int>(32, Allocator.Persistent) { 0, 1, 2, 3, 4, 5, 6, 7 };
list.CopyFrom(container.AsReadOnlySpan());
ExpectedLength(ref list, 8);
for (int i = 0; i < list.Length; ++i)
{
Assert.AreEqual(i, list[i]);
}
container.Dispose();
}
list.Add(123);
{
var container = new NativeHashSet<int>(32, Allocator.Persistent) { 0, 1, 2, 3, 4, 5, 6, 7 };
using (var array = container.ToNativeArray(Allocator.TempJob))
{
list.CopyFrom(array);
}
ExpectedLength(ref list, 8);
for (int i = 0; i < list.Length; ++i)
{
list.Contains(i);
}
container.Dispose();
}
list.Add(456);
{
var container = new UnsafeHashSet<int>(32, Allocator.Persistent) { 0, 1, 2, 3, 4, 5, 6, 7 };
using (var array = container.ToNativeArray(Allocator.TempJob))
{
list.CopyFrom(array);
}
ExpectedLength(ref list, 8);
for (int i = 0; i < list.Length; ++i)
{
list.Contains(i);
}
container.Dispose();
}
list.Dispose();
}
[BurstCompile(CompileSynchronously = true)]
struct TempListInJob : IJob
{
public NativeArray<int> Output;
public void Execute()
{
var list = new NativeList<int>(Allocator.Temp);
list.Add(17);
Output[0] = list[0];
list.Dispose();
}
}
[Test]
[Ignore("Unstable on CI, DOTS-1965")]
public void TempListInBurstJob()
{
var job = new TempListInJob() { Output = CollectionHelper.CreateNativeArray<int>(1, CommonRwdAllocator.Handle) };
job.Schedule().Complete();
Assert.AreEqual(17, job.Output[0]);
job.Output.Dispose();
}
[Test]
public void SetCapacityLessThanLength()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Resize(10, NativeArrayOptions.UninitializedMemory);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
Assert.Throws<ArgumentOutOfRangeException>(() => { list.Capacity = 5; });
#endif
list.Dispose();
}
[Test]
public void DisposingNativeListDerivedArrayDoesNotThrow()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Add(1);
NativeArray<int> array = list.AsArray();
Assert.DoesNotThrow(() => { array.Dispose(); });
list.Dispose();
}
[Test]
public void NativeList_DisposeJob()
{
var container = new NativeList<int>(Allocator.Persistent);
Assert.True(container.IsCreated);
Assert.DoesNotThrow(() => { container.Add(0); });
Assert.DoesNotThrow(() => { container.Contains(0); });
var disposeJob = container.Dispose(default);
Assert.False(container.IsCreated);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
Assert.Throws<ObjectDisposedException>(
() => { container.Contains(0); });
#endif
disposeJob.Complete();
}
[Test]
public void ForEachWorks()
{
var container = new NativeList<int>(Allocator.Persistent);
container.Add(10);
container.Add(20);
int sum = 0;
int count = 0;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
sum = 0;
count = 0;
foreach (var p in container)
{
sum += p;
count++;
}
});
Assert.AreEqual(30, sum);
Assert.AreEqual(2, count);
container.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void NativeList_UseAfterFree_UsesCustomOwnerTypeName()
{
var list = new NativeList<int>(10, CommonRwdAllocator.Handle);
list.Add(17);
list.Dispose();
Assert.That(() => list[0],
Throws.Exception.TypeOf<ObjectDisposedException>()
.With.Message.Contains($"The {list.GetType()} has been deallocated"));
}
[Test]
[TestRequiresCollectionChecks]
public void AtomicSafetyHandle_AllocatorTemp_UniqueStaticSafetyIds()
{
// All collections that use Allocator.Temp share the same core AtomicSafetyHandle.
// This test verifies that containers can proceed to assign unique static safety IDs to each
// AtomicSafetyHandle value, which will not be shared by other containers using Allocator.Temp.
var listInt = new NativeList<int>(10, Allocator.Temp);
var listFloat = new NativeList<float>(10, Allocator.Temp);
listInt.Add(17);
listInt.Dispose();
Assert.That(() => listInt[0],
Throws.Exception.TypeOf<ObjectDisposedException>()
.With.Message.Contains($"The {listInt.GetType()} has been deallocated"));
listFloat.Add(1.0f);
listFloat.Dispose();
Assert.That(() => listFloat[0],
Throws.Exception.TypeOf<ObjectDisposedException>()
.With.Message.Contains($"The {listFloat.GetType()} has been deallocated"));
}
[BurstCompile(CompileSynchronously = true)]
struct NativeListCreateAndUseAfterFreeBurst : IJob
{
public void Execute()
{
var list = new NativeList<int>(10, Allocator.Temp);
list.Add(17);
list.Dispose();
list.Add(42);
}
}
[Test]
[TestRequiresCollectionChecks]
public void NativeList_CreateAndUseAfterFreeInBurstJob_UsesCustomOwnerTypeName()
{
// Make sure this isn't the first container of this type ever created, so that valid static safety data exists
var list = new NativeList<int>(10, CommonRwdAllocator.Handle);
list.Dispose();
var job = new NativeListCreateAndUseAfterFreeBurst
{
};
// Two things:
// 1. This exception is logged, not thrown; thus, we use LogAssert to detect it.
// 2. Calling write operation after container.Dispose() emits an unintuitive error message. For now, all this test cares about is whether it contains the
// expected type name.
job.Run();
LogAssert.Expect(LogType.Exception,
new Regex($"InvalidOperationException: The {Regex.Escape(list.GetType().ToString())} has been declared as \\[ReadOnly\\] in the job, but you are writing to it"));
}
[Test]
public unsafe void NativeList_IndexOf()
{
using (var list = new NativeList<int>(10, Allocator.Persistent) { 123, 789 })
{
bool r0 = false, r1 = false, r2 = false;
GCAllocRecorder.ValidateNoGCAllocs(() =>
{
r0 = -1 != list.IndexOf(456);
r1 = list.Contains(123);
r2 = list.Contains(789);
});
Assert.False(r0);
Assert.True(r1);
Assert.True(r2);
}
}
[Test]
public void NativeList_InsertRangeWithBeginEnd()
{
var list = new NativeList<byte>(3, Allocator.Persistent);
list.Add(0);
list.Add(3);
list.Add(4);
Assert.AreEqual(3, list.Length);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRangeWithBeginEnd(-1, 8));
Assert.Throws<ArgumentException>(() => list.InsertRangeWithBeginEnd(3, 1));
#endif
Assert.DoesNotThrow(() => list.InsertRangeWithBeginEnd(1, 3));
Assert.AreEqual(5, list.Length);
list[1] = 1;
list[2] = 2;
for (var i = 0; i < list.Length; ++i)
{
Assert.AreEqual(i, list[i]);
}
Assert.DoesNotThrow(() => list.InsertRangeWithBeginEnd(5, 8));
Assert.AreEqual(8, list.Length);
list[5] = 5;
list[6] = 6;
list[7] = 7;
for (var i = 0; i < list.Length; ++i)
{
Assert.AreEqual(i, list[i]);
}
list.Dispose();
}
[Test]
public void NativeList_InsertRange()
{
var list = new NativeList<byte>(3, Allocator.Persistent);
list.Add(0);
list.Add(3);
list.Add(4);
Assert.AreEqual(3, list.Length);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, 8));
Assert.Throws<ArgumentException>(() => list.InsertRange(3, -1));
#endif
Assert.DoesNotThrow(() => list.InsertRange(1, 0));
Assert.AreEqual(3, list.Length);
Assert.DoesNotThrow(() => list.InsertRange(1, 2));
Assert.AreEqual(5, list.Length);
list[1] = 1;
list[2] = 2;
for (var i = 0; i < list.Length; ++i)
{
Assert.AreEqual(i, list[i]);
}
Assert.DoesNotThrow(() => list.InsertRange(5, 3));
Assert.AreEqual(8, list.Length);
list[5] = 5;
list[6] = 6;
list[7] = 7;
for (var i = 0; i < list.Length; ++i)
{
Assert.AreEqual(i, list[i]);
}
list.Dispose();
}
[Test]
public void NativeList_CustomAllocatorTest()
{
AllocatorManager.Initialize();
var allocatorHelper = new AllocatorHelper<CustomAllocatorTests.CountingAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize();
using (var container = new NativeList<byte>(1, allocator.Handle))
{
}
Assert.IsTrue(allocator.WasUsed);
allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
[BurstCompile]
struct BurstedCustomAllocatorJob : IJob
{
[NativeDisableUnsafePtrRestriction]
public unsafe CustomAllocatorTests.CountingAllocator* Allocator;
public void Execute()
{
unsafe
{
using (var container = new NativeList<byte>(1, Allocator->Handle))
{
}
}
}
}
[Test]
public unsafe void NativeList_BurstedCustomAllocatorTest()
{
AllocatorManager.Initialize();
var allocatorHelper = new AllocatorHelper<CustomAllocatorTests.CountingAllocator>(AllocatorManager.Persistent);
ref var allocator = ref allocatorHelper.Allocator;
allocator.Initialize();
var allocatorPtr = (CustomAllocatorTests.CountingAllocator*)UnsafeUtility.AddressOf<CustomAllocatorTests.CountingAllocator>(ref allocator);
unsafe
{
var handle = new BurstedCustomAllocatorJob {Allocator = allocatorPtr}.Schedule();
handle.Complete();
}
Assert.IsTrue(allocator.WasUsed);
allocator.Dispose();
allocatorHelper.Dispose();
AllocatorManager.Shutdown();
}
[Test]
public unsafe void NativeList_SetCapacity()
{
using (var list = new NativeList<int>(1, Allocator.Persistent))
{
list.Add(1);
Assert.DoesNotThrow(() => list.SetCapacity(128));
list.Add(1);
Assert.AreEqual(2, list.Length);
#if ENABLE_UNITY_COLLECTIONS_CHECKS || UNITY_DOTS_DEBUG
Assert.Throws<ArgumentOutOfRangeException>(() => list.SetCapacity(1));
#endif
list.RemoveAtSwapBack(0);
Assert.AreEqual(1, list.Length);
Assert.DoesNotThrow(() => list.SetCapacity(1));
list.TrimExcess();
Assert.AreEqual(1, list.Capacity);
}
}
[Test]
public unsafe void NativeList_TrimExcess()
{
using (var list = new NativeList<int>(32, Allocator.Persistent))
{
list.Add(1);
list.TrimExcess();
Assert.AreEqual(1, list.Length);
Assert.AreEqual(1, list.Capacity);
list.RemoveAtSwapBack(0);
Assert.AreEqual(list.Length, 0);
list.TrimExcess();
Assert.AreEqual(list.Capacity, 0);
list.Add(1);
Assert.AreEqual(list.Length, 1);
Assert.AreNotEqual(list.Capacity, 0);
list.Clear();
}
}
public struct NestedContainer
{
public NativeList<int> data;
}
[Test]
public void NativeList_Nested()
{
var inner = new NativeList<int>(CommonRwdAllocator.Handle);
NestedContainer nestedStruct = new NestedContainer { data = inner };
var containerNestedStruct = new NativeList<NestedContainer>(CommonRwdAllocator.Handle);
var containerNested = new NativeList<NativeList<int>>(CommonRwdAllocator.Handle);
containerNested.Add(inner);
containerNestedStruct.Add(nestedStruct);
containerNested.Dispose();
containerNestedStruct.Dispose();
inner.Dispose();
}
[Test]
public void NativeList_AddReplicate()
{
using (var list = new NativeList<int>(32, Allocator.Persistent))
{
list.AddReplicate(value: 42, count: 10);
Assert.AreEqual(10, list.Length);
foreach (var item in list)
Assert.AreEqual(42, item);
list.AddReplicate(value: 42, count: 100);
Assert.AreEqual(110, list.Length);
foreach (var item in list)
Assert.AreEqual(42, item);
}
}
static IEnumerable<TestCaseData> AddRangeData()
{
var list = new NativeList<int>(Allocator.Persistent);
for (var i = 0; i < 10; ++i)
list.Add(i);
yield return new TestCaseData(list)
{ TestName = nameof(NativeList<int>) };
}
[Test]
[TestCaseSource(nameof(AddRangeData))]
public void NativeList_AddRange(NativeList<int> testData)
{
for (var i = 0; i < testData.Length; ++i)
Assume.That(testData[i], Is.EqualTo(i));
using var list = new NativeList<int>(Allocator.Persistent);
list.AddRange(testData);
Assert.That(list.Length, Is.EqualTo(testData.Length));
for (var i = 0; i < list.Length; ++i)
Assert.That(list[i], Is.EqualTo(i));
if (testData is INativeDisposable disposable)
disposable.Dispose();
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f492edc6c73b74b7f994f4e948d53302
timeCreated: 1485127824
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,617 @@
#if ENABLE_UNITY_COLLECTIONS_CHECKS
using UnityEngine;
using NUnit.Framework;
using System;
using Unity.Jobs;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.NotBurstCompatible;
using Unity.Collections.Tests;
#pragma warning disable 0219
#pragma warning disable 0414
internal class NativeListJobDebuggerTests : CollectionsTestFixture
{
[BurstCompile(CompileSynchronously = true)]
struct NativeListAddJob : IJob
{
NativeList<int> list;
public NativeListAddJob(NativeList<int> list) { this.list = list; }
public void Execute()
{
list.Add(1);
}
}
[BurstCompile(CompileSynchronously = true)]
struct NativeArrayTest : IJob
{
NativeArray<int> array;
public NativeArrayTest(NativeArray<int> array) { this.array = array; }
public void Execute()
{
}
}
struct NestedContainerJob : IJob
{
public NativeList<NativeList<int>> nestedContainer;
public void Execute()
{
nestedContainer.Clear();
}
}
[Test]
[TestRequiresCollectionChecks]
public void NativeList_NestedJob_Error()
{
var container = new NativeList<NativeList<int>>(CommonRwdAllocator.Handle);
var nestedJob = new NestedContainerJob
{
nestedContainer = container
};
JobHandle job = default;
Assert.Throws<InvalidOperationException>(() => { job = nestedJob.Schedule(); });
job.Complete();
container.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void AddElementToListFromJobInvalidatesArray()
{
var list = new NativeList<int>(CommonRwdAllocator.Handle);
list.Add(0);
NativeArray<int> arrayBeforeSchedule = list.AsArray();
Assert.AreEqual(list.Length, 1);
var jobData = new NativeListAddJob(list);
var job = jobData.Schedule();
Assert.Throws<ObjectDisposedException>(
() => {
int readVal = arrayBeforeSchedule[0];
});
Assert.Throws<InvalidOperationException>(() => { NativeArray<int> array = list.AsArray(); Debug.Log(array.Length); });
Assert.Throws<InvalidOperationException>(() => { int readVal = list.Capacity; });
Assert.Throws<InvalidOperationException>(() => { list.Dispose(); });
Assert.Throws<InvalidOperationException>(() => { int readVal = list[0]; });
job.Complete();
// Assert.AreEqual(1, arrayBeforeSchedule.Length); - temporarily commenting out updated assert checks to ensure editor version promotion succeeds
Assert.Throws<ObjectDisposedException>(
() => {
int readVal = arrayBeforeSchedule[0];
});
Assert.AreEqual(2, list.Length);
Assert.AreEqual(0, list[0]);
Assert.AreEqual(1, list[1]);
NativeArray<int> arrayAfter = list.AsArray();
Assert.AreEqual(2, arrayAfter.Length);
Assert.AreEqual(0, arrayAfter[0]);
Assert.AreEqual(1, arrayAfter[1]);
list.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void AccessBefore()
{
var list = new NativeList<int>(CommonRwdAllocator.Handle);
var jobHandle = new NativeListAddJob(list).Schedule();
Assert.Throws<InvalidOperationException>(() =>
{
list.AsArray();
});
jobHandle.Complete();
list.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void AccessAfter()
{
var list = new NativeList<int>(CommonRwdAllocator.Handle);
var array = list.AsArray();
var jobHandle = new NativeListAddJob(list).Schedule();
Assert.Throws<InvalidOperationException>(() =>
{
new NativeArrayTest(array).Schedule(jobHandle);
});
jobHandle.Complete();
list.Dispose();
}
[Test]
public void ScheduleDerivedArrayAllowDerivingArrayAgain()
{
var list = new NativeList<int>(1, Allocator.Persistent);
// The scheduled job only receives a NativeArray thus it can't be resized
var writeJobHandle = new NativeArrayTest(list.AsArray()).Schedule();
// For that reason casting here is legal, as opposed to AddElementToListFromJobInvalidatesArray case where it is not legal
// Since we NativeList is passed to the job
#pragma warning disable 0219 // assigned but its value is never used
NativeArray<int> array = list.AsArray();
#pragma warning restore 0219
list.Dispose(writeJobHandle);
}
[Test]
[TestRequiresCollectionChecks]
public void ScheduleDerivedArrayExceptions()
{
var list = new NativeList<int>(1, Allocator.Persistent);
var addListJobHandle = new NativeListAddJob(list).Schedule();
#pragma warning disable 0219 // assigned but its value is never used
Assert.Throws<InvalidOperationException>(() => { NativeArray<int> array = list.AsArray(); });
#pragma warning restore 0219
addListJobHandle.Complete();
list.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void ScheduleDerivedArrayExceptions2()
{
var list = new NativeList<int>(1, Allocator.Persistent);
NativeArray<int> array = list.AsArray();
var addListJobHandle = new NativeListAddJob(list).Schedule();
// The array previously cast should become invalid
// as soon as the job is scheduled, since we can't predict if an element will be added or not
Assert.Throws<InvalidOperationException>(() => { new NativeArrayTest(array).Schedule(); });
addListJobHandle.Complete();
list.Dispose();
}
[BurstCompile(CompileSynchronously = true)]
struct ReadOnlyListAccess : IJob
{
[ReadOnly]
NativeList<int> list;
public ReadOnlyListAccess(NativeList<int> list) { this.list = list; }
public void Execute()
{
}
}
[Test]
public void ReadOnlyListInJobKeepsAsArrayValid()
{
var list = new NativeList<int>(CommonRwdAllocator.Handle);
list.Add(0);
var arrayBeforeSchedule = list.AsArray();
var jobData = new ReadOnlyListAccess(list);
var job = jobData.Schedule();
job.Complete();
Assert.AreEqual(0, arrayBeforeSchedule[0]);
list.Dispose();
}
[Test]
public void AsArrayJobKeepsAsArrayValid()
{
var list = new NativeList<int>(CommonRwdAllocator.Handle);
list.Add(0);
var arrayBeforeSchedule = list.AsArray();
var jobData = new NativeArrayTest(list.AsArray());
var job = jobData.Schedule();
job.Complete();
Assert.AreEqual(0, arrayBeforeSchedule[0]);
list.Dispose();
}
[BurstCompile(CompileSynchronously = true)]
struct NativeListToArrayConversionFromJob : IJob
{
public NativeList<int> list;
public void Execute()
{
list.Add(0);
list.Add(0);
NativeArray<int> arr = list.AsArray();
arr[0] = 1;
arr[1] = 2;
}
}
[Test]
public void CastListToArrayInsideJob()
{
var jobData = new NativeListToArrayConversionFromJob();
jobData.list = new NativeList<int>(1, Allocator.Persistent);
jobData.Schedule().Complete();
Assert.AreEqual(new int[] { 1, 2 }, jobData.list.ToArrayNBC());
jobData.list.Dispose();
}
[BurstCompile(CompileSynchronously = true)]
struct WriteJob : IJobParallelFor
{
public NativeArray<float> output;
public void Execute(int i)
{
output[i] = i;
}
}
[Test]
[TestRequiresCollectionChecks]
public void WriteToArrayFromJobThenReadListFromMainThread()
{
var list = new NativeList<float>(1, Allocator.Persistent);
list.Add(0);
list.Add(1);
for (int i = 0; i < 2; i++)
{
var writeJob = new WriteJob();
writeJob.output = list.AsArray();
var writeJobHandle = writeJob.Schedule(list.Length, 1);
Assert.Throws<InvalidOperationException>(() => { float val = writeJob.output[0]; });
writeJobHandle.Complete();
}
list.Dispose();
}
[Test]
public void NativeList_DisposeJob()
{
var list = new NativeList<int>(Allocator.Persistent);
var deps = new NativeListAddJob(list).Schedule();
deps = list.Dispose(deps);
Assert.IsFalse(list.IsCreated);
deps.Complete();
}
struct InvalidArrayAccessFromListJob : IJob
{
public NativeList<int> list;
public void Execute()
{
list.Add(1);
NativeArray<int> array = list.AsArray();
list.Add(2);
// Assert.Throws<InvalidOperationException>(() => { array[0] = 5; }); - temporarily commenting out updated assert checks to ensure editor version promotion succeeds
}
}
[Test]
[TestRequiresCollectionChecks]
public void InvalidatedArrayAccessFromListThrowsInsideJob()
{
var job = new InvalidArrayAccessFromListJob { list = new NativeList<int>(CommonRwdAllocator.Handle) };
job.Schedule().Complete();
job.list.Dispose();
}
[Test]
public void DisposeAliasedArrayDoesNotThrow()
{
var list = new NativeList<int>(Allocator.Persistent);
var array = list.AsArray();
Assert.DoesNotThrow(() => { array.Dispose(); });
list.Dispose();
}
// Burst error BC1071: Unsupported assert type
// [BurstCompile(CompileSynchronously = true)]
struct NativeArrayTestReadOnly : IJob
{
[ReadOnly]
NativeArray<int> array;
public NativeArrayTestReadOnly(NativeArray<int> array) { this.array = array; }
public void Execute()
{
var arr = array;
Assert.Throws<InvalidOperationException>(() => { arr[0] = 5; });
Assert.AreEqual(7, array[0]);
}
}
// Burst error BC1071: Unsupported assert type
// [BurstCompile(CompileSynchronously = true)]
struct NativeArrayTestAsReadOnly : IJob
{
[ReadOnly]
NativeArray<int>.ReadOnly array;
public NativeArrayTestAsReadOnly(NativeArray<int>.ReadOnly array) { this.array = array; }
public void Execute()
{
var arr = array;
Assert.AreEqual(7, array[0]);
}
}
[Test]
[TestRequiresCollectionChecks]
public void ReadOnlyAliasedArrayThrows()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Add(7);
new NativeArrayTestReadOnly(list.AsArray()).Schedule().Complete();
list.Dispose();
}
// Burst error BC1071: Unsupported assert type
// [BurstCompile(CompileSynchronously = true)]
struct NativeArrayTestWriteOnly : IJob
{
[WriteOnly]
NativeArray<int> array;
public NativeArrayTestWriteOnly(NativeArray<int> array) { this.array = array; }
public void Execute()
{
var arr = array;
Assert.Throws<InvalidOperationException>(() => { int read = arr[0]; });
arr[0] = 7;
}
}
[Test]
[TestRequiresCollectionChecks]
public void NativeList_AsArray_Jobs()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Add(0);
var writer = list.AsArray();
var writerJob = new NativeArrayTestWriteOnly(writer).Schedule();
var reader = list.AsArray();
var readerJob = new NativeArrayTestReadOnly(reader).Schedule(writerJob);
// Tests that read only container safety check trows...
var writerJob2 = new NativeArrayTestWriteOnly(reader).Schedule(readerJob);
// Tests that write only container safety check trows...
var readerJob2 = new NativeArrayTestReadOnly(writer).Schedule(writerJob2);
readerJob2.Complete();
list.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void NativeList_AsReadOnly_Jobs()
{
var list = new NativeList<int>(Allocator.Persistent);
list.Add(0);
var writer = list.AsArray();
var writerJob = new NativeArrayTestWriteOnly(writer).Schedule();
var reader = list.AsReadOnly();
var readerJob = new NativeArrayTestAsReadOnly(reader).Schedule(writerJob);
readerJob.Complete();
list.Dispose();
}
// Burst error BC1071: Unsupported assert type
// [BurstCompile(CompileSynchronously = true)]
struct NativeListTestReadOnly : IJob
{
[ReadOnly]
public NativeArray<int>.ReadOnly reader;
public void Execute()
{
Assert.True(reader.Contains(7));
Assert.AreEqual(7, reader[0]);
}
}
[Test]
public void NativeList_AsReadOnly()
{
NativeList<int> list;
JobHandle readerJob;
{
list = new NativeList<int>(Allocator.Persistent);
list.Add(7);
var reader = list.AsReadOnly();
list.Dispose(); // <- cause invalid use
Assert.Throws<InvalidOperationException>(() => { readerJob = new NativeListTestReadOnly { reader = reader }.Schedule(); });
}
{
list = new NativeList<int>(Allocator.Persistent);
list.Add(7);
var reader = list.AsReadOnly();
readerJob = new NativeListTestReadOnly { reader = reader }.Schedule();
}
list.Dispose(readerJob);
readerJob.Complete();
}
[BurstCompile(CompileSynchronously = true)]
struct NativeListTestParallelWriter : IJob
{
[WriteOnly]
public NativeList<int>.ParallelWriter writer;
public unsafe void Execute()
{
var range = stackalloc int[2] { 7, 3 };
writer.AddNoResize(range[0]);
writer.AddRangeNoResize(range, 1);
}
}
[Test]
public void NativeList_ParallelWriter()
{
NativeList<int> list;
{
list = new NativeList<int>(2, Allocator.Persistent);
var writer = list.AsParallelWriter();
list.Dispose(); // <- cause invalid use
Assert.Throws<InvalidOperationException>(() =>
{
var writerJob = new NativeListTestParallelWriter { writer = writer }.Schedule();
writerJob.Complete();
});
}
{
list = new NativeList<int>(2, Allocator.Persistent);
var writer = list.AsParallelWriter();
var writerJob = new NativeListTestParallelWriter { writer = writer }.Schedule();
writerJob.Complete();
}
Assert.AreEqual(2, list.Length);
Assert.AreEqual(7, list[0]);
Assert.AreEqual(7, list[1]);
list.Dispose();
}
[Test]
public void NativeList_ParallelWriter_NoPtrCaching()
{
NativeList<int> list;
{
list = new NativeList<int>(2, Allocator.Persistent);
var writer = list.AsParallelWriter();
list.Capacity = 100;
var writerJob = new NativeListTestParallelWriter { writer = writer }.Schedule();
writerJob.Complete();
}
Assert.AreEqual(2, list.Length);
Assert.AreEqual(7, list[0]);
Assert.AreEqual(7, list[1]);
list.Dispose();
}
[Test]
[TestRequiresCollectionChecks]
public void NativeList_AsReadOnlyAndParallelWriter()
{
NativeList<int> list;
JobHandle jobHandle;
list = new NativeList<int>(Allocator.Persistent);
list.Add(7);
jobHandle = new NativeListTestReadOnly { reader = list.AsReadOnly() }.Schedule();
jobHandle = new NativeListTestParallelWriter { writer = list.AsParallelWriter() }.Schedule(jobHandle);
jobHandle = new NativeListTestReadOnly { reader = list.AsReadOnly() }.Schedule(jobHandle);
jobHandle = new NativeListTestParallelWriter { writer = list.AsParallelWriter() }.Schedule(jobHandle);
list.Dispose(jobHandle);
jobHandle.Complete();
}
unsafe void Expected(ref NativeList<int> list, int expectedLength, int[] expected)
{
Assert.AreEqual(0 == expectedLength, list.IsEmpty);
Assert.AreEqual(list.Length, expectedLength);
for (var i = 0; i < list.Length; ++i)
{
var value = list[i];
Assert.AreEqual(expected[i], value);
}
}
[Test]
public unsafe void NativeList_RemoveRange()
{
var list = new NativeList<int>(10, Allocator.Persistent);
int[] range = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// test removing from the end
fixed (int* r = range) list.AddRange(r, 10);
list.RemoveRange(6, 3);
Expected(ref list, 7, new int[] { 0, 1, 2, 3, 4, 5, 9 });
list.Clear();
// test removing all but one
fixed (int* r = range) list.AddRange(r, 10);
list.RemoveRange(0, 9);
Expected(ref list, 1, new int[] { 9 });
list.Clear();
// test removing from the front
fixed (int* r = range) list.AddRange(r, 10);
list.RemoveRange(0, 3);
Expected(ref list, 7, new int[] { 3, 4, 5, 6, 7, 8, 9 });
list.Clear();
// test removing from the middle
fixed (int* r = range) list.AddRange(r, 10);
list.RemoveRange(0, 3);
Expected(ref list, 7, new int[] { 3, 4, 5, 6, 7, 8, 9 });
list.Clear();
// test removing whole range
fixed (int* r = range) list.AddRange(r, 10);
list.RemoveRange(0, 10);
Expected(ref list, 0, new int[] { 0 });
list.Clear();
list.Dispose();
}
}
#endif
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: eebf40a7db1244e6782a238f4c5d279b
timeCreated: 1485127824
licenseType: Pro
MonoImporter:
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