-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayView`1.cs
More file actions
460 lines (400 loc) · 16.2 KB
/
ArrayView`1.cs
File metadata and controls
460 lines (400 loc) · 16.2 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
namespace Ramstack.Collections;
/// <summary>
/// Represents a read-only view of an array, providing safe and efficient access to a subset of its elements.
/// </summary>
/// <typeparam name="T">The type of the elements in the array view.</typeparam>
[DebuggerDisplay("{ToStringDebugger(),nq}")]
[DebuggerTypeProxy(typeof(ArrayViewDebugView<>))]
[CollectionBuilder(typeof(ArrayView), nameof(ArrayView.Create))]
public readonly struct ArrayView<T> : IReadOnlyList<T>
{
private readonly T[]? _array;
private readonly int _index;
private readonly int _count;
/// <summary>
/// Gets the empty array view.
/// </summary>
public static ArrayView<T> Empty => default;
/// <summary>
/// Gets the number of elements in the current <see cref="ArrayView{T}"/> object.
/// </summary>
public int Length => _count;
/// <summary>
/// Gets a value indicating whether the <see cref="ArrayView{T}"/> was declared but not initialized.
/// </summary>
public bool IsDefault => _array is null;
/// <inheritdoc cref="IReadOnlyList{T}.this"/>
public ref readonly T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)index >= (uint)_count)
ThrowHelper.ThrowArgumentOutOfRangeException();
return ref _array!.GetRawArrayData(_index + index);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ArrayView{T}"/> structure that creates a view
/// for the all elements in the specified array.
/// </summary>
/// <param name="array">The array to wrap.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArrayView(T[] array)
{
_index = 0;
_count = array.Length;
_array = array;
}
/// <summary>
/// Initializes a new instance of the <see cref="ArrayView{T}"/> structure that creates
/// a view for the specified range of the elements in the specified array.
/// </summary>
/// <param name="array">The array to wrap.</param>
/// <param name="index">The zero-based starting position of the view in the array.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArrayView(T[] array, int index)
{
if ((uint)index > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
_index = index;
_count = array.Length - index;
_array = array;
}
/// <summary>
/// Initializes a new instance of the <see cref="ArrayView{T}"/> structure that creates
/// a view for the specified range of the elements in the specified array.
/// </summary>
/// <param name="array">The array to wrap.</param>
/// <param name="index">The zero-based starting position of the view in the array.</param>
/// <param name="length">The number of characters to include in the view.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArrayView(T[] array, int index, int length)
{
if (IntPtr.Size == 8)
{
if ((ulong)(uint)index + (uint)length > (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
}
else
{
if ((uint)index > (uint)array.Length || (uint)length > (uint)(array.Length - index))
ThrowHelper.ThrowArgumentOutOfRangeException();
}
_index = index;
_count = length;
_array = array;
}
/// <summary>
/// Initializes a new instance of the <see cref="ArrayView{T}"/> structure that creates
/// a view for the specified range of the elements in the specified array.
/// </summary>
/// <remarks>
/// This constructor is intentionally minimal and skips all argument validations,
/// as the caller is responsible for ensuring correctness (e.g.,
/// <paramref name="array"/> is non-null, <paramref name="index"/> and
/// <paramref name="length"/> are within bounds).
/// </remarks>
/// <param name="array">The array to wrap.</param>
/// <param name="index">The zero-based starting position of the view in the array.</param>
/// <param name="length">The number of characters to include in the view.</param>
/// <param name="unused">Unused parameter used only to differentiate between overloads.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ArrayView(T[] array, int index, int length, int unused)
{
_index = index;
_count = length;
_array = array;
_ = unused;
}
/// <inheritdoc cref="IEnumerable{T}.GetEnumerator"/>
public Enumerator GetEnumerator() =>
new(this);
/// <summary>
/// Forms a slice out of the current array view starting at the specified index.
/// </summary>
/// <param name="index">The index at which to begin the slice.</param>
/// <returns>
/// An array view that consists of all elements of the current array view
/// from <paramref name="index"/> to the end of the array view.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArrayView<T> Slice(int index)
{
if ((uint)index > (uint)_count)
ThrowHelper.ThrowArgumentOutOfRangeException();
return new ArrayView<T>(_array!, _index + index, _count - index, unused: 0);
}
/// <summary>
/// Forms a slice of the specified length out of the current array view starting at the specified index.
/// </summary>
/// <param name="index">The index at which to begin the slice.</param>
/// <param name="count">The length of the slice.</param>
/// <returns>
/// An array view of <paramref name="count"/> elements starting at <paramref name="index"/>.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArrayView<T> Slice(int index, int count)
{
if (IntPtr.Size == 8)
{
if ((ulong)(uint)index + (uint)count > (uint)_count)
ThrowHelper.ThrowArgumentOutOfRangeException();
}
else
{
if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index))
ThrowHelper.ThrowArgumentOutOfRangeException();
}
return new ArrayView<T>(_array!, _index + index, count, unused: 0);
}
/// <summary>
/// Copies the contents of this array view into a new array.
/// </summary>
/// <returns>
/// An array containing the data in the current array view.
/// </returns>
public T[] ToArray() =>
((ReadOnlySpan<T>)this).ToArray();
/// <summary>
/// Returns a read-only span over the current array view.
/// </summary>
/// <returns>
/// The read-only span representation of the array view.
/// </returns>
public ReadOnlySpan<T> AsSpan() =>
this;
/// <summary>
/// Returns a read-only a memory region over the current array view.
/// </summary>
/// <returns>
/// The memory representation of the read-only array.
/// </returns>
public ReadOnlyMemory<T> AsMemory() =>
this;
/// <summary>
/// Returns a reference to the element of the <see cref="ArrayView{T}"/> at index zero.
/// </summary>
/// <returns>
/// A reference to the element of the <see cref="ArrayView{T}"/> at index zero.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref readonly T GetPinnableReference()
{
//
// Normalize the returned reference.
// We must not return a reference to an element outside the bounds of our view
// when the view is empty (_count = 0), even if it points to a valid element
// in the underlying array. In this case, we return a null reference.
//
// Examples:
//
// Full array (_array):
// [0][1][2][3][4][5][6][7][8][9]
// |--------------------------|
//
// Case 1: Non-empty view (_index = 3, _count = 4)
// [3][4][5][6]
// ^ ^
// |--------| <- valid range for this view
//
// Case 2: Empty view (_index = 3, _count = 0)
// [3][4][5][6]
// ^
// | <- no valid reference for this view
//
ref var p = ref Unsafe.NullRef<T>();
if (_count != 0)
p = ref _array!.GetRawArrayData(_index)!;
return ref p!;
}
/// <summary>
/// Copies the contents of this <see cref="ArrayView{T}"/> into a destination <see cref="Span{T}"/>.
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public void CopyTo(Span<T> destination) =>
AsSpan().CopyTo(destination);
/// <summary>
/// Attempts to copy the contents of this <see cref="ArrayView{T}"/>
/// into a destination <see cref="Span{T}"/> and returns a value to indicate
/// whether the operation succeeded.
/// </summary>
/// <param name="destination">The span to copy items into.</param>
/// <returns>
/// <see langword="true"/> if the copy operation succeeded; otherwise, <see langword="false"/>.
/// </returns>
public bool TryCopyTo(Span<T> destination) =>
AsSpan().TryCopyTo(destination);
/// <summary>
/// Defines an implicit conversion of an array of type <typeparamref name="T"/> to <see cref="ArrayView{T}"/>.
/// </summary>
/// <param name="array">The array to convert.</param>
/// <returns>
/// An array view representation of the array.
/// </returns>
public static implicit operator ArrayView<T>(T[]? array) =>
new(array ?? []);
/// <summary>
/// Defines an implicit conversion of a read-only array of type <typeparamref name="T"/> to an array view.
/// </summary>
/// <param name="array">The array to convert.</param>
/// <returns>
/// An array view representation of the read-only array.
/// </returns>
public static implicit operator ArrayView<T>(ReadOnlyArray<T> array) =>
array.AsView();
/// <summary>
/// Defines an implicit conversion of a read-only array of type <typeparamref name="T"/> to an array view.
/// </summary>
/// <param name="array">The array to convert.</param>
/// <returns>
/// An array view representation of the read-only array.
/// </returns>
public static implicit operator ArrayView<T>(ImmutableArray<T> array)
{
#if NET8_0_OR_GREATER
return ImmutableCollectionsMarshal.AsArray(array);
#else
return Unsafe.As<ImmutableArray<T>, ReadOnlyArray<T>>(ref array).AsView();
#endif
}
/// <summary>
/// Defines an implicit conversion of an array view to the <see cref="ReadOnlyMemory{T}"/>.
/// </summary>
/// <param name="view">The array view to convert.</param>
/// <returns>
/// A <see cref="ReadOnlyMemory{T}"/> representation of the array view.
/// </returns>
public static implicit operator ReadOnlyMemory<T>(ArrayView<T> view) =>
new(view._array ?? [], view._index, view._count);
/// <summary>
/// Defines an implicit conversion of an array view to the <see cref="ReadOnlySpan{T}"/>.
/// </summary>
/// <param name="view">The array view to convert.</param>
/// <returns>
/// A <see cref="ReadOnlySpan{T}"/> representation of the array view.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator ReadOnlySpan<T>(ArrayView<T> view)
{
var array = view._array ?? [];
return MemoryMarshal.CreateReadOnlySpan(
ref array.GetRawArrayData(view._index),
length: view._count);
}
/// <summary>
/// Defines an implicit conversion of an array segment to the <see cref="ArrayView{T}"/>.
/// </summary>
/// <param name="segment">The array segment to convert.</param>
/// <returns>
/// A <see cref="ArrayView{T}"/> representation of the array segment.
/// </returns>
public static implicit operator ArrayView<T>(ArraySegment<T> segment) =>
new(segment.Array!, segment.Offset, segment.Count, unused: 0);
/// <summary>
/// Returns a string representation of the current instance's state,
/// intended for debugging purposes.
/// </summary>
/// <returns>
/// A string containing information about the current instance.
/// </returns>
private string ToStringDebugger() =>
_array is null ? "Uninitialized" : $"Length = {_count}";
#region IEnumerable<T> implementation
IEnumerator<T> IEnumerable<T>.GetEnumerator() =>
new ArrayViewEnumerator(this);
IEnumerator IEnumerable.GetEnumerator() =>
new ArrayViewEnumerator(this);
#endregion
#region IReadOnlyCollection<T> implementation
int IReadOnlyCollection<T>.Count => _count;
#endregion
#region IReadOnlyList<T> implementation
T IReadOnlyList<T>.this[int index] => this[index];
#endregion
#region Inner type: Enumerator
/// <summary>
/// Provides the ability to iterate through the elements of the <see cref="ArrayView{T}"/>.
/// </summary>
public struct Enumerator
{
private readonly T[]? _array;
private int _index;
private readonly int _final;
/// <inheritdoc cref="IEnumerator{T}.Current" />
public readonly ref readonly T Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if ((uint)_index >= (uint)_final)
ThrowHelper.ThrowArgumentOutOfRangeException();
return ref _array!.GetRawArrayData(_index);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Enumerator"/> structure.
/// </summary>
/// <param name="view">The <see cref="ArrayView{T}"/> to iterate through its elements.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Enumerator(ArrayView<T> view)
{
_index = view._index - 1;
_final = view._index + view._count;
_array = view._array;
}
/// <inheritdoc cref="IEnumerator.MoveNext" />
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
++_index;
return (uint)_final > (uint)_index;
}
}
#endregion
#region Inner type: ArrayViewEnumerator
/// <summary>
/// Provides the ability to iterate through the elements of the <see cref="ArrayView{T}"/>.
/// </summary>
private sealed class ArrayViewEnumerator : IEnumerator<T>
{
private readonly T[]? _array;
private int _index;
private readonly int _final;
/// <inheritdoc cref="IEnumerator{T}.Current" />
public T Current
{
get
{
if ((uint)_index >= (uint)_final)
ThrowHelper.ThrowArgumentOutOfRangeException();
return _array!.GetRawArrayData(_index);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ArrayViewEnumerator"/> class.
/// </summary>
/// <param name="view">The <see cref="ArrayView{T}"/> to iterate through its elements.</param>
public ArrayViewEnumerator(ArrayView<T> view)
{
_index = view._index - 1;
_final = view._index + view._count;
_array = view._array;
}
/// <inheritdoc />
public bool MoveNext()
{
++_index;
return (uint)_index < (uint)_final;
}
/// <inheritdoc />
public void Dispose()
{ }
/// <inheritdoc />
object? IEnumerator.Current => Current;
/// <inheritdoc />
void IEnumerator.Reset() =>
ThrowHelper.ThrowNotSupportedException();
}
#endregion
}