-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayBuilder.cs
More file actions
213 lines (185 loc) · 6.8 KB
/
ArrayBuilder.cs
File metadata and controls
213 lines (185 loc) · 6.8 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
namespace Ramstack.Parsing.Collections;
/// <summary>
/// Represents an array builder for elements of type <typeparamref name="T"/>.
/// </summary>
/// <remarks>
/// This structure is optimized for performance and relies on proper initialization.
///
/// Always initialize instances using one of the available constructors with the <c>new</c> keyword,
/// including the parameterless constructor: <c>new ArrayBuilder<T>()</c>.
///
/// Do not use <c>default(ArrayBuilder<T>)</c> or similar patterns, as this results
/// in an uninitialized instance with an invalid internal state,
/// causing a <see cref="NullReferenceException"/> when methods are called.
///
/// This design choice was made to avoid unnecessary overhead and maintain control over
/// internal state initialization in modern C# versions where parameterless constructors
/// in structs are supported.
/// </remarks>
/// <typeparam name="T">The type of elements stored in the array builder.</typeparam>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ArrayBuilderDebugView<>))]
internal struct ArrayBuilder<T>
{
private T[] _array;
private int _count;
/// <summary>
/// Gets the number of items contained in the <see cref="ArrayBuilder{T}"/>.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public readonly int Count => _count;
/// <summary>
/// Gets the underlying buffer.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public readonly T[] InnerBuffer => _array;
/// <summary>
/// Gets an item at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the item to get.</param>
public readonly ref T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
var array = _array;
if ((uint)index >= (uint)_count || (uint)index >= (uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
return ref array[index];
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ArrayBuilder{T}"/>.
/// </summary>
public ArrayBuilder()
{
_count = 0;
_array = [];
}
/// <summary>
/// Initializes a new instance of the <see cref="ArrayBuilder{T}"/> with the specified buffer capacity.
/// </summary>
/// <param name="capacity">The initial capacity of the buffer.</param>
public ArrayBuilder(int capacity)
{
_count = 0;
_array = new T[capacity];
}
/// <summary>
/// Adds an item to the underlying array, resizing it if necessary.
/// </summary>
/// <param name="item">The item to add.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(T item)
{
var array = _array;
var count = _count;
if ((uint)count < (uint)array.Length)
{
array[count] = item;
_count = count + 1;
}
else
{
AddSlow(item);
}
}
/// <summary>
/// Attempts to add an item to the underlying array, without throwing an exception if there is no room.
/// </summary>
/// <param name="item">The item to add.</param>
/// <remarks>
/// Use this method if you know there is enough space in the <see cref="ArrayBuilder{T}"/>
/// for another item, and you are writing performance-sensitive code.
/// </remarks>
/// <returns>
/// <see langword="true"/> if the item was added to the underlying array; otherwise, <see langword="false"/>.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryAdd(T item)
{
var array = _array;
var count = _count;
if ((uint)count < (uint)array.Length)
{
array[count] = item;
_count = count + 1;
return true;
}
return false;
}
/// <summary>
/// Adds the elements of the specified array to the end of the underlying array.
/// </summary>
/// <param name="items">The array of elements to add.</param>
public void AddRange(T[] items)
{
var array = _array;
var count = _count;
if (array.Length - count < items.Length)
array = Grow(checked(count + items.Length));
_count = count + items.Length;
_ = array.Length;
items.AsSpan().TryCopyTo(array.AsSpan(count));
}
/// <summary>
/// Removes all elements from the <see cref="ArrayBuilder{T}" />.
/// </summary>
public void Clear()
{
// The array is not cleared (e.g., references or reference-containing data are not set to null)
// intentionally for performance reasons. This type is designed to be used as a temporary object
// and solely for building arrays. Therefore, there is no risk of memory leaks,
// and clearing unused elements would be unnecessary.
_count = 0;
}
/// <summary>
/// Returns a <see cref="Span{T}"/> representing the written data of the current instance.
/// </summary>
/// <returns>
/// A <see cref="Span{T}"/> that represents the data within the current instance.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Span<T> AsSpan()
{
var array = _array;
var count = _count;
_ = array.Length;
return MemoryMarshal.CreateSpan(
ref MemoryMarshal.GetArrayDataReference(array),
count);
}
/// <summary>
/// Copies the elements of the <see cref="ArrayBuilder{T}"/> to a new array.
/// </summary>
/// <returns>
/// An array containing copies of the elements of the <see cref="ArrayBuilder{T}"/>.
/// </returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly T[] ToArray() =>
AsSpan().ToArray();
[MethodImpl(MethodImplOptions.NoInlining)]
private void AddSlow(T item)
{
var array = Grow(1);
var count = _count;
if ((uint)count < (uint)array.Length)
array[count] = item;
_count = count + 1;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private T[] Grow(int extra)
{
var array = _array;
var required = checked(array.Length + extra);
var capacity = array.Length != 0 ? array.Length * 2 : 4;
if ((uint)capacity > (uint)Array.MaxLength)
capacity = Array.MaxLength;
if (capacity < required)
capacity = required;
var destination = new T[capacity];
array.AsSpan().TryCopyTo(destination);
_array = destination;
return destination;
}
}