Files
s7netplus/S7.Net/StreamExtensions.cs
Serge Camille 09c8b18d3d Adjust ReadFixed implementation somewhat. Exceeding the length of the buffer was already an error before.
Change the tests by replacing the memory buffer with a Fake stream giving 1 byte at a time.
2020-09-03 20:48:18 +02:00

56 lines
1.9 KiB
C#

using System;
using System.IO;
using System.Threading.Tasks;
namespace S7.Net
{
/// <summary>
/// Extensions for Streams
/// </summary>
public static class StreamExtensions
{
/// <summary>
/// Reads a fixed amount of bytes from the stream into the buffer
/// </summary>
/// <param name="stream">the Stream to read from</param>
/// <param name="buffer">the buffer to read into</param>
/// <param name="offset">the offset in the buffer to read into</param>
/// <param name="count">the amount of bytes to read into the buffer</param>
/// <returns>returns the amount of read bytes</returns>
public static int ReadFixed(this Stream stream, byte[] buffer, int offset, int count)
{
int read = 0;
int received;
do
{
received = stream.Read(buffer, offset + read, count - read);
read += received;
}
while (read < count && received > 0);
return read;
}
/// <summary>
/// Reads a fixed amount of bytes from the stream into the buffer
/// </summary>
/// <param name="stream">the Stream to read from</param>
/// <param name="buffer">the buffer to read into</param>
/// <param name="offset">the offset in the buffer to read into</param>
/// <param name="count">the amount of bytes to read into the buffer</param>
/// <returns>returns the amount of read bytes</returns>
public static async Task<int> ReadFixedAsync(this Stream stream, byte[] buffer, int offset, int count)
{
int read = 0;
int received;
do
{
received = await stream.ReadAsync(buffer, offset + read, count - read);
read += received;
}
while (read < count && received > 0);
return read;
}
}
}