Iceshrimp.NET/Iceshrimp.Backend/Core/Extensions/StreamExtensions.cs
Laura Hausmann 7e4282b386
[backend/drive] Switch to stream processing for remote media
This makes sure that files larger than the configured maximum remote media cache size are not loaded into memory (if the size is known), or are only loaded into memory until the configured maximum size before getting discarded (if the size is not known)
2024-07-28 23:32:04 +02:00

31 lines
No EOL
770 B
C#

using System.Buffers;
namespace Iceshrimp.Backend.Core.Extensions;
public static class StreamExtensions
{
public static async Task CopyToAsync(
this Stream source, Stream destination, long? maxLength, CancellationToken cancellationToken
)
{
var buffer = ArrayPool<byte>.Shared.Rent(81920);
try
{
int bytesRead;
var totalBytesRead = 0L;
while ((maxLength == null || totalBytesRead <= maxLength) && (bytesRead = await DoRead()) != 0)
{
totalBytesRead += bytesRead;
await destination.WriteAsync(new ReadOnlyMemory<byte>(buffer, 0, bytesRead), cancellationToken);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
return;
ValueTask<int> DoRead() => source.ReadAsync(new Memory<byte>(buffer), cancellationToken);
}
}