From a5e559ca04a1a0d4f50d35f9c2cb8a1d4382cdc1 Mon Sep 17 00:00:00 2001 From: Brennan Date: Fri, 6 Dec 2024 14:32:49 -0800 Subject: [PATCH] Fix MultipartReaderStream synchronous read when using buffer offset --- .../WebUtilities/src/MultipartReaderStream.cs | 2 +- .../WebUtilities/test/MultipartReaderTests.cs | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/Http/WebUtilities/src/MultipartReaderStream.cs b/src/Http/WebUtilities/src/MultipartReaderStream.cs index 208d1b38f0e0..9dd5ce6a76f8 100644 --- a/src/Http/WebUtilities/src/MultipartReaderStream.cs +++ b/src/Http/WebUtilities/src/MultipartReaderStream.cs @@ -174,7 +174,7 @@ public override int Read(byte[] buffer, int offset, int count) if (index != 0) { // Sync, it's already buffered - var slice = buffer.AsSpan(0, Math.Min(buffer.Length, index)); + var slice = buffer.AsSpan(offset, Math.Min(count, index)); var readAmount = _innerStream.Read(slice); return UpdatePosition(readAmount); diff --git a/src/Http/WebUtilities/test/MultipartReaderTests.cs b/src/Http/WebUtilities/test/MultipartReaderTests.cs index 8231ec472bc0..bc442b567dc0 100644 --- a/src/Http/WebUtilities/test/MultipartReaderTests.cs +++ b/src/Http/WebUtilities/test/MultipartReaderTests.cs @@ -389,4 +389,28 @@ public async Task MultipartReader_StripQuotesFromBoundary() var section = await reader.ReadNextSectionAsync(); Assert.NotNull(section); } + + [Fact] + public async Task SyncReadWithOffsetWorks() + { + var stream = MakeStream(OnePartBody); + var reader = new MultipartReader(Boundary, stream); + var buffer = new byte[5]; + + var section = await reader.ReadNextSectionAsync(); + Assert.NotNull(section); + Assert.Single(section.Headers); + Assert.Equal("form-data; name=\"text\"", section.Headers["Content-Disposition"][0]); + + var read = section.Body.Read(buffer, 2, buffer.Length - 2); + Assert.Equal("\0\0tex", GetString(buffer, read + 2)); + + read = section.Body.Read(buffer, 1, buffer.Length - 1); + Assert.Equal("\0t de", GetString(buffer, read + 1)); + + read = section.Body.Read(buffer, 0, buffer.Length); + Assert.Equal("fault", GetString(buffer, read)); + + Assert.Null(await reader.ReadNextSectionAsync()); + } }