Skip to content

Commit

Permalink
Merge pull request #799 from pziezio/fix-ibufferwriter-span-size
Browse files Browse the repository at this point in the history
Fix IBufferWriterExtensions Write for unmanaged types
  • Loading branch information
Sergio0694 authored Aug 20, 2024
2 parents b7ad78e + 8de7190 commit 5670be1
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,9 @@ public static Stream AsStream(this IBufferWriter<byte> writer)
public static unsafe void Write<T>(this IBufferWriter<byte> writer, T value)
where T : unmanaged
{
int length = sizeof(T);
Span<byte> span = writer.GetSpan(1);
Span<byte> span = writer.GetSpan(sizeof(T));

if (span.Length < length)
if (span.Length < sizeof(T))
{
ThrowArgumentExceptionForEndOfBuffer();
}
Expand All @@ -60,7 +59,7 @@ public static unsafe void Write<T>(this IBufferWriter<byte> writer, T value)

Unsafe.WriteUnaligned(ref r0, value);

writer.Advance(length);
writer.Advance(sizeof(T));
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,4 +118,22 @@ public void Test_IBufferWriterExtensions_WriteReadOverItems_ReadOnlySpan()

Assert.IsTrue(span.SequenceEqual(buffer.AsSpan()));
}

// See https://github.com/CommunityToolkit/dotnet/issues/798
[TestMethod]
public void Test_IBufferWriterExtensions_WriteExceedingFreeCapacity()
{
ArrayPoolBufferWriter<byte> writer = new();

// Leave only one byte of free capacity
int count = writer.Capacity - 1;

for (int i = 0; i < count; i++)
{
writer.Write<byte>(0);
}

// Write 4 bytes
writer.Write(1);
}
}

0 comments on commit 5670be1

Please sign in to comment.