Skip to content

Commit

Permalink
Fix IBufferWriterExtensions Write for unmanaged types
Browse files Browse the repository at this point in the history
  • Loading branch information
pziezio authored and Sergio0694 committed Aug 20, 2024
1 parent b7ad78e commit 8de7190
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 8de7190

Please sign in to comment.