Skip to content

Commit 8a6769c

Browse files
committed
Fixes #3
1 parent 4e51a2e commit 8a6769c

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

ValueStringBuilder/ValueStringBuilder.cs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,13 @@ public ref struct ValueStringBuilder
66
{
77
private int _bufferPosition;
88
private Span<char> _buffer;
9+
private char[]? arrayFromPool;
910

1011
public ValueStringBuilder()
1112
{
1213
_bufferPosition = 0;
1314
_buffer = new char[32];
15+
arrayFromPool = null;
1416
}
1517

1618
public ref char this[int index] => ref _buffer[index];
@@ -43,13 +45,25 @@ public void AppendLine(ReadOnlySpan<char> str)
4345

4446
public override string ToString() => new(_buffer[.._bufferPosition]);
4547

48+
public void Dispose()
49+
{
50+
if (arrayFromPool is not null)
51+
{
52+
ArrayPool<char>.Shared.Return(arrayFromPool);
53+
}
54+
}
55+
4656
private void Grow(int capacity = 0)
4757
{
4858
var currentSize = _buffer.Length;
4959
var newSize = capacity > 0 ? capacity : currentSize * 2;
5060
var rented = ArrayPool<char>.Shared.Rent(newSize);
61+
var oldBuffer = arrayFromPool;
5162
_buffer.CopyTo(rented);
52-
_buffer = rented;
53-
ArrayPool<char>.Shared.Return(rented);
63+
_buffer = arrayFromPool = rented;
64+
if (oldBuffer is not null)
65+
{
66+
ArrayPool<char>.Shared.Return(oldBuffer);
67+
}
5468
}
5569
}

0 commit comments

Comments
 (0)