Skip to content

Commit

Permalink
Fixes linkdotnet#3
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdotnet committed Mar 21, 2024
1 parent 4e51a2e commit 8a6769c
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions ValueStringBuilder/ValueStringBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@ public ref struct ValueStringBuilder
{
private int _bufferPosition;
private Span<char> _buffer;
private char[]? arrayFromPool;

public ValueStringBuilder()
{
_bufferPosition = 0;
_buffer = new char[32];
arrayFromPool = null;
}

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

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

public void Dispose()
{
if (arrayFromPool is not null)
{
ArrayPool<char>.Shared.Return(arrayFromPool);
}
}

private void Grow(int capacity = 0)
{
var currentSize = _buffer.Length;
var newSize = capacity > 0 ? capacity : currentSize * 2;
var rented = ArrayPool<char>.Shared.Rent(newSize);
var oldBuffer = arrayFromPool;
_buffer.CopyTo(rented);
_buffer = rented;
ArrayPool<char>.Shared.Return(rented);
_buffer = arrayFromPool = rented;
if (oldBuffer is not null)
{
ArrayPool<char>.Shared.Return(oldBuffer);
}
}
}

0 comments on commit 8a6769c

Please sign in to comment.