A game about forced loneliness, made by TACStudios
at master 1035 lines 32 kB view raw
1using NUnit.Framework; 2using Unity.Collections; 3using Unity.Jobs; 4using Unity.Collections.LowLevel.Unsafe; 5using Unity.Collections.LowLevel.Unsafe.NotBurstCompatible; 6using Unity.Collections.Tests; 7using System; 8using Unity.Burst; 9using System.Runtime.InteropServices; 10using UnityEngine.TestTools; 11using System.Text.RegularExpressions; 12using UnityEngine; 13 14internal class NativeHashMapTests : CollectionsTestCommonBase 15{ 16#pragma warning disable 0649 // always default value 17 struct NonBlittableStruct : IEquatable<NonBlittableStruct> 18 { 19 object o; 20 21 public bool Equals(NonBlittableStruct other) 22 { 23 return Equals(o, other.o); 24 } 25 26 public override bool Equals(object obj) 27 { 28 if (ReferenceEquals(null, obj)) return false; 29 return obj is NonBlittableStruct other && Equals(other); 30 } 31 32 public override int GetHashCode() 33 { 34 return (o != null ? o.GetHashCode() : 0); 35 } 36 } 37 38#pragma warning restore 0649 39 40 static void ExpectedCount<TKey, TValue>(ref NativeHashMap<TKey, TValue> container, int expected) 41 where TKey : unmanaged, IEquatable<TKey> 42 where TValue : unmanaged 43 { 44 Assert.AreEqual(expected == 0, container.IsEmpty); 45 Assert.AreEqual(expected, container.Count); 46 } 47 48 [Test] 49 public void NativeHashMap_TryAdd_TryGetValue_Clear() 50 { 51 var hashMap = new NativeHashMap<int, int>(16, Allocator.Temp); 52 ExpectedCount(ref hashMap, 0); 53 54 int iSquared; 55 // Make sure GetValue fails if hash map is empty 56 Assert.IsFalse(hashMap.TryGetValue(0, out iSquared), "TryGetValue on empty hash map did not fail"); 57 58 // Make sure inserting values work 59 for (int i = 0; i < 16; ++i) 60 Assert.IsTrue(hashMap.TryAdd(i, i * i), "Failed to add value"); 61 ExpectedCount(ref hashMap, 16); 62 63 // Make sure inserting duplicate keys fails 64 for (int i = 0; i < 16; ++i) 65 Assert.IsFalse(hashMap.TryAdd(i, i), "Adding duplicate keys did not fail"); 66 ExpectedCount(ref hashMap, 16); 67 68 // Make sure reading the inserted values work 69 for (int i = 0; i < 16; ++i) 70 { 71 Assert.IsTrue(hashMap.TryGetValue(i, out iSquared), "Failed get value from hash table"); 72 Assert.AreEqual(iSquared, i * i, "Got the wrong value from the hash table"); 73 } 74 75 // Make sure clearing removes all keys 76 hashMap.Clear(); 77 ExpectedCount(ref hashMap, 0); 78 79 for (int i = 0; i < 16; ++i) 80 Assert.IsFalse(hashMap.TryGetValue(i, out iSquared), "Got value from hash table after clearing"); 81 82 hashMap.Dispose(); 83 } 84 85 [Test] 86 public void NativeHashMap_Key_Collisions() 87 { 88 var hashMap = new NativeHashMap<int, int>(16, Allocator.Temp); 89 int iSquared; 90 // Make sure GetValue fails if hash map is empty 91 Assert.IsFalse(hashMap.TryGetValue(0, out iSquared), "TryGetValue on empty hash map did not fail"); 92 // Make sure inserting values work 93 for (int i = 0; i < 8; ++i) 94 Assert.IsTrue(hashMap.TryAdd(i, i * i), "Failed to add value"); 95 // The bucket size is capacity * 2, adding that number should result in hash collisions 96 for (int i = 0; i < 8; ++i) 97 Assert.IsTrue(hashMap.TryAdd(i + 32, i), "Failed to add value with potential hash collision"); 98 // Make sure reading the inserted values work 99 for (int i = 0; i < 8; ++i) 100 { 101 Assert.IsTrue(hashMap.TryGetValue(i, out iSquared), "Failed get value from hash table"); 102 Assert.AreEqual(iSquared, i * i, "Got the wrong value from the hash table"); 103 } 104 for (int i = 0; i < 8; ++i) 105 { 106 Assert.IsTrue(hashMap.TryGetValue(i + 32, out iSquared), "Failed get value from hash table"); 107 Assert.AreEqual(iSquared, i, "Got the wrong value from the hash table"); 108 } 109 hashMap.Dispose(); 110 } 111 112 [StructLayout(LayoutKind.Explicit)] 113 unsafe struct LargeKey : IEquatable<LargeKey> 114 { 115 [FieldOffset(0)] 116 public int* Ptr; 117 118 [FieldOffset(300)] 119 int x; 120 121 public bool Equals(LargeKey rhs) 122 { 123 return Ptr == rhs.Ptr; 124 } 125 public override int GetHashCode() 126 { 127 return (int)Ptr; 128 } 129 } 130 131 [Test] 132 public void NativeHashMap_HashMapSupportsAutomaticCapacityChange() 133 { 134 var hashMap = new NativeHashMap<int, int>(1, Allocator.Temp); 135 int iSquared; 136 // Make sure inserting values work and grows the capacity 137 for (int i = 0; i < 8; ++i) 138 Assert.IsTrue(hashMap.TryAdd(i, i * i), "Failed to add value"); 139 Assert.IsTrue(hashMap.Capacity >= 8, "Capacity was not updated correctly"); 140 // Make sure reading the inserted values work 141 for (int i = 0; i < 8; ++i) 142 { 143 Assert.IsTrue(hashMap.TryGetValue(i, out iSquared), "Failed get value from hash table"); 144 Assert.AreEqual(iSquared, i * i, "Got the wrong value from the hash table"); 145 } 146 hashMap.Dispose(); 147 } 148 149 [Test] 150 [TestRequiresDotsDebugOrCollectionChecks] 151 public void NativeHashMap_HashMapSameKey() 152 { 153 using (var hashMap = new NativeHashMap<int, int>(0, Allocator.Persistent)) 154 { 155 Assert.DoesNotThrow(() => hashMap.Add(0, 0)); 156 Assert.Throws<ArgumentException>(() => hashMap.Add(0, 0)); 157 } 158 159 using (var hashMap = new NativeHashMap<int, int>(0, Allocator.Persistent)) 160 { 161 Assert.IsTrue(hashMap.TryAdd(0, 0)); 162 Assert.IsFalse(hashMap.TryAdd(0, 0)); 163 } 164 } 165 166 [Test] 167 public void NativeHashMap_IsEmpty() 168 { 169 var container = new NativeHashMap<int, int>(0, Allocator.Persistent); 170 Assert.IsTrue(container.IsEmpty); 171 172 container.TryAdd(0, 0); 173 Assert.IsFalse(container.IsEmpty); 174 Assert.AreNotEqual(0, container.Capacity); 175 ExpectedCount(ref container, 1); 176 177 container.Remove(0); 178 Assert.IsTrue(container.IsEmpty); 179 180 container.TryAdd(0, 0); 181 container.Clear(); 182 Assert.IsTrue(container.IsEmpty); 183 184 container.Dispose(); 185 } 186 187 [Test] 188 public void NativeHashMap_HashMapEmptyCapacity() 189 { 190 var hashMap = new NativeHashMap<int, int>(0, Allocator.Persistent); 191 hashMap.TryAdd(0, 0); 192 Assert.AreNotEqual(0, hashMap.Capacity); 193 ExpectedCount(ref hashMap, 1); 194 hashMap.Dispose(); 195 } 196 197 [Test] 198 public void NativeHashMap_Remove() 199 { 200 var hashMap = new NativeHashMap<int, int>(8, Allocator.Temp); 201 int iSquared; 202 // Make sure inserting values work 203 for (int i = 0; i < 8; ++i) 204 { 205 Assert.IsTrue(hashMap.TryAdd(i, i * i), "Failed to add value"); 206 } 207 208 // Make sure reading the inserted values work 209 for (int i = 0; i < 8; ++i) 210 { 211 Assert.IsTrue(hashMap.TryGetValue(i, out iSquared), "Failed get value from hash table"); 212 Assert.AreEqual(iSquared, i * i, "Got the wrong value from the hash table"); 213 } 214 for (int rm = 0; rm < 8; ++rm) 215 { 216 Assert.IsTrue(hashMap.Remove(rm)); 217 Assert.IsFalse(hashMap.TryGetValue(rm, out iSquared), "Failed to remove value from hash table"); 218 for (int i = rm + 1; i < 8; ++i) 219 { 220 Assert.IsTrue(hashMap.TryGetValue(i, out iSquared), "Failed get value from hash table"); 221 Assert.AreEqual(iSquared, i * i, "Got the wrong value from the hash table"); 222 } 223 } 224 // Make sure entries were freed 225 for (int i = 0; i < 8; ++i) 226 { 227 Assert.IsTrue(hashMap.TryAdd(i, i * i), "Failed to add value"); 228 } 229 230 hashMap.Dispose(); 231 } 232 233 [Test] 234 public void NativeHashMap_RemoveOnEmptyMap_DoesNotThrow() 235 { 236 var hashMap = new NativeHashMap<int, int>(0, Allocator.Temp); 237 Assert.DoesNotThrow(() => hashMap.Remove(0)); 238 Assert.DoesNotThrow(() => hashMap.Remove(-425196)); 239 hashMap.Dispose(); 240 } 241 242 [Test] 243 public void NativeHashMap_TryAddScalability() 244 { 245 var hashMap = new NativeHashMap<int, int>(1, Allocator.Persistent); 246 for (int i = 0; i != 1000 * 100; i++) 247 { 248 hashMap.TryAdd(i, i); 249 } 250 251 int value; 252 Assert.IsFalse(hashMap.TryGetValue(-1, out value)); 253 Assert.IsFalse(hashMap.TryGetValue(1000 * 1000, out value)); 254 255 for (int i = 0; i != 1000 * 100; i++) 256 { 257 Assert.IsTrue(hashMap.TryGetValue(i, out value)); 258 Assert.AreEqual(i, value); 259 } 260 261 hashMap.Dispose(); 262 } 263 264 [Test] 265 public void NativeHashMap_GetKeysEmpty() 266 { 267 var hashMap = new NativeHashMap<int, int>(1, Allocator.Temp); 268 var keys = hashMap.GetKeyArray(Allocator.Temp); 269 hashMap.Dispose(); 270 271 Assert.AreEqual(0, keys.Length); 272 keys.Dispose(); 273 } 274 275 [Test] 276 public void NativeHashMap_GetKeys() 277 { 278 var hashMap = new NativeHashMap<int, int>(1, Allocator.Temp); 279 for (int i = 0; i < 30; ++i) 280 { 281 hashMap.TryAdd(i, 2 * i); 282 } 283 var keys = hashMap.GetKeyArray(Allocator.Temp); 284 hashMap.Dispose(); 285 286 Assert.AreEqual(30, keys.Length); 287 keys.Sort(); 288 for (int i = 0; i < 30; ++i) 289 { 290 Assert.AreEqual(i, keys[i]); 291 } 292 keys.Dispose(); 293 } 294 295 [Test] 296 public void NativeHashMap_GetValues() 297 { 298 var hashMap = new NativeHashMap<int, int>(1, Allocator.Temp); 299 for (int i = 0; i < 30; ++i) 300 { 301 hashMap.TryAdd(i, 2 * i); 302 } 303 var values = hashMap.GetValueArray(Allocator.Temp); 304 hashMap.Dispose(); 305 306 Assert.AreEqual(30, values.Length); 307 values.Sort(); 308 for (int i = 0; i < 30; ++i) 309 { 310 Assert.AreEqual(2 * i, values[i]); 311 } 312 values.Dispose(); 313 } 314 315 [Test] 316 public void NativeHashMap_GetKeysAndValues() 317 { 318 var hashMap = new NativeHashMap<int, int>(1, Allocator.Temp); 319 for (int i = 0; i < 30; ++i) 320 { 321 hashMap.TryAdd(i, 2 * i); 322 } 323 var keysValues = hashMap.GetKeyValueArrays(Allocator.Temp); 324 hashMap.Dispose(); 325 326 Assert.AreEqual(30, keysValues.Keys.Length); 327 Assert.AreEqual(30, keysValues.Values.Length); 328 329 // ensure keys and matching values are aligned 330 for (int i = 0; i < 30; ++i) 331 { 332 Assert.AreEqual(2 * keysValues.Keys[i], keysValues.Values[i]); 333 } 334 335 keysValues.Keys.Sort(); 336 for (int i = 0; i < 30; ++i) 337 { 338 Assert.AreEqual(i, keysValues.Keys[i]); 339 } 340 341 keysValues.Values.Sort(); 342 for (int i = 0; i < 30; ++i) 343 { 344 Assert.AreEqual(2 * i, keysValues.Values[i]); 345 } 346 347 keysValues.Dispose(); 348 } 349 350 public struct TestEntityGuid : IEquatable<TestEntityGuid>, IComparable<TestEntityGuid> 351 { 352 public ulong a; 353 public ulong b; 354 355 public bool Equals(TestEntityGuid other) 356 { 357 return a == other.a && b == other.b; 358 } 359 360 public override int GetHashCode() 361 { 362 unchecked 363 { 364 return (a.GetHashCode() * 397) ^ b.GetHashCode(); 365 } 366 } 367 368 public int CompareTo(TestEntityGuid other) 369 { 370 var aComparison = a.CompareTo(other.a); 371 if (aComparison != 0) return aComparison; 372 return b.CompareTo(other.b); 373 } 374 } 375 376 [Test] 377 public void NativeHashMap_GetKeysGuid() 378 { 379 var hashMap = new NativeHashMap<TestEntityGuid, int>(1, Allocator.Temp); 380 for (int i = 0; i < 30; ++i) 381 { 382 var didAdd = hashMap.TryAdd(new TestEntityGuid() { a = (ulong)i * 5, b = 3 * (ulong)i }, 2 * i); 383 Assert.IsTrue(didAdd); 384 } 385 386 // Validate Hashtable has all the expected values 387 ExpectedCount(ref hashMap, 30); 388 for (int i = 0; i < 30; ++i) 389 { 390 int output; 391 var exists = hashMap.TryGetValue(new TestEntityGuid() { a = (ulong)i * 5, b = 3 * (ulong)i }, out output); 392 Assert.IsTrue(exists); 393 Assert.AreEqual(2 * i, output); 394 } 395 396 // Validate keys array 397 var keys = hashMap.GetKeyArray(Allocator.Temp); 398 Assert.AreEqual(30, keys.Length); 399 400 keys.Sort(); 401 for (int i = 0; i < 30; ++i) 402 { 403 Assert.AreEqual(new TestEntityGuid() { a = (ulong)i * 5, b = 3 * (ulong)i }, keys[i]); 404 } 405 406 hashMap.Dispose(); 407 keys.Dispose(); 408 } 409 410 [Test] 411 public void NativeHashMap_IndexerWorks() 412 { 413 var hashMap = new NativeHashMap<int, int>(1, Allocator.Temp); 414 hashMap[5] = 7; 415 Assert.AreEqual(7, hashMap[5]); 416 417 hashMap[5] = 9; 418 Assert.AreEqual(9, hashMap[5]); 419 420 hashMap.Dispose(); 421 } 422 423 [Test] 424 public void NativeHashMap_ContainsKeyHashMap() 425 { 426 var hashMap = new NativeHashMap<int, int>(1, Allocator.Temp); 427 hashMap[5] = 7; 428 429 Assert.IsTrue(hashMap.ContainsKey(5)); 430 Assert.IsFalse(hashMap.ContainsKey(6)); 431 432 hashMap.Dispose(); 433 } 434 435 [Test] 436 [TestRequiresCollectionChecks] 437 public void NativeHashMap_UseAfterFree_UsesCustomOwnerTypeName() 438 { 439 var container = new NativeHashMap<int, int>(10, CommonRwdAllocator.Handle); 440 container[0] = 123; 441 container.Dispose(); 442 NUnit.Framework.Assert.That(() => container[0], 443 Throws.Exception.TypeOf<ObjectDisposedException>() 444 .With.Message.Contains($"The {container.GetType()} has been deallocated")); 445 } 446 447 [BurstCompile(CompileSynchronously = true)] 448 struct NativeHashMap_CreateAndUseAfterFreeBurst : IJob 449 { 450 public void Execute() 451 { 452 var container = new NativeHashMap<int, int>(10, Allocator.Temp); 453 container[0] = 17; 454 container.Dispose(); 455 container[1] = 42; 456 } 457 } 458 459 [Test] 460 [TestRequiresCollectionChecks] 461 public void NativeHashMap_CreateAndUseAfterFreeInBurstJob_UsesCustomOwnerTypeName() 462 { 463 // Make sure this isn't the first container of this type ever created, so that valid static safety data exists 464 var container = new NativeHashMap<int, int>(10, CommonRwdAllocator.Handle); 465 container.Dispose(); 466 467 var job = new NativeHashMap_CreateAndUseAfterFreeBurst 468 { 469 }; 470 471 // Two things: 472 // 1. This exception is logged, not thrown; thus, we use LogAssert to detect it. 473 // 2. Calling write operation after container.Dispose() emits an unintuitive error message. For now, all this test cares about is whether it contains the 474 // expected type name. 475 job.Run(); 476 LogAssert.Expect(LogType.Exception, 477 new Regex($"InvalidOperationException: The {Regex.Escape(container.GetType().ToString())} has been declared as \\[ReadOnly\\] in the job, but you are writing to it")); 478 } 479 480 [Test] 481 public void NativeHashMap_ForEach_FixedStringInHashMap() 482 { 483 using (var stringList = new NativeList<FixedString32Bytes>(10, Allocator.Persistent) { "Hello", ",", "World", "!" }) 484 { 485 var seen = new NativeArray<int>(stringList.Length, Allocator.Temp); 486 var container = new NativeHashMap<FixedString128Bytes, float>(50, Allocator.Temp); 487 foreach (var str in stringList) 488 { 489 container.Add(str, 0); 490 } 491 492 foreach (var pair in container) 493 { 494 int index = stringList.IndexOf(pair.Key); 495 Assert.AreEqual(stringList[index], pair.Key.ToString()); 496 seen[index] = seen[index] + 1; 497 } 498 499 for (int i = 0; i < stringList.Length; i++) 500 { 501 Assert.AreEqual(1, seen[i], $"Incorrect value count {stringList[i]}"); 502 } 503 } 504 } 505 506 [Test] 507 public void NativeHashMap_EnumeratorDoesNotReturnRemovedElementsTest() 508 { 509 NativeHashMap<int, int> container = new NativeHashMap<int, int>(5, Allocator.Temp); 510 for (int i = 0; i < 5; i++) 511 { 512 container.Add(i, i); 513 } 514 515 int elementToRemove = 2; 516 container.Remove(elementToRemove); 517 518 using (var enumerator = container.GetEnumerator()) 519 { 520 while (enumerator.MoveNext()) 521 { 522 Assert.AreNotEqual(elementToRemove, enumerator.Current.Key); 523 } 524 } 525 526 container.Dispose(); 527 } 528 529 [Test] 530 public void NativeHashMap_EnumeratorInfiniteIterationTest() 531 { 532 NativeHashMap<int, int> container = new NativeHashMap<int, int>(5, Allocator.Temp); 533 for (int i = 0; i < 5; i++) 534 { 535 container.Add(i, i); 536 } 537 538 for (int i = 0; i < 2; i++) 539 { 540 container.Remove(i); 541 } 542 543 var expected = container.Count; 544 int count = 0; 545 using (var enumerator = container.GetEnumerator()) 546 { 547 while (enumerator.MoveNext()) 548 { 549 if (count++ > expected) 550 { 551 break; 552 } 553 } 554 } 555 556 Assert.AreEqual(expected, count); 557 container.Dispose(); 558 } 559 560 [Test] 561 public void NativeHashMap_ForEach([Values(10, 1000)] int n) 562 { 563 var seen = new NativeArray<int>(n, Allocator.Temp); 564 using (var container = new NativeHashMap<int, int>(32, CommonRwdAllocator.Handle)) 565 { 566 for (int i = 0; i < n; i++) 567 { 568 container.Add(i, i * 37); 569 } 570 571 var count = 0; 572 foreach (var kv in container) 573 { 574 int value; 575 Assert.True(container.TryGetValue(kv.Key, out value)); 576 Assert.AreEqual(value, kv.Value); 577 Assert.AreEqual(kv.Key * 37, kv.Value); 578 579 seen[kv.Key] = seen[kv.Key] + 1; 580 ++count; 581 } 582 583 Assert.AreEqual(container.Count, count); 584 for (int i = 0; i < n; i++) 585 { 586 Assert.AreEqual(1, seen[i], $"Incorrect key count {i}"); 587 } 588 } 589 } 590 591 struct NativeHashMap_ForEach_Job : IJob 592 { 593 public NativeHashMap<int, int>.ReadOnly Input; 594 595 [ReadOnly] 596 public int Num; 597 598 public void Execute() 599 { 600 var seen = new NativeArray<int>(Num, Allocator.Temp); 601 602 var count = 0; 603 foreach (var kv in Input) 604 { 605 int value; 606 Assert.True(Input.TryGetValue(kv.Key, out value)); 607 Assert.AreEqual(value, kv.Value); 608 Assert.AreEqual(kv.Key * 37, kv.Value); 609 610 seen[kv.Key] = seen[kv.Key] + 1; 611 ++count; 612 } 613 614 Assert.AreEqual(Input.Count, count); 615 for (int i = 0; i < Num; i++) 616 { 617 Assert.AreEqual(1, seen[i], $"Incorrect key count {i}"); 618 } 619 620 seen.Dispose(); 621 } 622 } 623 624 [Test] 625 public void NativeHashMap_ForEach_From_Job([Values(10, 1000)] int n) 626 { 627 var seen = new NativeArray<int>(n, Allocator.Temp); 628 using (var container = new NativeHashMap<int, int>(32, CommonRwdAllocator.Handle)) 629 { 630 for (int i = 0; i < n; i++) 631 { 632 container.Add(i, i * 37); 633 } 634 635 new NativeHashMap_ForEach_Job 636 { 637 Input = container.AsReadOnly(), 638 Num = n, 639 640 }.Run(); 641 } 642 } 643 644 struct NativeHashMap_Write_Job : IJob 645 { 646 public NativeHashMap<int, int> Input; 647 648 public void Execute() 649 { 650 Input.Clear(); 651 } 652 } 653 654 [Test] 655 public void NativeHashMap_Write_From_Job() 656 { 657 using (var container = new NativeHashMap<int, int>(32, CommonRwdAllocator.Handle)) 658 { 659 container.Add(1, 37); 660 Assert.IsFalse(container.IsEmpty); 661 new NativeHashMap_Write_Job 662 { 663 Input = container, 664 }.Run(); 665 Assert.IsTrue(container.IsEmpty); 666 } 667 } 668 669 [Test] 670 [TestRequiresCollectionChecks] 671 public void NativeHashMap_ForEach_Throws_When_Modified() 672 { 673 using (var container = new NativeHashMap<int, int>(32, CommonRwdAllocator.Handle)) 674 { 675 container.Add(0, 012); 676 container.Add(1, 123); 677 container.Add(2, 234); 678 container.Add(3, 345); 679 container.Add(4, 456); 680 container.Add(5, 567); 681 container.Add(6, 678); 682 container.Add(7, 789); 683 container.Add(8, 890); 684 container.Add(9, 901); 685 686 Assert.Throws<ObjectDisposedException>(() => 687 { 688 foreach (var kv in container) 689 { 690 container.Add(10, 10); 691 } 692 }); 693 694 Assert.Throws<ObjectDisposedException>(() => 695 { 696 foreach (var kv in container) 697 { 698 container.Remove(1); 699 } 700 }); 701 } 702 } 703 704 struct NativeHashMap_ForEachIterator : IJob 705 { 706 [ReadOnly] 707 public NativeHashMap<int, int>.Enumerator Iter; 708 709 public void Execute() 710 { 711 while (Iter.MoveNext()) 712 { 713 } 714 } 715 } 716 717 [Test] 718 [TestRequiresCollectionChecks] 719 public void NativeHashMap_ForEach_Throws_Job_Iterator() 720 { 721 using (var container = new NativeHashMap<int, int>(32, CommonRwdAllocator.Handle)) 722 { 723 var jobHandle = new NativeHashMap_ForEachIterator 724 { 725 Iter = container.GetEnumerator() 726 727 }.Schedule(); 728 729 Assert.Throws<InvalidOperationException>(() => { container.Add(1, 1); }); 730 731 jobHandle.Complete(); 732 } 733 } 734 735 [Test] 736 public void NativeHashMap_CustomAllocatorTest() 737 { 738 AllocatorManager.Initialize(); 739 var allocatorHelper = new AllocatorHelper<CustomAllocatorTests.CountingAllocator>(AllocatorManager.Persistent); 740 ref var allocator = ref allocatorHelper.Allocator; 741 allocator.Initialize(); 742 743 using (var container = new NativeHashMap<int, int>(1, allocator.Handle)) 744 { 745 } 746 747 Assert.IsTrue(allocator.WasUsed); 748 allocator.Dispose(); 749 allocatorHelper.Dispose(); 750 AllocatorManager.Shutdown(); 751 } 752 753 [BurstCompile] 754 struct BurstedCustomAllocatorJob : IJob 755 { 756 [NativeDisableUnsafePtrRestriction] 757 public unsafe CustomAllocatorTests.CountingAllocator* Allocator; 758 759 public void Execute() 760 { 761 unsafe 762 { 763 using (var container = new NativeHashMap<int, int>(1, Allocator->Handle)) 764 { 765 } 766 } 767 } 768 } 769 770 [Test] 771 public unsafe void NativeHashMap_BurstedCustomAllocatorTest() 772 { 773 AllocatorManager.Initialize(); 774 var allocatorHelper = new AllocatorHelper<CustomAllocatorTests.CountingAllocator>(AllocatorManager.Persistent); 775 ref var allocator = ref allocatorHelper.Allocator; 776 allocator.Initialize(); 777 778 var allocatorPtr = (CustomAllocatorTests.CountingAllocator*)UnsafeUtility.AddressOf<CustomAllocatorTests.CountingAllocator>(ref allocator); 779 unsafe 780 { 781 var handle = new BurstedCustomAllocatorJob { Allocator = allocatorPtr }.Schedule(); 782 handle.Complete(); 783 } 784 785 Assert.IsTrue(allocator.WasUsed); 786 allocator.Dispose(); 787 allocatorHelper.Dispose(); 788 AllocatorManager.Shutdown(); 789 } 790 791 public struct NestedHashMap 792 { 793 public NativeHashMap<int, int> map; 794 } 795 796 [Test] 797 public void NativeHashMap_Nested() 798 { 799 var mapInner = new NativeHashMap<int, int>(16, CommonRwdAllocator.Handle); 800 NestedHashMap mapStruct = new NestedHashMap { map = mapInner }; 801 802 var mapNestedStruct = new NativeHashMap<int, NestedHashMap>(16, CommonRwdAllocator.Handle); 803 var mapNested = new NativeHashMap<int, NativeHashMap<int, int>>(16, CommonRwdAllocator.Handle); 804 805 mapNested[14] = mapInner; 806 mapNestedStruct[17] = mapStruct; 807 808 mapNested.Dispose(); 809 mapNestedStruct.Dispose(); 810 mapInner.Dispose(); 811 } 812 813 [Test] 814 public void NativeHashMap_ForEach_FixedStringKey() 815 { 816 using (var stringList = new NativeList<FixedString32Bytes>(10, Allocator.Persistent) { "Hello", ",", "World", "!" }) 817 { 818 var seen = new NativeArray<int>(stringList.Length, Allocator.Temp); 819 var container = new NativeHashMap<FixedString128Bytes, float>(50, Allocator.Temp); 820 foreach (var str in stringList) 821 { 822 container.Add(str, 0); 823 } 824 825 foreach (var pair in container) 826 { 827 int index = stringList.IndexOf(pair.Key); 828 Assert.AreEqual(stringList[index], pair.Key.ToString()); 829 seen[index] = seen[index] + 1; 830 } 831 832 for (int i = 0; i < stringList.Length; i++) 833 { 834 Assert.AreEqual(1, seen[i], $"Incorrect value count {stringList[i]}"); 835 } 836 } 837 } 838 [Test] 839 public void NativeHashMap_SupportsAutomaticCapacityChange() 840 { 841 var container = new NativeHashMap<int, int>(1, Allocator.Temp); 842 int iSquared; 843 844 // Make sure inserting values work and grows the capacity 845 for (int i = 0; i < 8; ++i) 846 { 847 Assert.IsTrue(container.TryAdd(i, i * i), "Failed to add value"); 848 } 849 Assert.IsTrue(container.Capacity >= 8, "Capacity was not updated correctly"); 850 851 // Make sure reading the inserted values work 852 for (int i = 0; i < 8; ++i) 853 { 854 Assert.IsTrue(container.TryGetValue(i, out iSquared), "Failed get value from hash table"); 855 Assert.AreEqual(iSquared, i * i, "Got the wrong value from the hash table"); 856 } 857 858 container.Dispose(); 859 } 860 861 [Test] 862 [TestRequiresDotsDebugOrCollectionChecks] 863 public void NativeHashMap_SameKey() 864 { 865 using (var container = new NativeHashMap<int, int>(0, Allocator.Persistent)) 866 { 867 Assert.DoesNotThrow(() => container.Add(0, 0)); 868 Assert.Throws<ArgumentException>(() => container.Add(0, 0)); 869 } 870 871 using (var container = new NativeHashMap<int, int>(0, Allocator.Persistent)) 872 { 873 Assert.IsTrue(container.TryAdd(0, 0)); 874 Assert.IsFalse(container.TryAdd(0, 0)); 875 } 876 } 877 878 [Test] 879 public void NativeHashMap_EmptyCapacity() 880 { 881 var container = new NativeHashMap<int, int>(0, Allocator.Persistent); 882 container.TryAdd(0, 0); 883 ExpectedCount(ref container, 1); 884 container.Dispose(); 885 } 886 887 [Test] 888 public unsafe void NativeHashMap_TrimExcess() 889 { 890 using (var container = new NativeHashMap<int, int>(1024, Allocator.Persistent)) 891 { 892 var oldCapacity = container.Capacity; 893 894 container.Add(123, 345); 895 container.TrimExcess(); 896 Assert.AreEqual(1, container.Count); 897 Assert.AreNotEqual(oldCapacity, container.Capacity); 898 899 oldCapacity = container.Capacity; 900 901 container.Remove(123); 902 Assert.AreEqual(container.Count, 0); 903 container.TrimExcess(); 904 Assert.AreEqual(oldCapacity, container.Capacity); 905 906 container.Add(123, 345); 907 Assert.AreEqual(container.Count, 1); 908 Assert.AreEqual(oldCapacity, container.Capacity); 909 910 container.Clear(); 911 Assert.AreEqual(container.Count, 0); 912 Assert.AreEqual(oldCapacity, container.Capacity); 913 } 914 } 915 916 [Test] 917 public void NativeHashMap_DisposeJob() 918 { 919 var container0 = new NativeHashMap<int, int>(1, Allocator.Persistent); 920 Assert.True(container0.IsCreated); 921 Assert.DoesNotThrow(() => { container0.Add(0, 1); }); 922 Assert.True(container0.ContainsKey(0)); 923 924 var container1 = new NativeHashMap<int, int>(1, Allocator.Persistent); 925 Assert.True(container1.IsCreated); 926 Assert.DoesNotThrow(() => { container1.Add(1, 2); }); 927 Assert.True(container1.ContainsKey(1)); 928 929 var disposeJob0 = container0.Dispose(default); 930 Assert.False(container0.IsCreated); 931#if ENABLE_UNITY_COLLECTIONS_CHECKS 932 Assert.Throws<ObjectDisposedException>( 933 () => { container0.ContainsKey(0); }); 934#endif 935 936 var disposeJob = container1.Dispose(disposeJob0); 937 Assert.False(container1.IsCreated); 938#if ENABLE_UNITY_COLLECTIONS_CHECKS 939 Assert.Throws<ObjectDisposedException>( 940 () => { container1.ContainsKey(1); }); 941#endif 942 943 disposeJob.Complete(); 944 } 945 946 [Test] 947 public void NativeHashMap_CanInsertSentinelValue() 948 { 949 var map = new NativeHashMap<uint, int>(32, Allocator.Temp); 950 map.Add(uint.MaxValue, 123); 951 FastAssert.AreEqual(1, map.Count); 952 int v; 953 FastAssert.IsTrue(map.TryGetValue(uint.MaxValue, out v)); 954 FastAssert.AreEqual(123, v); 955 map.Dispose(); 956 } 957 958 [Test] 959 public void NativeHashMap_SoakTest([Values(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)] int s) 960 { 961 Unity.Mathematics.Random rng = Unity.Mathematics.Random.CreateFromIndex((uint)s); 962 var d = new System.Collections.Generic.Dictionary<ulong, int>(); 963 var map = new NativeHashMap<ulong, int>(32, Allocator.Temp); 964 var list = new NativeList<ulong>(32, Allocator.Temp); 965 966 unsafe ulong NextULong(ref Unity.Mathematics.Random rng) 967 { 968 var u = rng.NextUInt2(); 969 return *(ulong*)&u; 970 } 971 972 for (int i = 0; i < 200; i++) 973 { 974 var x = NextULong(ref rng); 975 while (d.ContainsKey(x)) 976 x = NextULong(ref rng); 977 d.Add(x, list.Length); 978 map.Add(x, list.Length); 979 list.Add(x); 980 } 981 FastAssert.AreEqual(d.Count, list.Length); 982 FastAssert.AreEqual(map.Count, list.Length); 983 foreach (var kvp in d) 984 { 985 FastAssert.IsTrue(map.TryGetValue(kvp.Key, out var v)); 986 FastAssert.AreEqual(kvp.Value, v); 987 } 988 989 for (int i = 0; i < 10000; i++) 990 { 991 float removeProb = list.Length == 0 ? 0 : 0.5f; 992 if (rng.NextFloat() <= removeProb) 993 { 994 // remove value 995 int index = rng.NextInt(list.Length); 996 var key = list[index]; 997 list.RemoveAtSwapBack(index); 998 FastAssert.IsTrue(d.TryGetValue(key, out var idx1)); 999 FastAssert.IsTrue(d.Remove(key)); 1000 FastAssert.IsTrue(map.TryGetValue(key, out var idx2)); 1001 FastAssert.AreEqual(idx1, idx2); 1002 map.Remove(key); 1003 if (index < list.Length) 1004 { 1005 d[list[index]] = index; 1006 map[list[index]] = index; 1007 } 1008 } 1009 else 1010 { 1011 // add value 1012 var x = NextULong(ref rng); 1013 while (d.ContainsKey(x)) 1014 x = NextULong(ref rng); 1015 d.Add(x, list.Length); 1016 map.Add(x, list.Length); 1017 list.Add(x); 1018 } 1019 FastAssert.AreEqual(d.Count, list.Length); 1020 FastAssert.AreEqual(map.Count, list.Length); 1021 } 1022 } 1023 1024 [Test] 1025 public void NativeHashMap_IndexerAdd_ResizesContainer() 1026 { 1027 var container = new NativeHashMap<int, int>(8, Allocator.Persistent); 1028 for (int i = 0; i < 1024; i++) 1029 { 1030 container[i] = i; 1031 } 1032 Assert.AreEqual(1024, container.Count); 1033 container.Dispose(); 1034 } 1035}