AsReadOnlySpan -> AsSpan rename to fix build breaks
[platform/upstream/coreclr.git] / src / mscorlib / shared / System / Collections / Generic / ValueListBuilder.cs
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.
4
5 using System.Buffers;
6 using System.Diagnostics;
7 using System.Runtime.CompilerServices;
8
9 namespace System.Collections.Generic
10 {
11     internal ref partial struct ValueListBuilder<T>
12     {
13         private Span<T> _span;
14         private T[] _arrayFromPool;
15         private int _pos;
16
17         public ValueListBuilder(Span<T> initialSpan)
18         {
19             _span = initialSpan;
20             _arrayFromPool = null;
21             _pos = 0;
22         }
23
24         public int Length => _pos;
25
26         public ref T this[int index]
27         {
28             get
29             {
30                 Debug.Assert(index < _pos);
31                 return ref _span[index];
32             }
33         }
34
35         [MethodImpl(MethodImplOptions.AggressiveInlining)]
36         public void Append(T item)
37         {
38             int pos = _pos;
39             if (pos >= _span.Length)
40                 Grow();
41
42             _span[pos] = item;
43             _pos = pos + 1;
44         }
45
46         public ReadOnlySpan<T> AsSpan()
47         {
48             return _span.Slice(0, _pos);
49         }
50
51         [MethodImpl(MethodImplOptions.AggressiveInlining)]
52         public void Dispose()
53         {
54             if (_arrayFromPool != null)
55             {
56                 ArrayPool<T>.Shared.Return(_arrayFromPool);
57                 _arrayFromPool = null;
58             }
59         }
60
61         private void Grow()
62         {
63             T[] array = ArrayPool<T>.Shared.Rent(_span.Length * 2);
64
65             bool success = _span.TryCopyTo(array);
66             Debug.Assert(success);
67
68             T[] toReturn = _arrayFromPool;
69             _span = _arrayFromPool = array;
70             if (toReturn != null)
71             {
72                 ArrayPool<T>.Shared.Return(toReturn);
73             }
74         }
75     }
76 }