SpanWriter now has an argument that allows it to be resizable.
```cs
public SpanWriter(Span<byte> initialBuffer, bool resize = false)
public SpanWriter(int initialCapacity, bool resize = false)
```
If a SpanWriter is set to be resizable, or given an initial capacity instead of a buffer, it must be disposed:
```cs
public static void SomeMethod()
{
using var writer = new SpanWriter(stackalloc byte[512], true);
// stuff
// Automatic Dispose of writer
}
```
This is because the SpanWriter uses `ArrayPool<byte>.Shared` _rented buffers_ to resize. If the writer is not disposed, those buffers will never be reused resulting in a _memory leak_.
It is possible that the SpanWriter will outright ditch the initial buffer if resize is set to true and growing is needed. To check/account for that we can do the following:
```cs
public static void SomeMethod()
{
Span<byte> span = stackalloc byte[512];
using var writer = new SpanWriter(span, true);
// write some stuff that causes the span to grow
span = writer.RawBuffer;
// Do stuff with the span
}
```
Make sure you don't accidentally `Dispose()` the writer or use the `RawBuffer` outside of the `using` block. If you do, bad things will happen! (NullPointerException, or a fresh SpanWriter with no buffer, depending on the situation).
SpanWriter can also now be used with a fixed statement since it has a `PinnableReference()` function.
63 lines
1.8 KiB
C#
63 lines
1.8 KiB
C#
using System;
|
|
using System.Buffers;
|
|
using Xunit;
|
|
|
|
namespace Server.Tests
|
|
{
|
|
public class SpanWriterTests
|
|
{
|
|
[Fact]
|
|
public unsafe void TestSpanWriterResizes()
|
|
{
|
|
Span<byte> smallStack = stackalloc byte[8];
|
|
using var writer = new SpanWriter(smallStack, true);
|
|
writer.Write(0x1024L);
|
|
writer.Write(0x1024L);
|
|
|
|
var span = writer.RawBuffer;
|
|
fixed (byte* spanPtr = span)
|
|
{
|
|
fixed (byte* stackPtr = smallStack)
|
|
{
|
|
Assert.True(spanPtr != stackPtr);
|
|
}
|
|
}
|
|
|
|
Assert.True(span.Length > smallStack.Length);
|
|
}
|
|
|
|
[Fact]
|
|
public unsafe void TestSpanWriterOnlyStackAlloc()
|
|
{
|
|
Span<byte> smallStack = stackalloc byte[8];
|
|
using var writer = new SpanWriter(smallStack, true);
|
|
writer.Write(0x1024L);
|
|
|
|
var span = writer.RawBuffer;
|
|
fixed (byte* spanPtr = span)
|
|
{
|
|
fixed (byte* stackPtr = smallStack)
|
|
{
|
|
Assert.True(spanPtr == stackPtr);
|
|
}
|
|
}
|
|
|
|
Assert.True(span.Length == smallStack.Length);
|
|
AssertThat.Equal(smallStack, stackalloc byte[] { 0, 0, 0, 0, 0, 0, 0x10, 0x24 });
|
|
}
|
|
|
|
[Fact]
|
|
public void TestSpanWriterNoResizeThrows()
|
|
{
|
|
Assert.Throws<OutOfMemoryException>(
|
|
() =>
|
|
{
|
|
Span<byte> smallStack = stackalloc byte[8];
|
|
using var writer = new SpanWriter(smallStack);
|
|
writer.Write(0x1024L);
|
|
writer.Write(0x1024L);
|
|
}
|
|
);
|
|
}
|
|
}
|
|
}
|