-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContiguousSet.cs
More file actions
569 lines (509 loc) · 18.1 KB
/
Copy pathContiguousSet.cs
File metadata and controls
569 lines (509 loc) · 18.1 KB
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
// Copyright (c) 2023-2026 ktsu-dev contributors
namespace ktsu.Containers;
using System.Collections;
using System.Diagnostics.CodeAnalysis;
#if NET5_0_OR_GREATER
using System.Runtime.CompilerServices;
#endif
/// <summary>
/// Represents a generic set that maintains unique elements in contiguous memory for optimal cache performance.
/// </summary>
/// <remarks>
/// A contiguous memory set maintains all unique elements in a single contiguous block of memory,
/// optimizing cache locality and memory access patterns for better performance while ensuring
/// element uniqueness.
///
/// This implementation uses a managed array for contiguous storage and a hash set for fast
/// uniqueness checks, ensuring that all elements are stored contiguously in memory while
/// providing efficient set operations.
///
/// This implementation supports:
/// <list type="bullet">
/// <item>Adding unique elements while maintaining contiguous memory layout</item>
/// <item>Removing elements by value</item>
/// <item>Fast uniqueness checks with O(1) complexity</item>
/// <item>Set operations like union, intersection, and difference</item>
/// <item>Enumeration with cache-friendly sequential access</item>
/// <item>Guaranteed contiguous memory allocation</item>
/// </list>
///
/// Performance characteristics:
/// <list type="bullet">
/// <item>Add: O(1) average for uniqueness check, O(1) amortized for insertion</item>
/// <item>Contains: O(1) average time complexity</item>
/// <item>Remove: O(n) due to element shifting to maintain contiguity</item>
/// <item>Enumeration: Optimal cache performance due to contiguous layout</item>
/// </list>
/// </remarks>
/// <typeparam name="T">The type of elements stored in the set.</typeparam>
[SuppressMessage(
"Naming",
"CA1710:Identifiers should have correct suffix",
Justification = "ContiguousSet is a known collection name"
)]
public class ContiguousSet<T> : ISet<T>
#if NET5_0_OR_GREATER
, IReadOnlySet<T>
#else
, IReadOnlyCollection<T>
#endif
{
/// <summary>
/// The backing array that stores elements in contiguous memory.
/// </summary>
private T[] items;
/// <summary>
/// The internal hash set used for fast uniqueness checks.
/// </summary>
private readonly HashSet<T> uniquenessSet;
/// <summary>
/// The default initial capacity for the set.
/// </summary>
private const int DefaultCapacity = 4;
/// <summary>
/// Gets the number of elements in the set.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Gets the current capacity of the set.
/// </summary>
public int Capacity => items.Length;
/// <summary>
/// Gets a value indicating whether the set is read-only.
/// </summary>
public bool IsReadOnly => false;
/// <summary>
/// Initializes a new instance of the <see cref="ContiguousSet{T}"/> class.
/// </summary>
public ContiguousSet()
{
items = new T[DefaultCapacity];
uniquenessSet = [];
Count = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="ContiguousSet{T}"/> class with the specified equality comparer.
/// </summary>
/// <param name="comparer">The equality comparer to use for determining element equality.</param>
/// <exception cref="ArgumentNullException">Thrown when comparer is null.</exception>
public ContiguousSet(IEqualityComparer<T> comparer)
{
Ensure.NotNull(comparer);
items = new T[DefaultCapacity];
uniquenessSet = new HashSet<T>(comparer);
Count = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="ContiguousSet{T}"/> class with initial capacity.
/// </summary>
/// <param name="capacity">The initial capacity of the set.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when capacity is negative.</exception>
public ContiguousSet(int capacity)
{
ArgumentOutOfRangeException.ThrowIfNegative(capacity);
items = capacity == 0 ? [] : new T[capacity];
#if NETSTANDARD2_0
uniquenessSet = [];
#else
uniquenessSet = new HashSet<T>(capacity);
#endif
Count = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="ContiguousSet{T}"/> class with initial capacity and equality comparer.
/// </summary>
/// <param name="capacity">The initial capacity of the set.</param>
/// <param name="comparer">The equality comparer to use for determining element equality.</param>
/// <exception cref="ArgumentNullException">Thrown when comparer is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when capacity is negative.</exception>
public ContiguousSet(int capacity, IEqualityComparer<T> comparer)
{
ArgumentOutOfRangeException.ThrowIfNegative(capacity);
Ensure.NotNull(comparer);
items = capacity == 0 ? [] : new T[capacity];
#if NETSTANDARD2_0
uniquenessSet = new HashSet<T>(comparer);
#else
uniquenessSet = new HashSet<T>(capacity, comparer);
#endif
Count = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="ContiguousSet{T}"/> class with elements from an existing collection.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new contiguous set.</param>
/// <exception cref="ArgumentNullException">Thrown when collection is null.</exception>
public ContiguousSet(IEnumerable<T> collection)
{
Ensure.NotNull(collection);
items = new T[DefaultCapacity];
uniquenessSet = [];
Count = 0;
foreach (T item in collection)
{
Add(item);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ContiguousSet{T}"/> class with elements from an existing collection and an equality comparer.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new contiguous set.</param>
/// <param name="comparer">The equality comparer to use for determining element equality.</param>
/// <exception cref="ArgumentNullException">Thrown when collection or comparer is null.</exception>
public ContiguousSet(IEnumerable<T> collection, IEqualityComparer<T> comparer)
{
Ensure.NotNull(collection);
Ensure.NotNull(comparer);
items = new T[DefaultCapacity];
uniquenessSet = new HashSet<T>(comparer);
Count = 0;
foreach (T item in collection)
{
Add(item);
}
}
/// <summary>
/// Adds an element to the set if it doesn't already exist, maintaining contiguous memory layout.
/// </summary>
/// <param name="item">The element to add.</param>
/// <returns>true if the element was added; false if it already exists.</returns>
/// <remarks>
/// This operation has O(1) average time complexity for uniqueness check and O(1) amortized for insertion.
/// The element is added at the end of the contiguous array to maintain cache-friendly layout.
/// </remarks>
public bool Add(T item)
{
if (!uniquenessSet.Add(item))
{
// Element already exists
return false;
}
if (Count == items.Length)
{
Grow();
}
items[Count] = item;
Count++;
return true;
}
/// <summary>
/// Adds an element to the set. This is the explicit interface implementation for ICollection{T}.
/// </summary>
/// <param name="item">The element to add.</param>
void ICollection<T>.Add(T item) => Add(item);
/// <summary>
/// Removes all elements from the set.
/// </summary>
public void Clear()
{
#if NET5_0_OR_GREATER
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
#else
if (!typeof(T).IsValueType)
#endif
{
// Clear references to help GC
Array.Clear(items, 0, Count);
}
Count = 0;
uniquenessSet.Clear();
}
/// <summary>
/// Determines whether the set contains the specified element.
/// </summary>
/// <param name="item">The element to locate.</param>
/// <returns>true if the element is found; otherwise, false.</returns>
/// <remarks>
/// This operation has O(1) average time complexity.
/// </remarks>
public bool Contains(T item) => uniquenessSet.Contains(item);
/// <summary>
/// Copies the elements of the set to an array, starting at the specified array index.
/// </summary>
/// <param name="array">The destination array.</param>
/// <param name="arrayIndex">The zero-based index in the destination array at which copying begins.</param>
/// <exception cref="ArgumentNullException">Thrown when array is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when arrayIndex is negative.</exception>
/// <exception cref="ArgumentException">Thrown when the destination array is too small.</exception>
public void CopyTo(T[] array, int arrayIndex)
{
Ensure.NotNull(array);
ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex);
ArgumentOutOfRangeException.ThrowIfGreaterThan(arrayIndex, array.Length);
ArgumentOutOfRangeException.ThrowIfGreaterThan(Count, array.Length - arrayIndex);
Array.Copy(items, 0, array, arrayIndex, Count);
}
/// <summary>
/// Removes the specified element from the set.
/// </summary>
/// <param name="item">The element to remove.</param>
/// <returns>true if the element was found and removed; otherwise, false.</returns>
/// <remarks>
/// This operation has O(n) time complexity for finding the element in the array
/// and O(1) average time complexity for removing from the hash set.
/// Elements are shifted to maintain contiguous memory layout.
/// </remarks>
public bool Remove(T item)
{
if (!uniquenessSet.Remove(item))
{
// Element doesn't exist
return false;
}
// Find and remove from the array
int index = Array.IndexOf(items, item, 0, Count);
if (index >= 0)
{
Count--;
if (index < Count)
{
Array.Copy(items, index + 1, items, index, Count - index);
}
#if NET5_0_OR_GREATER
if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
#else
if (!typeof(T).IsValueType)
#endif
{
items[Count] = default!;
}
}
return true;
}
/// <summary>
/// Returns an enumerator that iterates through the set.
/// </summary>
/// <returns>An enumerator for the set.</returns>
/// <remarks>
/// Enumeration benefits from the contiguous memory layout with optimal cache performance.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
for (int i = 0; i < Count; i++)
{
yield return items[i];
}
}
/// <summary>
/// Returns an enumerator that iterates through the set.
/// </summary>
/// <returns>An enumerator for the set.</returns>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
/// <summary>
/// Modifies the current set to contain all elements that are present in itself, the specified collection, or both.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <exception cref="ArgumentNullException">Thrown when other is null.</exception>
public void UnionWith(IEnumerable<T> other)
{
Ensure.NotNull(other);
foreach (T item in other)
{
Add(item);
}
}
/// <summary>
/// Modifies the current set to contain only elements that are present in that set and in the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <exception cref="ArgumentNullException">Thrown when other is null.</exception>
public void IntersectWith(IEnumerable<T> other)
{
Ensure.NotNull(other);
HashSet<T> otherSet = new(other, uniquenessSet.Comparer);
// Remove items that are not in the other collection
for (int i = Count - 1; i >= 0; i--)
{
T item = items[i];
if (!otherSet.Contains(item))
{
Remove(item);
}
}
}
/// <summary>
/// Removes all elements in the specified collection from the current set.
/// </summary>
/// <param name="other">The collection of items to remove from the set.</param>
/// <exception cref="ArgumentNullException">Thrown when other is null.</exception>
public void ExceptWith(IEnumerable<T> other)
{
Ensure.NotNull(other);
foreach (T item in other)
{
Remove(item);
}
}
/// <summary>
/// Modifies the current set to contain only elements that are present either in that set or in the specified collection, but not both.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <exception cref="ArgumentNullException">Thrown when other is null.</exception>
public void SymmetricExceptWith(IEnumerable<T> other)
{
Ensure.NotNull(other);
HashSet<T> otherSet = new(other, uniquenessSet.Comparer);
// Remove items that are in both sets
for (int i = Count - 1; i >= 0; i--)
{
T item = items[i];
if (otherSet.Remove(item))
{
// Item exists in both - remove from current set
Remove(item);
}
}
// Add remaining items from other set (items that were only in other)
foreach (T item in otherSet)
{
Add(item);
}
}
/// <summary>
/// Determines whether the current set is a subset of the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a subset of other; otherwise, false.</returns>
/// <exception cref="ArgumentNullException">Thrown when other is null.</exception>
public bool IsSubsetOf(IEnumerable<T> other)
{
Ensure.NotNull(other);
return uniquenessSet.IsSubsetOf(other);
}
/// <summary>
/// Determines whether the current set is a superset of the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a superset of other; otherwise, false.</returns>
/// <exception cref="ArgumentNullException">Thrown when other is null.</exception>
public bool IsSupersetOf(IEnumerable<T> other)
{
Ensure.NotNull(other);
return uniquenessSet.IsSupersetOf(other);
}
/// <summary>
/// Determines whether the current set is a proper subset of the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a proper subset of other; otherwise, false.</returns>
/// <exception cref="ArgumentNullException">Thrown when other is null.</exception>
public bool IsProperSubsetOf(IEnumerable<T> other)
{
Ensure.NotNull(other);
return uniquenessSet.IsProperSubsetOf(other);
}
/// <summary>
/// Determines whether the current set is a proper superset of the specified collection.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is a proper superset of other; otherwise, false.</returns>
/// <exception cref="ArgumentNullException">Thrown when other is null.</exception>
public bool IsProperSupersetOf(IEnumerable<T> other)
{
Ensure.NotNull(other);
return uniquenessSet.IsProperSupersetOf(other);
}
/// <summary>
/// Determines whether the current set and a specified collection share common elements.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set and other share at least one common element; otherwise, false.</returns>
/// <exception cref="ArgumentNullException">Thrown when other is null.</exception>
public bool Overlaps(IEnumerable<T> other)
{
Ensure.NotNull(other);
return uniquenessSet.Overlaps(other);
}
/// <summary>
/// Determines whether the current set and the specified collection contain the same elements.
/// </summary>
/// <param name="other">The collection to compare to the current set.</param>
/// <returns>true if the current set is equal to other; otherwise, false.</returns>
/// <exception cref="ArgumentNullException">Thrown when other is null.</exception>
public bool SetEquals(IEnumerable<T> other)
{
Ensure.NotNull(other);
return uniquenessSet.SetEquals(other);
}
/// <summary>
/// Ensures that the set has enough capacity for the specified number of elements.
/// </summary>
/// <param name="capacity">The minimum capacity required.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when capacity is negative.</exception>
/// <remarks>
/// This method can be used to pre-allocate memory and avoid multiple reallocations
/// when the final size is known in advance. This maintains the contiguous memory guarantee.
/// </remarks>
public void EnsureCapacity(int capacity)
{
ArgumentOutOfRangeException.ThrowIfNegative(capacity);
if (items.Length < capacity)
{
Grow(capacity);
}
}
/// <summary>
/// Sets the capacity to the actual number of elements, reducing memory usage.
/// </summary>
/// <remarks>
/// This method creates a new contiguous memory block sized exactly for the current elements,
/// potentially reducing memory usage while maintaining the contiguous memory guarantee.
/// </remarks>
public void TrimExcess()
{
if (Count < items.Length * 0.9) // Only trim if there's significant unused space
{
T[] newItems = Count == 0 ? [] : new T[Count];
Array.Copy(items, newItems, Count);
items = newItems;
}
}
/// <summary>
/// Gets a span representing the elements in the set.
/// </summary>
/// <returns>A span over the set's elements.</returns>
/// <remarks>
/// This method provides direct access to the contiguous memory, enabling high-performance
/// operations and interoperability with other APIs that work with spans.
/// </remarks>
public Span<T> AsSpan() => new(items, 0, Count);
/// <summary>
/// Gets a read-only span representing the elements in the set.
/// </summary>
/// <returns>A read-only span over the set's elements.</returns>
/// <remarks>
/// This method provides direct read-only access to the contiguous memory, enabling high-performance
/// operations while preventing modifications.
/// </remarks>
public ReadOnlySpan<T> AsReadOnlySpan() => new(items, 0, Count);
/// <summary>
/// Creates a shallow copy of the set.
/// </summary>
/// <returns>A new set containing all elements from the original set with contiguous memory layout.</returns>
public ContiguousSet<T> Clone()
{
ContiguousSet<T> clone = new(Count, uniquenessSet.Comparer);
Array.Copy(items, clone.items, Count);
clone.Count = Count;
foreach (T item in items.AsSpan(0, Count))
{
clone.uniquenessSet.Add(item);
}
return clone;
}
/// <summary>
/// Grows the set's capacity.
/// </summary>
/// <param name="minimumCapacity">The minimum required capacity.</param>
private void Grow(int minimumCapacity = 0)
{
int newCapacity = items.Length == 0 ? DefaultCapacity : items.Length * 2;
if (newCapacity < minimumCapacity)
{
newCapacity = minimumCapacity;
}
T[] newItems = new T[newCapacity];
Array.Copy(items, newItems, Count);
items = newItems;
}
}