2021-04-29 15:35:57 -04:00
|
|
|
// Copyright Epic Games, Inc. All Rights Reserved.
|
|
|
|
|
|
2021-04-29 15:10:34 -04:00
|
|
|
using System;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
2022-03-16 11:18:39 -04:00
|
|
|
namespace Horde.Build.Utilities
|
2021-04-29 15:10:34 -04:00
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Extension methods for working with streams
|
|
|
|
|
/// </summary>
|
|
|
|
|
static class StreamExtensions
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Reads data of a fixed size into the buffer. Throws an exception if the whole block cannot be read.
|
|
|
|
|
/// </summary>
|
2022-03-23 14:50:23 -04:00
|
|
|
/// <param name="stream">The stream to read from</param>
|
|
|
|
|
/// <param name="data">Buffer to receive the read data</param>
|
|
|
|
|
/// <param name="offset">Offset within the buffer to read the new data</param>
|
|
|
|
|
/// <param name="length">Length of the data to read</param>
|
2021-04-29 15:10:34 -04:00
|
|
|
/// <returns>Async task</returns>
|
2022-03-23 14:50:23 -04:00
|
|
|
public static Task ReadFixedSizeDataAsync(this Stream stream, byte[] data, int offset, int length)
|
2021-04-29 15:10:34 -04:00
|
|
|
{
|
2022-03-23 14:50:23 -04:00
|
|
|
return ReadFixedSizeDataAsync(stream, data.AsMemory(offset, length));
|
2021-04-29 15:10:34 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Reads data of a fixed size into the buffer. Throws an exception if the whole block cannot be read.
|
|
|
|
|
/// </summary>
|
2022-03-23 14:50:23 -04:00
|
|
|
/// <param name="stream">The stream to read from</param>
|
|
|
|
|
/// <param name="data">Buffer to receive the read data</param>
|
2021-04-29 15:10:34 -04:00
|
|
|
/// <returns>Async task</returns>
|
2022-03-23 14:50:23 -04:00
|
|
|
public static async Task ReadFixedSizeDataAsync(this Stream stream, Memory<byte> data)
|
2021-04-29 15:10:34 -04:00
|
|
|
{
|
2022-03-23 14:50:23 -04:00
|
|
|
while (data.Length > 0)
|
2021-04-29 15:10:34 -04:00
|
|
|
{
|
2022-03-23 14:50:23 -04:00
|
|
|
int count = await stream.ReadAsync(data);
|
|
|
|
|
if (count == 0)
|
2021-04-29 15:10:34 -04:00
|
|
|
{
|
|
|
|
|
throw new EndOfStreamException();
|
|
|
|
|
}
|
2022-03-23 14:50:23 -04:00
|
|
|
data = data.Slice(count);
|
2021-04-29 15:10:34 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|