-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathNativeHashSet.cs
1193 lines (1079 loc) · 39.5 KB
/
NativeHashSet.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//-----------------------------------------------------------------------
// <copyright file="NativeHashSet.cs" company="Jackson Dunstan">
// Copyright (c) Jackson Dunstan. See LICENSE.md.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
namespace JacksonDunstan.NativeCollections
{
/// <summary>
/// The state of a <see cref="NativeHashSet{T}"/>. Shared among instances
/// of the struct via a pointer to unmanaged memory. This has no type
/// parameters, so it can be used by all set types.
/// </summary>
[StructLayout(LayoutKind.Explicit)]
internal unsafe struct NativeHashSetState
{
/// <summary>
/// Item data
/// </summary>
[FieldOffset(0)]
internal byte* Items;
// 4-byte padding on 32-bit architectures here
/// <summary>
/// Next bucket data
/// </summary>
[FieldOffset(8)]
internal byte* Next;
// 4-byte padding on 32-bit architectures here
/// <summary>
/// Bucket data
/// </summary>
[FieldOffset(16)]
internal byte* Buckets;
// 4-byte padding on 32-bit architectures here
/// <summary>
/// Capacity of the <see cref="Items"/> array
/// </summary>
[FieldOffset(24)]
internal int ItemCapacity;
/// <summary>
/// Bucket capacity - 1
/// </summary>
[FieldOffset(28)]
internal int BucketCapacityMask;
/// <summary>
/// Allocated index length
/// </summary>
[FieldOffset(32)]
internal int AllocatedIndexLength;
/// <summary>
/// Array indexed by thread index of first free
/// </summary>
[FieldOffset(JobsUtility.CacheLineSize < 64 ? 64 : JobsUtility.CacheLineSize)]
internal fixed int FirstFreeTLS[JobsUtility.MaxJobThreadCount * IntsPerCacheLine];
/// <summary>
/// Number of ints that fit in one cache line
/// </summary>
internal const int IntsPerCacheLine = JobsUtility.CacheLineSize / sizeof(int);
}
/// <summary>
/// A hash set native collection.
/// </summary>
///
/// <typeparam name="T">
/// Type of items in the set. Must be blittable.
/// </typeparam>
[NativeContainer]
[DebuggerDisplay("Length = {Length}. Capacity = {Capacity}")]
[DebuggerTypeProxy(typeof(NativeHashSetDebugView<>))]
[StructLayout(LayoutKind.Sequential)]
public unsafe struct NativeHashSet<T> : IDisposable
#if CSHARP_7_3_OR_NEWER
where T : unmanaged
#else
where T : struct
#endif
, IEquatable<T>
{
/// <summary>
/// Iterator over the set
/// </summary>
private struct NativeMultiHashSetIterator
{
/// <summary>
/// Currently iterated item
/// </summary>
internal T Item;
/// <summary>
/// Index of the next entry in the set
/// </summary>
internal int NextEntryIndex;
}
/// <summary>
/// State of the set or null if the list is created with the default
/// constructor or <see cref="Dispose()"/> has been called. This is
/// shared among all instances of the set.
/// </summary>
[NativeDisableUnsafePtrRestriction]
NativeHashSetState* m_State;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
/// <summary>
/// A handle to information about what operations can be safely
/// performed on the set at any given time.
/// </summary>
AtomicSafetyHandle m_Safety;
/// <summary>
/// A handle that can be used to tell if the set has been disposed yet
/// or not, which allows for error-checking double disposal.
/// </summary>
[NativeSetClassTypeToNullOnSchedule]
DisposeSentinel m_DisposeSentinel;
#endif
/// <summary>
/// Allocator to allocate unmanaged memory with
/// </summary>
readonly Allocator m_Allocator;
/// <summary>
/// Create an empty hash set with a given capacity
/// </summary>
///
/// <param name="capacity">
/// Capacity of the hash set. If less than four, four is used.
/// </param>
///
/// <param name="allocator">
/// Allocator to allocate unmanaged memory with. Must be valid.
/// </param>
public NativeHashSet(int capacity, Allocator allocator)
{
// Require a valid allocator
if (allocator <= Allocator.None)
{
throw new ArgumentException(
"Allocator must be Temp, TempJob or Persistent",
"allocator");
}
RequireBlittable();
// Insist on a minimum capacity
if (capacity < 4)
{
capacity = 4;
}
m_Allocator = allocator;
// Allocate the state
NativeHashSetState* state = (NativeHashSetState*)UnsafeUtility.Malloc(
sizeof(NativeHashSetState),
UnsafeUtility.AlignOf<NativeHashSetState>(),
allocator);
state->ItemCapacity = capacity;
// To reduce collisions, use twice as many buckets
int bucketLength = capacity * 2;
bucketLength = NextHigherPowerOfTwo(bucketLength);
state->BucketCapacityMask = bucketLength - 1;
// Allocate state arrays
int nextOffset;
int bucketOffset;
int totalSize = CalculateDataLayout(
capacity,
bucketLength,
out nextOffset,
out bucketOffset);
state->Items = (byte*)UnsafeUtility.Malloc(
totalSize,
JobsUtility.CacheLineSize,
allocator);
state->Next = state->Items + nextOffset;
state->Buckets = state->Items + bucketOffset;
m_State = state;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
#if UNITY_2018_3_OR_NEWER
DisposeSentinel.Create(
out m_Safety,
out m_DisposeSentinel,
1,
allocator);
#else
DisposeSentinel.Create(
out m_Safety,
out m_DisposeSentinel,
1);
#endif
#endif
Clear();
}
/// <summary>
/// Get the number of items in the set.
///
/// This operation requires read access.
/// </summary>
public int Length
{
get
{
RequireReadAccess();
NativeHashSetState* state = m_State;
int* nextPtrs = (int*)state->Next;
int freeListSize = 0;
for (int tls = 0; tls < JobsUtility.MaxJobThreadCount; ++tls)
{
for (int freeIdx = state->FirstFreeTLS[tls * NativeHashSetState.IntsPerCacheLine];
freeIdx >= 0;
freeIdx = nextPtrs[freeIdx])
{
++freeListSize;
}
}
return Math.Min(state->ItemCapacity, state->AllocatedIndexLength) - freeListSize;
}
}
/// <summary>
/// Get or set the set's capacity to hold items. The capacity can't be
/// set to be lower than it currently is.
///
/// The 'get' operation requires read access and the 'set' operation
/// requires write access.
/// </summary>
public int Capacity
{
get
{
RequireReadAccess();
return m_State->ItemCapacity;
}
set
{
RequireWriteAccess();
Reallocate(value);
}
}
/// <summary>
/// Try to add an item to the set.
///
/// This operation requires write access.
/// </summary>
///
/// <param name="item">
/// Item to add
/// </param>
///
/// <returns>
/// If the item was added to the set. This is false only if the item was
/// already in the set.</returns>
public bool TryAdd(T item)
{
RequireWriteAccess();
NativeMultiHashSetIterator tempIt;
if (TryGetFirstValueAtomic(m_State, item, out tempIt))
{
return false;
}
// Allocate an entry from the free list
int idx;
int* nextPtrs;
if (m_State->AllocatedIndexLength >= m_State->ItemCapacity
&& m_State->FirstFreeTLS[0] < 0)
{
for (int tls = 1; tls < JobsUtility.MaxJobThreadCount; ++tls)
{
if (m_State->FirstFreeTLS[tls * NativeHashSetState.IntsPerCacheLine] >= 0)
{
idx = m_State->FirstFreeTLS[tls * NativeHashSetState.IntsPerCacheLine];
nextPtrs = (int*)m_State->Next;
m_State->FirstFreeTLS[tls * NativeHashSetState.IntsPerCacheLine] = nextPtrs[idx];
nextPtrs[idx] = -1;
m_State->FirstFreeTLS[0] = idx;
break;
}
}
if (m_State->FirstFreeTLS[0] < 0)
{
int capacity = m_State->ItemCapacity;
int newCapacity = capacity == 0 ? 1 : capacity * 2;
Reallocate(newCapacity);
}
}
idx = m_State->FirstFreeTLS[0];
if (idx >= 0)
{
m_State->FirstFreeTLS[0] = ((int*)m_State->Next)[idx];
}
else
{
idx = m_State->AllocatedIndexLength++;
}
// Write the new value to the entry
UnsafeUtility.WriteArrayElement(m_State->Items, idx, item);
int bucket = item.GetHashCode() & m_State->BucketCapacityMask;
// Add the index to the hash-set
int* buckets = (int*)m_State->Buckets;
nextPtrs = (int*)m_State->Next;
nextPtrs[idx] = buckets[bucket];
buckets[bucket] = idx;
return true;
}
/// <summary>
/// Remove all items from the set.
///
/// This operation requires write access.
/// </summary>
public void Clear()
{
RequireWriteAccess();
int* buckets = (int*)m_State->Buckets;
for (int i = 0; i <= m_State->BucketCapacityMask; ++i)
{
buckets[i] = -1;
}
int* nextPtrs = (int*)m_State->Next;
for (int i = 0; i < m_State->ItemCapacity; ++i)
{
nextPtrs[i] = -1;
}
for (int tls = 0; tls < JobsUtility.MaxJobThreadCount; ++tls)
{
m_State->FirstFreeTLS[tls * NativeHashSetState.IntsPerCacheLine] = -1;
}
m_State->AllocatedIndexLength = 0;
}
/// <summary>
/// Remove an item from the set.
///
/// This operation requires write access.
/// </summary>
///
/// <param name="item">
/// Item to remove
/// </param>
///
/// <returns>
/// If the item was removed. This is false only if the item wasn't
/// contained in the set.
/// </returns>
public bool Remove(T item)
{
RequireWriteAccess();
// First find the slot based on the hash
int* buckets = (int*)m_State->Buckets;
int* nextPtrs = (int*)m_State->Next;
int bucket = item.GetHashCode() & m_State->BucketCapacityMask;
int prevEntry = -1;
int entryIdx = buckets[bucket];
while (entryIdx >= 0 && entryIdx < m_State->ItemCapacity)
{
if (UnsafeUtility.ReadArrayElement<T>(m_State->Items, entryIdx).Equals(item))
{
// Found matching element, remove it
if (prevEntry < 0)
{
buckets[bucket] = nextPtrs[entryIdx];
}
else
{
nextPtrs[prevEntry] = nextPtrs[entryIdx];
}
// And free the index
nextPtrs[entryIdx] = m_State->FirstFreeTLS[0];
m_State->FirstFreeTLS[0] = entryIdx;
return true;
}
prevEntry = entryIdx;
entryIdx = nextPtrs[entryIdx];
}
return false;
}
/// <summary>
/// Check if the set contains a given item
///
/// This operation requires read access.
/// </summary>
///
/// <param name="item">
/// Item to check
/// </param>
///
/// <returns>
/// If the set contains the given item
/// </returns>
public bool Contains(T item)
{
RequireReadAccess();
NativeMultiHashSetIterator tempIt;
return TryGetFirstValueAtomic(m_State, item, out tempIt);
}
/// <summary>
/// Check if the underlying unmanaged memory has been created and not
/// freed via a call to <see cref="Dispose()"/>.
///
/// This operation has no access requirements.
///
/// This operation is O(1).
/// </summary>
///
/// <value>
/// Initially true when a non-default constructor is called but
/// initially false when the default constructor is used. After
/// <see cref="Dispose()"/> is called, this becomes false. Note that
/// calling <see cref="Dispose()"/> on one copy of a set doesn't result
/// in this becoming false for all copies if it was true before. This
/// property should <i>not</i> be used to check whether the set is
/// usable, only to check whether it was <i>ever</i> usable.
/// </value>
public bool IsCreated
{
get
{
return m_State != null;
}
}
/// <summary>
/// Release the set's unmanaged memory. Do not use it after this. Do
/// not call <see cref="Dispose()"/> on copies of the set either.
///
/// This operation requires write access.
///
/// This complexity of this operation is O(1) plus the allocator's
/// deallocation complexity.
/// </summary>
public void Dispose()
{
RequireWriteAccess();
// Make sure we're not double-disposing
#if ENABLE_UNITY_COLLECTIONS_CHECKS
#if UNITY_2018_3_OR_NEWER
DisposeSentinel.Dispose(ref m_Safety, ref m_DisposeSentinel);
#else
DisposeSentinel.Dispose(m_Safety, ref m_DisposeSentinel);
#endif
#endif
Deallocate();
}
/// <summary>
/// Schedule a job to release the set's unmanaged memory after the given
/// dependency jobs. Do not use it after this job executes. Do
/// not call <see cref="Dispose()"/> on copies of the set either.
///
/// This operation requires write access.
///
/// This complexity of this operation is O(1) plus the allocator's
/// deallocation complexity.
/// </summary>
public JobHandle Dispose(JobHandle inputDeps)
{
RequireWriteAccess();
#if ENABLE_UNITY_COLLECTIONS_CHECKS
// Clear the dispose sentinel, but don't Dispose it
DisposeSentinel.Clear(ref m_DisposeSentinel);
#endif
// Schedule the job
DisposeJob disposeJob = new DisposeJob { Set = this };
JobHandle jobHandle = disposeJob.Schedule(inputDeps);
// Release the atomic safety handle now that the job is scheduled
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.Release(m_Safety);
#endif
m_State = null;
return jobHandle;
}
/// <summary>
/// A job to call <see cref="NativeHashSet{T}.Deallocate"/>
/// </summary>
private struct DisposeJob : IJob
{
internal NativeHashSet<T> Set;
public void Execute()
{
Set.Deallocate();
}
}
/// <summary>
/// Add all of the items in the set to an array
/// </summary>
///
/// <param name="array">
/// Array to add to. If <see cref="NativeArray{T}.IsCreated"/> is false
/// or the array isn't long enough to hold all the items of the set,
/// a new <see cref="NativeArray{T}"/> will be created with length
/// equal to the number of items in the set and with the same
/// allocator as the set.
/// </param>
///
/// <param name="index">
/// Index into <paramref name="array"/> to start adding items at
/// </param>
public NativeArray<T> ToNativeArray(
NativeArray<T> array = default(NativeArray<T>),
int index = 0)
{
RequireReadAccess();
if (index < 0)
{
index = 0;
}
int length = Length;
if (!array.IsCreated || array.Length - index < length)
{
array = new NativeArray<T>(length + index, m_Allocator);
}
int* bucketArray = (int*)m_State->Buckets;
int* bucketNext = (int*)m_State->Next;
for (int i = 0; i <= m_State->BucketCapacityMask; ++i)
{
for (int b = bucketArray[i]; b != -1; b = bucketNext[b])
{
array[index] = UnsafeUtility.ReadArrayElement<T>(
m_State->Items,
b);
index++;
}
}
return array;
}
/// <summary>
/// Create a <see cref="ParallelWriter"/> that writes to this set.
///
/// This operation has no access requirements, but using the writer
/// requires write access.
/// </summary>
///
/// <returns>
/// A <see cref="ParallelWriter"/> that writes to this set
/// </returns>
public ParallelWriter AsParallelWriter()
{
ParallelWriter writer;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
writer.m_Safety = m_Safety;
#endif
writer.m_ThreadIndex = 0;
writer.m_State = m_State;
return writer;
}
/// <summary>
/// Deallocate the state's contents then the state itself.
/// </summary>
private void Deallocate()
{
UnsafeUtility.Free(m_State->Items, m_Allocator);
m_State->Items = null;
m_State->Next = null;
m_State->Buckets = null;
UnsafeUtility.Free(m_State, m_Allocator);
m_State = null;
}
/// <summary>
/// Allocate an entry from the free list. The list must not be full.
/// </summary>
///
/// <param name="state">
/// State to allocate from.
/// </param>
///
/// <param name="threadIndex">
/// Index of the allocating thread.
/// </param>
///
/// <returns>
/// The allocated free list entry index
/// </returns>
private static int AllocFreeListEntry(
NativeHashSetState* state,
int threadIndex)
{
int idx;
int* nextPtrs = (int*)state->Next;
do
{
idx = state->FirstFreeTLS[threadIndex * NativeHashSetState.IntsPerCacheLine];
if (idx < 0)
{
// Try to refill local cache
Interlocked.Exchange(
ref state->FirstFreeTLS[threadIndex * NativeHashSetState.IntsPerCacheLine],
-2);
// If it failed try to get one from the never-allocated array
if (state->AllocatedIndexLength < state->ItemCapacity)
{
idx = Interlocked.Add(ref state->AllocatedIndexLength, 16) - 16;
if (idx < state->ItemCapacity - 1)
{
int count = Math.Min(16, state->ItemCapacity - idx);
for (int i = 1; i < count; ++i)
{
nextPtrs[idx + i] = idx + i + 1;
}
nextPtrs[idx + count - 1] = -1;
nextPtrs[idx] = -1;
Interlocked.Exchange(
ref state->FirstFreeTLS[threadIndex * NativeHashSetState.IntsPerCacheLine],
idx + 1);
return idx;
}
if (idx == state->ItemCapacity - 1)
{
Interlocked.Exchange(
ref state->FirstFreeTLS[threadIndex * NativeHashSetState.IntsPerCacheLine],
-1);
return idx;
}
}
Interlocked.Exchange(
ref state->FirstFreeTLS[threadIndex * NativeHashSetState.IntsPerCacheLine],
-1);
// Failed to get any, try to get one from another free list
bool again = true;
while (again)
{
again = false;
for (int other = (threadIndex + 1) % JobsUtility.MaxJobThreadCount;
other != threadIndex;
other = (other + 1) % JobsUtility.MaxJobThreadCount)
{
do
{
idx = state->FirstFreeTLS[other * NativeHashSetState.IntsPerCacheLine];
if (idx < 0)
{
break;
}
} while (Interlocked.CompareExchange(
ref state->FirstFreeTLS[other * NativeHashSetState.IntsPerCacheLine],
nextPtrs[idx], idx) != idx);
if (idx == -2)
{
again = true;
}
else if (idx >= 0)
{
nextPtrs[idx] = -1;
return idx;
}
}
}
throw new InvalidOperationException("HashSet is full");
}
if (idx >= state->ItemCapacity)
{
throw new InvalidOperationException("HashSet is full");
}
} while (Interlocked.CompareExchange(
ref state->FirstFreeTLS[threadIndex * NativeHashSetState.IntsPerCacheLine],
nextPtrs[idx],
idx) != idx);
nextPtrs[idx] = -1;
return idx;
}
private static bool TryGetFirstValueAtomic(
NativeHashSetState* state,
T item,
out NativeMultiHashSetIterator it)
{
it.Item = item;
if (state->AllocatedIndexLength <= 0)
{
it.NextEntryIndex = -1;
return false;
}
// First find the slot based on the hash
int* buckets = (int*)state->Buckets;
int bucket = item.GetHashCode() & state->BucketCapacityMask;
it.NextEntryIndex = buckets[bucket];
return TryGetNextValueAtomic(state, ref it);
}
private static bool TryGetNextValueAtomic(
NativeHashSetState* state,
ref NativeMultiHashSetIterator it)
{
int entryIdx = it.NextEntryIndex;
it.NextEntryIndex = -1;
if (entryIdx < 0 || entryIdx >= state->ItemCapacity)
{
return false;
}
int* nextPtrs = (int*)state->Next;
while (!UnsafeUtility.ReadArrayElement<T>(
state->Items,
entryIdx).Equals(it.Item))
{
entryIdx = nextPtrs[entryIdx];
if (entryIdx < 0 || entryIdx >= state->ItemCapacity)
{
return false;
}
}
it.NextEntryIndex = nextPtrs[entryIdx];
return true;
}
/// <summary>
/// Implements parallel writer. Use AsParallelWriter to obtain it from container.
/// </summary>
[NativeContainer]
[NativeContainerIsAtomicWriteOnly]
public struct ParallelWriter
{
/// <summary>
/// State of the set or null if the list is created with the default
/// constructor or <see cref="Dispose()"/> has been called. This is
/// shared among all instances of the set.
/// </summary>
[NativeDisableUnsafePtrRestriction]
internal NativeHashSetState* m_State;
#if ENABLE_UNITY_COLLECTIONS_CHECKS
/// <summary>
/// A handle to information about what operations can be safely
/// performed on the set at any given time.
/// </summary>
internal AtomicSafetyHandle m_Safety;
#endif
/// <summary>
/// Thread index of the job using this object. This is set by Unity
/// and must have this exact name and type.
/// </summary>
[NativeSetThreadIndex]
internal int m_ThreadIndex;
/// <summary>
/// Get or set the set's capacity to hold items. The capacity can't
/// be set to be lower than it currently is.
///
/// The 'get' operation requires read access and the 'set' operation
/// requires write access.
/// </summary>
public int Capacity
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckReadAndThrow(m_Safety);
#endif
return m_State->ItemCapacity;
}
}
/// <summary>
/// Try to add an item to the set.
///
/// This operation requires write access.
/// </summary>
///
/// <param name="item">
/// Item to add
/// </param>
///
/// <returns>
/// If the item was added to the set. This is false only if the item
/// was already in the set.
/// </returns>
public bool TryAdd(T item)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
#endif
NativeMultiHashSetIterator tempIt;
if (TryGetFirstValueAtomic(m_State, item, out tempIt))
{
return false;
}
// Allocate an entry from the free list
int idx = AllocFreeListEntry(m_State, m_ThreadIndex);
// Write the new value to the entry
UnsafeUtility.WriteArrayElement(m_State->Items, idx, item);
int bucket = item.GetHashCode() & m_State->BucketCapacityMask;
// Add the index to the hash-map
int* buckets = (int*)m_State->Buckets;
if (Interlocked.CompareExchange(
ref buckets[bucket],
idx,
-1) != -1)
{
int* nextPtrs = (int*)m_State->Next;
do
{
nextPtrs[idx] = buckets[bucket];
if (TryGetFirstValueAtomic(m_State, item, out tempIt))
{
// Put back the entry in the free list if someone
// else added it while trying to add
do
{
nextPtrs[idx] = m_State->FirstFreeTLS[
m_ThreadIndex
* NativeHashSetState.IntsPerCacheLine];
} while (Interlocked.CompareExchange(
ref m_State->FirstFreeTLS[
m_ThreadIndex
* NativeHashSetState.IntsPerCacheLine],
idx,
nextPtrs[idx]) != nextPtrs[idx]);
return false;
}
} while (Interlocked.CompareExchange(
ref buckets[bucket],
idx,
nextPtrs[idx]) != nextPtrs[idx]);
}
return true;
}
/// <summary>
/// Set whether both read and write access should be allowed for the
/// set. This is used for automated testing purposes only.
/// </summary>
///
/// <param name="allowReadOrWriteAccess">
/// If both read and write access should be allowed for the set
/// </param>
[Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")]
public void TestUseOnlySetAllowReadAndWriteAccess(
bool allowReadOrWriteAccess)
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.SetAllowReadOrWriteAccess(
m_Safety,
allowReadOrWriteAccess);
#endif
}
}
/// <summary>
/// Reallocate to grow the capacity of the set
/// </summary>
///
/// <param name="newCapacity">
/// Capacity to grow to. Must be larger than the current capacity.
/// </param>
private void Reallocate(int newCapacity)
{
int newBucketCapacity = newCapacity * 2;
newBucketCapacity = NextHigherPowerOfTwo(newBucketCapacity);
// No change in capacity
if (m_State->ItemCapacity == newCapacity
&& m_State->BucketCapacityMask + 1 == newBucketCapacity)
{
return;
}
// Can't shrink
if (newCapacity < m_State->ItemCapacity)
{
throw new Exception("NativeHashSet<T> can't shrink");
}
// Allocate new data
int nextOffset;
int bucketOffset;
int totalSize = CalculateDataLayout(
newCapacity,
newBucketCapacity,
out nextOffset,
out bucketOffset);
byte* newData = (byte*)UnsafeUtility.Malloc(
totalSize,
JobsUtility.CacheLineSize,
m_Allocator);
byte* newItems = newData;
byte* newNext = newData + nextOffset;
byte* newBuckets = newData + bucketOffset;
// The items are taken from a free-list and might not be tightly
// packed, copy all of the old capacity
UnsafeUtility.MemCpy(
newItems,
m_State->Items,
m_State->ItemCapacity * UnsafeUtility.SizeOf<T>());
UnsafeUtility.MemCpy(
newNext,
m_State->Next,
m_State->ItemCapacity * UnsafeUtility.SizeOf<int>());
for (
int emptyNext = m_State->ItemCapacity;
emptyNext < newCapacity;
++emptyNext)
{
((int*)newNext)[emptyNext] = -1;
}
// Re-hash the buckets, first clear the new bucket list, then insert
// all values from the old list
for (int bucket = 0; bucket < newBucketCapacity; ++bucket)
{
((int*)newBuckets)[bucket] = -1;
}
for (int bucket = 0; bucket <= m_State->BucketCapacityMask; ++bucket)
{
int* buckets = (int*)m_State->Buckets;
int* nextPtrs = (int*)newNext;
while (buckets[bucket] >= 0)
{
int curEntry = buckets[bucket];
buckets[bucket] = nextPtrs[curEntry];
int newBucket = UnsafeUtility.ReadArrayElement<T>(
m_State->Items,
curEntry).GetHashCode() & (newBucketCapacity - 1);
nextPtrs[curEntry] = ((int*)newBuckets)[newBucket];
((int*)newBuckets)[newBucket] = curEntry;
}
}
// Free the old state contents
UnsafeUtility.Free(m_State->Items, m_Allocator);
// Set the new state contents