You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@lucenenet.apache.org by pa...@apache.org on 2026/04/16 14:58:46 UTC
(lucenenet) branch master updated: Fix Stream.ReadExactly CA2022 warning; optimize for stackalloc/arraypool (#1254)
This is an automated email from the ASF dual-hosted git repository.
paulirwin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/lucenenet.git
The following commit(s) were added to refs/heads/master by this push:
new e4d5f4132 Fix Stream.ReadExactly CA2022 warning; optimize for stackalloc/arraypool (#1254)
e4d5f4132 is described below
commit e4d5f41327fe6f140b6822137893c623bf2e54d3
Author: Paul Irwin <pa...@gmail.com>
AuthorDate: Thu Apr 16 08:58:40 2026 -0600
Fix Stream.ReadExactly CA2022 warning; optimize for stackalloc/arraypool (#1254)
* Fix Stream.ReadExactly CA2022 warning; optimize for stackalloc/arraypool
* PR feedback
* Fix compilation issue with test on .NET Framework
* Apply suggestions from code review
Co-authored-by: Copilot <17...@users.noreply.github.com>
---------
Co-authored-by: Copilot <17...@users.noreply.github.com>
---
Directory.Build.targets | 12 +-
.../Support/IO/TestStreamExtensions.cs | 225 +++++++++++++++++++-
src/Lucene.Net/Support/IO/StreamExtensions.cs | 236 +++++++++++++++------
3 files changed, 404 insertions(+), 69 deletions(-)
diff --git a/Directory.Build.targets b/Directory.Build.targets
index 48ad23bc2..3404e9e7b 100644
--- a/Directory.Build.targets
+++ b/Directory.Build.targets
@@ -38,17 +38,17 @@
<PublishDir Condition="'$(AlternatePublishRootDirectory)' != ''">$(AlternatePublishRootDirectory)/$(TargetFramework)/$(MSBuildProjectName)/</PublishDir>
</PropertyGroup>
- <!-- Features in .NET 9.x+ only -->
- <PropertyGroup Condition=" $(TargetFramework.StartsWith('net9.')) Or $(TargetFramework.StartsWith('net10.')) ">
+ <!-- Features in .NET 8.x+ only -->
+ <PropertyGroup Condition=" $(TargetFramework.StartsWith('net8.')) Or $(TargetFramework.StartsWith('net9.')) Or $(TargetFramework.StartsWith('net10.')) ">
- <DefineConstants>$(DefineConstants);FEATURE_STREAM_READEXACTLY</DefineConstants>
+ <DefineConstants>$(DefineConstants);FEATURE_ASPNETCORE_TESTHOST</DefineConstants>
</PropertyGroup>
- <!-- Features in .NET 8.x+ only -->
- <PropertyGroup Condition=" $(TargetFramework.StartsWith('net8.')) Or $(TargetFramework.StartsWith('net9.')) Or $(TargetFramework.StartsWith('net10.')) ">
+ <!-- Features in .NET 7.x+ only -->
+ <PropertyGroup Condition=" $(TargetFramework.StartsWith('net7.')) Or $(TargetFramework.StartsWith('net8.')) Or $(TargetFramework.StartsWith('net9.')) Or $(TargetFramework.StartsWith('net10.')) ">
- <DefineConstants>$(DefineConstants);FEATURE_ASPNETCORE_TESTHOST</DefineConstants>
+ <DefineConstants>$(DefineConstants);FEATURE_STREAM_READEXACTLY</DefineConstants>
</PropertyGroup>
diff --git a/src/Lucene.Net.Tests/Support/IO/TestStreamExtensions.cs b/src/Lucene.Net.Tests/Support/IO/TestStreamExtensions.cs
index 9a1b16567..168460e9b 100644
--- a/src/Lucene.Net.Tests/Support/IO/TestStreamExtensions.cs
+++ b/src/Lucene.Net.Tests/Support/IO/TestStreamExtensions.cs
@@ -78,6 +78,168 @@ public void TestRead_Span()
Assert.IsTrue(Encoding.UTF8.GetString(buffer).Equals(fileString));
}
+#if !FEATURE_STREAM_READEXACTLY
+ [Test]
+ public void TestReadExactly_ZeroLength()
+ {
+ using var ms = new MemoryStream();
+ Span<byte> buffer = Array.Empty<byte>();
+ ms.ReadExactly(buffer); // should succeed
+ }
+
+ [Test]
+ public void TestReadExactly_Success_FromStart()
+ {
+ var bytes = new byte[] { 1, 2, 3, 4 };
+ using var ms = new MemoryStream(bytes);
+
+ Span<byte> buffer = stackalloc byte[2];
+ ms.ReadExactly(buffer);
+
+ Assert.AreEqual((byte)1, buffer[0]);
+ Assert.AreEqual((byte)2, buffer[1]);
+ }
+
+ [Test]
+ public void TestReadExactly_Success_FromMiddle()
+ {
+ var bytes = new byte[] { 1, 2, 3, 4 };
+ using var ms = new MemoryStream(bytes);
+ ms.Seek(2, SeekOrigin.Begin);
+
+ Span<byte> buffer = stackalloc byte[2];
+ ms.ReadExactly(buffer);
+
+ Assert.AreEqual((byte)3, buffer[0]);
+ Assert.AreEqual((byte)4, buffer[1]);
+ }
+
+ [Test]
+ public void TestReadExactly_Success_IntoMiddle()
+ {
+ var bytes = new byte[] { 1, 2, 3, 4 };
+ using var ms = new MemoryStream(bytes);
+
+ Span<byte> buffer = stackalloc byte[4];
+ ms.ReadExactly(buffer.Slice(2));
+
+ Assert.AreEqual((byte)1, buffer[2]);
+ Assert.AreEqual((byte)2, buffer[3]);
+ }
+
+ [Test]
+ public void TestReadExactly_EndOfStream()
+ {
+ var bytes = new byte[] { 1, 2, 3, 4 };
+
+ Assert.Throws<EndOfStreamException>(() =>
+ {
+ using var ms = new MemoryStream(bytes);
+
+ Span<byte> buffer = stackalloc byte[5];
+ ms.ReadExactly(buffer);
+ });
+ }
+
+ [Test]
+ public void TestReadExactly_PartialReads()
+ {
+ var bytes = new byte[] { 1, 2, 3, 4 };
+ var partialStream = new MaxBytesPerReadStream(bytes, maxBytesPerRead: 1);
+
+ Span<byte> buffer = stackalloc byte[4];
+ partialStream.ReadExactly(buffer);
+
+ Assert.AreEqual((byte)1, buffer[0]);
+ Assert.AreEqual((byte)2, buffer[1]);
+ Assert.AreEqual((byte)3, buffer[2]);
+ Assert.AreEqual((byte)4, buffer[3]);
+ }
+
+ [Test]
+ public async Task TestReadExactlyAsync_ZeroLength()
+ {
+ using var ms = new MemoryStream();
+ var buffer = Array.Empty<byte>();
+ await ms.ReadExactlyAsync(buffer, 0, 0); // should succeed
+ }
+
+ [Test]
+ public async Task TestReadExactlyAsync_Success_FromStart()
+ {
+ var bytes = new byte[] { 1, 2, 3, 4 };
+ using var ms = new MemoryStream(bytes);
+
+ var buffer = new byte[2];
+ await ms.ReadExactlyAsync(buffer, 0, 2);
+
+ Assert.AreEqual((byte)1, buffer[0]);
+ Assert.AreEqual((byte)2, buffer[1]);
+ }
+
+ [Test]
+ public async Task TestReadExactlyAsync_Success_FromMiddle()
+ {
+ var bytes = new byte[] { 1, 2, 3, 4 };
+ using var ms = new MemoryStream(bytes);
+ ms.Seek(2, SeekOrigin.Begin);
+
+ var buffer = new byte[2];
+ await ms.ReadExactlyAsync(buffer, 0, 2);
+
+ Assert.AreEqual((byte)3, buffer[0]);
+ Assert.AreEqual((byte)4, buffer[1]);
+ }
+
+ [Test]
+ public async Task TestReadExactlyAsync_Success_IntoMiddle()
+ {
+ var bytes = new byte[] { 1, 2, 3, 4 };
+ using var ms = new MemoryStream(bytes);
+
+ var buffer = new byte[4];
+ await ms.ReadExactlyAsync(buffer, 2, 2);
+
+ Assert.AreEqual((byte)1, buffer[2]);
+ Assert.AreEqual((byte)2, buffer[3]);
+ }
+
+ [Test]
+ public async Task TestReadExactlyAsync_EndOfStream()
+ {
+ var bytes = new byte[] { 1, 2, 3, 4 };
+
+ try
+ {
+ using var ms = new MemoryStream(bytes);
+
+ var buffer = new byte[5];
+ await ms.ReadExactlyAsync(buffer, 0, 5);
+
+ Assert.Fail("Should have thrown an exception");
+ }
+ catch (EndOfStreamException)
+ {
+ Assert.Pass("Expected EndOfStreamException thrown");
+ }
+ }
+
+ [Test]
+ public async Task TestReadExactlyAsync_PartialReads()
+ {
+ var bytes = new byte[] { 1, 2, 3, 4 };
+ var partialStream = new MaxBytesPerReadStream(bytes, maxBytesPerRead: 1);
+
+ var buffer = new byte[4];
+ await partialStream.ReadExactlyAsync(buffer, 0, 4);
+
+ Assert.AreEqual((byte)1, buffer[0]);
+ Assert.AreEqual((byte)2, buffer[1]);
+ Assert.AreEqual((byte)3, buffer[2]);
+ Assert.AreEqual((byte)4, buffer[3]);
+ }
+#endif
+
[Test]
public void TestWrite_Span()
{
@@ -237,7 +399,7 @@ public async Task TestReadUTFAsync()
/// Helper method to calculate expected UTF stream length for validation
/// Matches DataOutput.writeUTF() spec (Java)
/// </summary>
- private long CalculateExpectedUTFStreamLength(string value)
+ private static long CalculateExpectedUTFStreamLength(string value)
{
long utfCount = 0;
foreach (char ch in value)
@@ -260,10 +422,71 @@ private long CalculateExpectedUTFStreamLength(string value)
stream.Position = 0;
}
+ // Partial-read async tests: verify that async read methods handle
+ // streams that return fewer bytes than requested per call.
+
+ [Test]
+ public async Task TestReadInt32BigEndianAsync_PartialReads()
+ {
+ await stream.WriteInt32BigEndianAsync(768347202);
+ var partialStream = new MaxBytesPerReadStream(((MemoryStream)stream).ToArray(), maxBytesPerRead: 1);
+
+ int result = await partialStream.ReadInt32BigEndianAsync();
+ Assert.AreEqual(768347202, result, "Incorrect int read with partial reads (async)");
+ }
+
+ [Test]
+ public async Task TestReadInt64BigEndianAsync_PartialReads()
+ {
+ await stream.WriteInt64BigEndianAsync(9875645283333L);
+ var partialStream = new MaxBytesPerReadStream(((MemoryStream)stream).ToArray(), maxBytesPerRead: 1);
+
+ long result = await partialStream.ReadInt64BigEndianAsync();
+ Assert.AreEqual(9875645283333L, result, "Incorrect long read with partial reads (async)");
+ }
+
+ [Test]
+ public async Task TestReadUTFAsync_PartialReads()
+ {
+ await stream.WriteUTFAsync(unihw);
+ var partialStream = new MaxBytesPerReadStream(((MemoryStream)stream).ToArray(), maxBytesPerRead: 1);
+
+ string result = await partialStream.ReadUTFAsync();
+ Assert.AreEqual(unihw, result, "Incorrect string read with partial reads (async)");
+ }
+
public override void SetUp()
{
base.SetUp();
stream = new MemoryStream();
}
}
+
+ /// <summary>
+ /// A stream wrapper that returns at most <c>maxBytesPerRead</c> bytes per
+ /// <see cref="ReadAsync(byte[], int, int, System.Threading.CancellationToken)"/> call,
+ /// simulating partial reads (e.g. network streams).
+ /// </summary>
+ internal sealed class MaxBytesPerReadStream : MemoryStream
+ {
+ private readonly int maxBytesPerRead;
+
+ public MaxBytesPerReadStream(byte[] data, int maxBytesPerRead)
+ : base(data, writable: false)
+ {
+ this.maxBytesPerRead = maxBytesPerRead;
+ }
+
+ public override int Read(byte[] buffer, int offset, int count)
+ {
+ int clamped = Math.Min(count, maxBytesPerRead);
+ return base.Read(buffer, offset, clamped);
+ }
+
+ public override Task<int> ReadAsync(byte[] buffer, int offset, int count, System.Threading.CancellationToken cancellationToken)
+ {
+ int clamped = Math.Min(count, maxBytesPerRead);
+ return base.ReadAsync(buffer, offset, clamped, cancellationToken);
+ }
+ }
}
diff --git a/src/Lucene.Net/Support/IO/StreamExtensions.cs b/src/Lucene.Net/Support/IO/StreamExtensions.cs
index 1d814e621..6eca88971 100644
--- a/src/Lucene.Net/Support/IO/StreamExtensions.cs
+++ b/src/Lucene.Net/Support/IO/StreamExtensions.cs
@@ -1,12 +1,15 @@
-using Lucene.Net.Support.Threading;
using System;
using System.Buffers;
using System.IO;
-using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
+#if !FEATURE_RANDOMACCESS_READ
+using Lucene.Net.Support.Threading;
+using System.Runtime.CompilerServices;
+#endif
+
namespace Lucene.Net.Support.IO
{
/*
@@ -154,6 +157,84 @@ public static int Read(this Stream stream, Span<byte> buffer)
}
}
+#if !FEATURE_STREAM_READEXACTLY
+ /// <summary>
+ /// Reads bytes from the stream into <paramref name="buffer"/> until it is completely filled.
+ /// </summary>
+ /// <param name="stream">The stream to read from.</param>
+ /// <param name="buffer">The buffer to read into.</param>
+ /// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
+ /// <exception cref="EndOfStreamException">The end of the stream is reached before filling the buffer.</exception>
+ /// <remarks>
+ /// This method is a polyfill for platforms (prior to .NET 7) that do not have the ReadExactly method.
+ /// </remarks>
+ public static void ReadExactly(this Stream stream, Span<byte> buffer)
+ {
+ if (stream is null)
+ throw new ArgumentNullException(nameof(stream));
+
+ byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
+ try
+ {
+ while (buffer.Length > 0)
+ {
+ int numRead = stream.Read(sharedBuffer, 0, buffer.Length);
+
+ if (numRead == 0)
+ {
+ throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
+ }
+
+ new ReadOnlySpan<byte>(sharedBuffer, 0, numRead).CopyTo(buffer);
+ buffer = buffer.Slice(numRead);
+ }
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(sharedBuffer);
+ }
+ }
+
+ /// <summary>
+ /// Reads bytes asynchronously from the stream into <paramref name="buffer"/> until it is completely filled.
+ /// </summary>
+ /// <param name="stream">The stream to read from.</param>
+ /// <param name="buffer">The buffer to read into.</param>
+ /// <param name="offset">The byte offset in <paramref name="buffer"/> at which to begin writing data read from the stream.</param>
+ /// <param name="count">The count of bytes to read.</param>
+ /// <exception cref="ArgumentNullException"><paramref name="stream"/> is null.</exception>
+ /// <exception cref="EndOfStreamException">The end of the stream is reached before filling the buffer.</exception>
+ /// <remarks>
+ /// This method is a polyfill for platforms (prior to .NET 7) that do not have the ReadExactlyAsync method.
+ /// </remarks>
+ public static async Task ReadExactlyAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default)
+ {
+ if (stream is null)
+ throw new ArgumentNullException(nameof(stream));
+ if (buffer is null)
+ throw new ArgumentNullException(nameof(buffer));
+ if (offset < 0)
+ throw new ArgumentOutOfRangeException(nameof(offset));
+ if (count < 0)
+ throw new ArgumentOutOfRangeException(nameof(count));
+ if (buffer.Length - offset < count)
+ throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.");
+
+ while (count > 0)
+ {
+ int numRead = await stream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
+
+ if (numRead == 0)
+ {
+ throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
+ }
+
+ count -= numRead;
+ offset += numRead;
+ }
+ }
+#endif
+
/// <summary>
/// Writes a sequence of bytes to the current stream and advances the current
/// position within this stream by the number of bytes written.
@@ -186,14 +267,23 @@ public static void Write(this Stream stream, char[] chars)
if (chars is null)
throw new ArgumentNullException(nameof(chars));
- byte[] newBytes = new byte[chars.Length * 2];
- for (int index = 0; index < chars.Length; index++)
+ int byteCount = chars.Length * 2;
+ byte[] newBytes = ArrayPool<byte>.Shared.Rent(byteCount);
+ try
+ {
+ for (int index = 0; index < chars.Length; index++)
+ {
+ int newIndex = index == 0 ? index : index * 2;
+ newBytes[newIndex] = (byte)chars[index];
+ newBytes[newIndex + 1] = (byte)(chars[index] >> 8);
+ }
+
+ stream.Write(newBytes, 0, byteCount);
+ }
+ finally
{
- int newIndex = index == 0 ? index : index * 2;
- newBytes[newIndex] = (byte)chars[index];
- newBytes[newIndex + 1] = (byte)(chars[index] >> 8);
+ ArrayPool<byte>.Shared.Return(newBytes);
}
- stream.Write(newBytes, 0, newBytes.Length);
}
public static char[] ReadChars(this Stream stream, int count)
@@ -203,11 +293,11 @@ public static char[] ReadChars(this Stream stream, int count)
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
- byte[] buff = new byte[2];
+ Span<byte> buff = stackalloc byte[2];
char[] newChars = new char[count];
for (int i = 0; i < count; i++)
{
- stream.Read(buff, 0, 2);
+ stream.ReadExactly(buff);
newChars[i] = (char)((buff[0] & 0xff) | ((buff[1] & 0xff) << 8));
}
return newChars;
@@ -218,12 +308,12 @@ public static void Write(this Stream stream, int value)
if (stream is null)
throw new ArgumentNullException(nameof(stream));
- byte[] buff = new byte[4];
+ Span<byte> buff = stackalloc byte[4];
buff[0] = (byte)(value);
buff[1] = (byte)(value >> 8);
buff[2] = (byte)(value >> 16);
buff[3] = (byte)(value >> 24);
- stream.Write(buff, 0, buff.Length);
+ stream.Write(buff);
}
public static int ReadInt32(this Stream stream)
@@ -231,8 +321,8 @@ public static int ReadInt32(this Stream stream)
if (stream is null)
throw new ArgumentNullException(nameof(stream));
- byte[] buff = new byte[4];
- stream.Read(buff, 0, buff.Length);
+ Span<byte> buff = stackalloc byte[4];
+ stream.ReadExactly(buff);
return (buff[0] & 0xff) | ((buff[1] & 0xff) << 8) |
((buff[2] & 0xff) << 16) | ((buff[3] & 0xff) << 24);
}
@@ -242,7 +332,7 @@ public static void Write(this Stream stream, long value)
if (stream is null)
throw new ArgumentNullException(nameof(stream));
- byte[] buff = new byte[8];
+ Span<byte> buff = stackalloc byte[8];
buff[0] = (byte)value;
buff[1] = (byte)(value >> 8);
buff[2] = (byte)(value >> 16);
@@ -251,7 +341,7 @@ public static void Write(this Stream stream, long value)
buff[5] = (byte)(value >> 40);
buff[6] = (byte)(value >> 48);
buff[7] = (byte)(value >> 56);
- stream.Write(buff, 0, buff.Length);
+ stream.Write(buff);
}
public static long ReadInt64(this Stream stream)
@@ -259,8 +349,8 @@ public static long ReadInt64(this Stream stream)
if (stream is null)
throw new ArgumentNullException(nameof(stream));
- byte[] buff = new byte[8];
- stream.Read(buff, 0, buff.Length);
+ Span<byte> buff = stackalloc byte[8];
+ stream.ReadExactly(buff);
uint lo = (uint)(buff[0] | buff[1] << 8 |
buff[2] << 16 | buff[3] << 24);
uint hi = (uint)(buff[4] | buff[5] << 8 |
@@ -268,19 +358,26 @@ public static long ReadInt64(this Stream stream)
return (long)((ulong)hi) << 32 | lo;
}
- //async versions of the above methods
+ // async versions of the above methods
public static async Task WriteInt32BigEndianAsync(this Stream output, int value, CancellationToken cancellationToken = default)
{
if (output is null)
throw new ArgumentNullException(nameof(output));
- byte[] buff = new byte[4];
- buff[0] = (byte)(value >> 24);
- buff[1] = (byte)(value >> 16);
- buff[2] = (byte)(value >> 8);
- buff[3] = (byte)value;
+ byte[] buff = ArrayPool<byte>.Shared.Rent(4);
+ try
+ {
+ buff[0] = (byte)(value >> 24);
+ buff[1] = (byte)(value >> 16);
+ buff[2] = (byte)(value >> 8);
+ buff[3] = (byte)value;
- await output.WriteAsync(buff, 0, buff.Length, cancellationToken).ConfigureAwait(false);
+ await output.WriteAsync(buff, 0, 4, cancellationToken).ConfigureAwait(false);
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buff);
+ }
}
public static async Task WriteInt64BigEndianAsync(this Stream output, long value, CancellationToken cancellationToken = default)
@@ -288,17 +385,24 @@ public static async Task WriteInt64BigEndianAsync(this Stream output, long value
if (output is null)
throw new ArgumentNullException(nameof(output));
- byte[] buff = new byte[8];
- buff[0] = (byte)(value >> 56);
- buff[1] = (byte)(value >> 48);
- buff[2] = (byte)(value >> 40);
- buff[3] = (byte)(value >> 32);
- buff[4] = (byte)(value >> 24);
- buff[5] = (byte)(value >> 16);
- buff[6] = (byte)(value >> 8);
- buff[7] = (byte)value;
-
- await output.WriteAsync(buff, 0, buff.Length, cancellationToken).ConfigureAwait(false);
+ byte[] buff = ArrayPool<byte>.Shared.Rent(8);
+ try
+ {
+ buff[0] = (byte)(value >> 56);
+ buff[1] = (byte)(value >> 48);
+ buff[2] = (byte)(value >> 40);
+ buff[3] = (byte)(value >> 32);
+ buff[4] = (byte)(value >> 24);
+ buff[5] = (byte)(value >> 16);
+ buff[6] = (byte)(value >> 8);
+ buff[7] = (byte)value;
+
+ await output.WriteAsync(buff, 0, 8, cancellationToken).ConfigureAwait(false);
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buff);
+ }
}
public static async Task WriteUTFAsync(this Stream output, string value, CancellationToken cancellationToken = default)
@@ -317,7 +421,7 @@ public static async Task WriteUTFAsync(this Stream output, string value, Cancell
{
int offset = 0;
offset = WriteInt16BigEndianToBuffer((int)utfCount, buffer, offset);
- offset = WriteUTFBytesToBuffer(value, (int)utfCount, buffer, offset);
+ offset = WriteUTFBytesToBuffer(value, buffer, offset);
await output.WriteAsync(buffer, 0, offset, cancellationToken).ConfigureAwait(false);
}
@@ -331,11 +435,17 @@ public static async Task<int> ReadInt32BigEndianAsync(this Stream input, Cancell
if (input is null)
throw new ArgumentNullException(nameof(input));
- byte[] buff = new byte[4];
- int read = await input.ReadAsync(buff, 0, buff.Length, cancellationToken).ConfigureAwait(false);
- if (read < buff.Length) throw new EndOfStreamException();
+ byte[] buff = ArrayPool<byte>.Shared.Rent(4);
+ try
+ {
+ await input.ReadExactlyAsync(buff, 0, 4, cancellationToken).ConfigureAwait(false);
- return (buff[0] << 24) | (buff[1] << 16) | (buff[2] << 8) | buff[3];
+ return (buff[0] << 24) | (buff[1] << 16) | (buff[2] << 8) | buff[3];
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buff);
+ }
}
public static async Task<long> ReadInt64BigEndianAsync(this Stream input, CancellationToken cancellationToken = default)
@@ -343,18 +453,24 @@ public static async Task<long> ReadInt64BigEndianAsync(this Stream input, Cancel
if (input is null)
throw new ArgumentNullException(nameof(input));
- byte[] buff = new byte[8];
- int read = await input.ReadAsync(buff, 0, buff.Length, cancellationToken).ConfigureAwait(false);
- if (read < buff.Length) throw new EndOfStreamException();
-
- return ((long)buff[0] << 56) |
- ((long)buff[1] << 48) |
- ((long)buff[2] << 40) |
- ((long)buff[3] << 32) |
- ((long)buff[4] << 24) |
- ((long)buff[5] << 16) |
- ((long)buff[6] << 8) |
- buff[7];
+ byte[] buff = ArrayPool<byte>.Shared.Rent(8);
+ try
+ {
+ await input.ReadExactlyAsync(buff, 0, 8, cancellationToken).ConfigureAwait(false);
+
+ return ((long)buff[0] << 56) |
+ ((long)buff[1] << 48) |
+ ((long)buff[2] << 40) |
+ ((long)buff[3] << 32) |
+ ((long)buff[4] << 24) |
+ ((long)buff[5] << 16) |
+ ((long)buff[6] << 8) |
+ buff[7];
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buff);
+ }
}
public static async Task<string> ReadUTFAsync(this Stream input, CancellationToken cancellationToken = default)
@@ -365,18 +481,14 @@ public static async Task<string> ReadUTFAsync(this Stream input, CancellationTok
byte[] lenBuff = ArrayPool<byte>.Shared.Rent(2);
try
{
- int readLen = await input.ReadAsync(lenBuff, 0, 2, cancellationToken).ConfigureAwait(false);
- if (readLen < 2)
- throw new EndOfStreamException("Unexpected end of stream while reading UTF length.");
+ await input.ReadExactlyAsync(lenBuff, 0, 2, cancellationToken).ConfigureAwait(false);
int length = (lenBuff[0] << 8) | lenBuff[1];
byte[] buffer = ArrayPool<byte>.Shared.Rent(length);
try
{
- int read = await input.ReadAsync(buffer, 0, length, cancellationToken).ConfigureAwait(false);
- if (read < length)
- throw new EndOfStreamException("Unexpected end of stream while reading UTF string.");
+ await input.ReadExactlyAsync(buffer, 0, length, cancellationToken).ConfigureAwait(false);
return Encoding.UTF8.GetString(buffer, 0, length);
}
@@ -410,14 +522,14 @@ private static long CountUTFBytes(string value)
return utfCount;
}
- private static int WriteInt16BigEndianToBuffer(int value, byte[] buffer, int offset)
+ private static int WriteInt16BigEndianToBuffer(int value, Span<byte> buffer, int offset)
{
buffer[offset++] = (byte)(value >> 8);
buffer[offset++] = (byte)value;
return offset;
}
- private static int WriteUTFBytesToBuffer(string value, long count, byte[] buffer, int offset)
+ private static int WriteUTFBytesToBuffer(string value, Span<byte> buffer, int offset)
{
foreach (char ch in value)
{
@@ -443,7 +555,7 @@ private static int WriteUTFBytesToBuffer(string value, long count, byte[] buffer
private static class SR
{
public const string IO_StreamTooLong = "Stream was too long.";
+ public const string IO_EOF_ReadBeyondEOF = "Unable to read beyond the end of the stream.";
}
-
}
}