-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathArrayBufferWriter.cs
More file actions
92 lines (72 loc) · 2.24 KB
/
Copy pathArrayBufferWriter.cs
File metadata and controls
92 lines (72 loc) · 2.24 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
namespace System.Buffers;
internal sealed class ArrayBufferWriter<T> : IBufferWriter<T>
{
private const int DefaultInitialBufferSize = 256;
private T[] _buffer;
private int _index;
public ArrayBufferWriter()
: this(DefaultInitialBufferSize)
{
}
public ArrayBufferWriter(int initialCapacity)
{
if (initialCapacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(initialCapacity));
}
_buffer = initialCapacity == 0 ? [] : new T[initialCapacity];
}
public ReadOnlyMemory<T> WrittenMemory => _buffer.AsMemory(0, _index);
public ReadOnlySpan<T> WrittenSpan => _buffer.AsSpan(0, _index);
public int WrittenCount => _index;
public int Capacity => _buffer.Length;
public int FreeCapacity => _buffer.Length - _index;
public void Clear()
{
_buffer.AsSpan(0, _index).Clear();
_index = 0;
}
public void Advance(int count)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if (count > FreeCapacity)
{
throw new InvalidOperationException("Cannot advance past the end of the buffer.");
}
_index += count;
}
public Memory<T> GetMemory(int sizeHint = 0)
{
CheckAndResizeBuffer(sizeHint);
return _buffer.AsMemory(_index);
}
public Span<T> GetSpan(int sizeHint = 0)
{
CheckAndResizeBuffer(sizeHint);
return _buffer.AsSpan(_index);
}
private void CheckAndResizeBuffer(int sizeHint)
{
if (sizeHint < 0)
{
throw new ArgumentOutOfRangeException(nameof(sizeHint));
}
if (sizeHint == 0)
{
sizeHint = 1;
}
if (sizeHint <= FreeCapacity)
{
return;
}
var growBy = Math.Max(sizeHint, _buffer.Length);
var newSize = checked(_buffer.Length + growBy);
Array.Resize(ref _buffer, newSize);
}
}