예제 #1
0
        public async Task <bool> FillBufferAsync(CancellationToken cancellationToken = default)
        {
            await FlushAsync(cancellationToken);

            return(await reader.FillBufferAsync(cancellationToken));
        }
 /// <summary>
 /// Fills the buffer asynchronous.
 /// </summary>
 /// <returns></returns>
 Task <bool> ICustomStreamReader.FillBufferAsync(CancellationToken cancellationToken)
 {
     return(baseStream.FillBufferAsync(cancellationToken));
 }
        /// <summary>
        /// Read a line from the byte stream
        /// </summary>
        /// <returns></returns>
        private async Task <long> readUntilBoundaryAsync(ICustomStreamReader reader, long totalBytesToRead, string boundary, CancellationToken cancellationToken)
        {
            int bufferDataLength = 0;

            var buffer = bufferPool.GetBuffer(bufferSize);

            try
            {
                int  boundaryLength = boundary.Length + 4;
                long bytesRead      = 0;

                while (bytesRead < totalBytesToRead && (reader.DataAvailable || await reader.FillBufferAsync(cancellationToken)))
                {
                    byte newChar = reader.ReadByteFromBuffer();
                    buffer[bufferDataLength] = newChar;

                    bufferDataLength++;
                    bytesRead++;

                    if (bufferDataLength >= boundaryLength)
                    {
                        int startIdx = bufferDataLength - boundaryLength;
                        if (buffer[startIdx] == '-' && buffer[startIdx + 1] == '-')
                        {
                            startIdx += 2;
                            bool ok = true;
                            for (int i = 0; i < boundary.Length; i++)
                            {
                                if (buffer[startIdx + i] != boundary[i])
                                {
                                    ok = false;
                                    break;
                                }
                            }

                            if (ok)
                            {
                                break;
                            }
                        }
                    }

                    if (bufferDataLength == buffer.Length)
                    {
                        // boundary is not longer than 70 bytes according to the specification, so keeping the last 100 (minimum 74) bytes is enough
                        const int bytesToKeep = 100;
                        Buffer.BlockCopy(buffer, buffer.Length - bytesToKeep, buffer, 0, bytesToKeep);
                        bufferDataLength = bytesToKeep;
                    }
                }

                return(bytesRead);
            }
            finally
            {
                bufferPool.ReturnBuffer(buffer);
            }
        }