// Copyright Epic Games, Inc. All Rights Reserved.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace HordeServer.Utilities
{
///
/// Extension methods for working with streams
///
static class StreamExtensions
{
///
/// Reads data of a fixed size into the buffer. Throws an exception if the whole block cannot be read.
///
/// The stream to read from
/// Buffer to receive the read data
/// Offset within the buffer to read the new data
/// Length of the data to read
/// Cancellation token for the operation
/// Async task
public static Task ReadFixedSizeDataAsync(this Stream stream, byte[] data, int offset, int length, CancellationToken cancellationToken = default)
{
return ReadFixedSizeDataAsync(stream, data.AsMemory(offset, length), cancellationToken);
}
///
/// Reads data of a fixed size into the buffer. Throws an exception if the whole block cannot be read.
///
/// The stream to read from
/// Buffer to receive the read data
/// Cancellation token for the operation
/// Async task
public static async Task ReadFixedSizeDataAsync(this Stream stream, Memory data, CancellationToken cancellationToken = default)
{
while (data.Length > 0)
{
int count = await stream.ReadAsync(data, cancellationToken);
if (count == 0)
{
throw new EndOfStreamException();
}
data = data.Slice(count);
}
}
}
}