-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
57 additions
and
53 deletions.
There are no files selected for viewing
57 changes: 57 additions & 0 deletions
57
src/LinkDotNet.StringBuilder/ValueStringBuilder.EnsureCapacity.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
using System.Buffers; | ||
using System.Runtime.CompilerServices; | ||
using System.Runtime.InteropServices; | ||
|
||
namespace LinkDotNet.StringBuilder; | ||
|
||
public ref partial struct ValueStringBuilder | ||
{ | ||
/// <summary> | ||
/// Ensures the builder's buffer size is at least <paramref name="newCapacity"/>, renting a larger buffer if not. | ||
/// </summary> | ||
/// <param name="newCapacity">New capacity for the builder.</param> | ||
/// <remarks> | ||
/// If <see cref="Length"/> is already >= <paramref name="newCapacity"/>, nothing is done. | ||
/// </remarks> | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public void EnsureCapacity(int newCapacity) | ||
{ | ||
if (Length >= newCapacity) | ||
{ | ||
return; | ||
} | ||
|
||
var newSize = FindSmallestPowerOf2Above(newCapacity); | ||
|
||
var rented = ArrayPool<char>.Shared.Rent(newSize); | ||
|
||
if (bufferPosition > 0) | ||
{ | ||
ref var sourceRef = ref MemoryMarshal.GetReference(buffer); | ||
ref var destinationRef = ref MemoryMarshal.GetReference(rented.AsSpan()); | ||
|
||
Unsafe.CopyBlock( | ||
ref Unsafe.As<char, byte>(ref destinationRef), | ||
ref Unsafe.As<char, byte>(ref sourceRef), | ||
(uint)bufferPosition * sizeof(char)); | ||
} | ||
|
||
if (arrayFromPool is not null) | ||
{ | ||
ArrayPool<char>.Shared.Return(arrayFromPool); | ||
} | ||
|
||
buffer = rented; | ||
arrayFromPool = rented; | ||
} | ||
|
||
/// <summary> | ||
/// Finds the smallest power of 2 which is greater than or equal to <paramref name="minimum"/>. | ||
/// </summary> | ||
/// <param name="minimum">The value the result should be greater than or equal to.</param> | ||
/// <returns>The smallest power of 2 >= <paramref name="minimum"/>.</returns> | ||
private static int FindSmallestPowerOf2Above(int minimum) | ||
{ | ||
return 1 << (int)Math.Ceiling(Math.Log2(minimum)); | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters