1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
6 using System.Diagnostics;
7 using System.Runtime.CompilerServices;
9 namespace System.Collections.Generic
11 internal ref partial struct ValueListBuilder<T>
13 private Span<T> _span;
14 private T[] _arrayFromPool;
17 public ValueListBuilder(Span<T> initialSpan)
20 _arrayFromPool = null;
24 public int Length => _pos;
26 public ref T this[int index]
30 Debug.Assert(index < _pos);
31 return ref _span[index];
35 [MethodImpl(MethodImplOptions.AggressiveInlining)]
36 public void Append(T item)
39 if (pos >= _span.Length)
46 public ReadOnlySpan<T> AsSpan()
48 return _span.Slice(0, _pos);
51 [MethodImpl(MethodImplOptions.AggressiveInlining)]
54 if (_arrayFromPool != null)
56 ArrayPool<T>.Shared.Return(_arrayFromPool);
57 _arrayFromPool = null;
63 T[] array = ArrayPool<T>.Shared.Rent(_span.Length * 2);
65 bool success = _span.TryCopyTo(array);
66 Debug.Assert(success);
68 T[] toReturn = _arrayFromPool;
69 _span = _arrayFromPool = array;
72 ArrayPool<T>.Shared.Return(toReturn);