This repository was archived by the owner on Nov 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 503
Expand file tree
/
Copy pathArrayBuilder.cs
More file actions
108 lines (93 loc) · 2.72 KB
/
ArrayBuilder.cs
File metadata and controls
108 lines (93 loc) · 2.72 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Debug = System.Diagnostics.Debug;
namespace System.Collections.Generic
{
/// <summary>
/// Helper class for building lists that avoids unnecessary allocation
/// </summary>
internal struct ArrayBuilder<T>
{
private T[] _items;
private int _count;
public T[] ToArray()
{
if (_items == null)
return Array.Empty<T>();
if (_count != _items.Length)
Array.Resize(ref _items, _count);
return _items;
}
public void Add(T item)
{
if (_items == null || _count == _items.Length)
Array.Resize(ref _items, 2 * _count + 1);
_items[_count++] = item;
}
public void Append(T[] newItems)
{
Append(newItems, 0, newItems.Length);
}
public void Append(T[] newItems, int offset, int length)
{
if (length == 0)
return;
Debug.Assert(length > 0);
Debug.Assert(newItems.Length >= offset + length);
EnsureCapacity(_count + length);
Array.Copy(newItems, offset, _items, _count, length);
_count += length;
}
public void Append(ArrayBuilder<T> newItems)
{
if (newItems.Count == 0)
return;
EnsureCapacity(_count + newItems.Count);
Array.Copy(newItems._items, 0, _items, _count, newItems.Count);
_count += newItems.Count;
}
public void ZeroExtend(int numItems)
{
Debug.Assert(numItems >= 0);
EnsureCapacity(_count + numItems);
_count += numItems;
}
public void EnsureCapacity(int requestedCapacity)
{
if (requestedCapacity > ((_items != null) ? _items.Length : 0))
{
int newCount = Math.Max(2 * _count + 1, requestedCapacity);
Array.Resize(ref _items, newCount);
}
}
public int Count
{
get
{
return _count;
}
}
public T this[int index]
{
get
{
return _items[index];
}
set
{
_items[index] = value;
}
}
public bool Contains(T t)
{
for (int i = 0; i < _count; i++)
{
if (_items[i].Equals(t))
{
return true;
}
}
return false;
}
}
}