using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace S7.Net
{
///
/// Extensions for Streams
///
public static class StreamExtensions
{
///
/// Reads bytes from the stream into the buffer until exactly the requested number of bytes (or EOF) have been read
///
/// the Stream to read from
/// the buffer to read into
/// the offset in the buffer to read into
/// the amount of bytes to read into the buffer
/// returns the amount of read bytes
public static int ReadExact(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;
}
///
/// Reads bytes from the stream into the buffer until exactly the requested number of bytes (or EOF) have been read
///
/// the Stream to read from
/// the buffer to read into
/// the offset in the buffer to read into
/// the amount of bytes to read into the buffer
/// A cancellation token that can be used to cancel the asynchronous operation.
/// returns the amount of read bytes
public static async Task ReadExactAsync(this Stream stream, byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
int read = 0;
int received;
do
{
received = await stream.ReadAsync(buffer, offset + read, count - read, cancellationToken).ConfigureAwait(false);
read += received;
}
while (read < count && received > 0);
return read;
}
}
}