private async Task CopyToAsyncImpl(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
int pos = _position;
int n = InternalEmulateRead(_length - _position);
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
if (memStrDest == null)
{
await destination.WriteAsync(_buffer, pos, n, cancellationToken).ConfigureAwait(false);
}
else
{
memStrDest.Write(_buffer, pos, n);
}
}