Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix PooledByteBufferWriter handling of sizeHint <= 0 #110031

Merged
merged 2 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Licensed to the .NET Foundation under one or more agreements.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
Expand All @@ -8,19 +8,20 @@ namespace System.Net.ServerSentEvents
{
internal sealed class PooledByteBufferWriter : IBufferWriter<byte>, IDisposable
{
private const int MinimumBufferSize = 256;
private ArrayBuffer _buffer = new(initialSize: 256, usePool: true);

public void Advance(int count) => _buffer.Commit(count);

public Memory<byte> GetMemory(int sizeHint = 0)
{
_buffer.EnsureAvailableSpace(sizeHint);
_buffer.EnsureAvailableSpace(Math.Max(sizeHint, MinimumBufferSize));
return _buffer.AvailableMemory;
}

public Span<byte> GetSpan(int sizeHint = 0)
{
_buffer.EnsureAvailableSpace(sizeHint);
_buffer.EnsureAvailableSpace(Math.Max(sizeHint, MinimumBufferSize));
return _buffer.AvailableSpan;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
Expand Down Expand Up @@ -117,6 +118,35 @@ async IAsyncEnumerable<SseItem<string>> GetItemsAsync([EnumeratorCancellation] C
}
}

[Fact]
public static async Task WriteLargeItems_DataWrittenSuccessfully()
{
const int NumberOfItems = 10;
byte[] expected = Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat("This is a test. This is only a test.", 100)));

MemoryStream memoryStream = new();
await SseFormatter.WriteAsync(GetBuffersAsync(), memoryStream, (item, writer) => writer.Write(item.Data));

memoryStream.Position = 0;
int count = 0;
foreach (SseItem<byte[]> item in SseParser.Create(memoryStream, (eventType, data) => data.ToArray()).Enumerate())
{
Assert.Equal(expected, item.Data);
count++;
}

Assert.Equal(NumberOfItems, count);

async IAsyncEnumerable<SseItem<byte[]>> GetBuffersAsync()
{
await Task.Yield();
for (int i = 0; i < NumberOfItems; i++)
{
yield return new SseItem<byte[]>(expected);
}
}
}

[Fact]
public static async Task WriteAsync_ParserCanRoundtripJsonEvents()
{
Expand Down
Loading