Ejemplo n.º 1
0
        public async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default)
        {
            int result = await reader.ReadAsync(buffer, offset, count, cancellationToken);

            if (result > 0)
            {
                if (bufferLength + result > bufferPool.BufferSize)
                {
                    await FlushAsync(cancellationToken);
                }

                Buffer.BlockCopy(buffer, offset, this.buffer, bufferLength, result);
                bufferLength += result;
                ReadBytes    += result;
                await FlushAsync(cancellationToken);
            }

            return(result);
        }
        /// <summary>
        ///     Copies the specified bytes to the stream from the input stream
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="count"></param>
        /// <param name="onCopy"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task copyBytesFromStream(ICustomStreamReader reader, long count, Action <byte[], int, int> onCopy,
                                               CancellationToken cancellationToken)
        {
            var buffer = bufferPool.GetBuffer(BufferSize);

            try
            {
                long remainingBytes = count;

                while (remainingBytes > 0)
                {
                    int bytesToRead = buffer.Length;
                    if (remainingBytes < bytesToRead)
                    {
                        bytesToRead = (int)remainingBytes;
                    }

                    int bytesRead = await reader.ReadAsync(buffer, 0, bytesToRead, cancellationToken);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    remainingBytes -= bytesRead;

                    await stream.WriteAsync(buffer, 0, bytesRead, cancellationToken);

                    onCopy?.Invoke(buffer, 0, bytesRead);
                }
            }
            finally
            {
                bufferPool.ReturnBuffer(buffer);
            }
        }
 /// <summary>
 /// Reads the asynchronous.
 /// </summary>
 /// <param name="buffer">The buffer.</param>
 /// <param name="offset">The offset.</param>
 /// <param name="count">The count.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns></returns>
 Task <int> ICustomStreamReader.ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
 {
     return(baseStream.ReadAsync(buffer, offset, count, cancellationToken));
 }