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.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(buffer, 0, bytesRead), cancellationToken); } } finally { ArrayPool.Shared.Return(buffer); } return; ValueTask DoRead() => source.ReadAsync(new Memory(buffer), cancellationToken); } }