Example #1
0
        public override async ValueTask <int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
        {
            CheckNotDisposed();
            ValidateBufferArgs(buffer, offset, length);

            if (!IsOpen)
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen);
            }


            // do we have something buffered?
            var count = ReadBuffer.Length - ReadBuffer.Position;

            if (count > 0)
            {
                return(await ReadBuffer.ReadAsync(buffer, offset, length, cancellationToken));
            }

            // does the request even fit into the buffer?
            // Note we test for >= instead of > to avoid nonsense buffering
            if (length >= ReadBuffer.Capacity)
            {
                return(await InnerTransport.ReadAsync(buffer, offset, length, cancellationToken));
            }

            // buffer a new chunk of bytes from the underlying transport
            ReadBuffer.Length = ReadBuffer.Capacity;
            ArraySegment <byte> bufSegment;

            ReadBuffer.TryGetBuffer(out bufSegment);
            ReadBuffer.Length = await InnerTransport.ReadAsync(bufSegment.Array, 0, bufSegment.Count, cancellationToken);

            ReadBuffer.Position = 0;

            // deliver the bytes
            return(await ReadBuffer.ReadAsync(buffer, offset, length, cancellationToken));
        }
Example #2
0
        public override async Task <int> ReadAsync(byte[] buffer, int offset, int length,
                                                   CancellationToken cancellationToken)
        {
            //TODO: investigate how it should work correctly
            CheckNotDisposed();

            ValidateBufferArgs(buffer, offset, length);

            if (!IsOpen)
            {
                throw new TTransportException(TTransportException.ExceptionType.NotOpen);
            }

            if (_inputBuffer.Capacity < _bufSize)
            {
                _inputBuffer.Capacity = _bufSize;
            }

            var got = await _inputBuffer.ReadAsync(buffer, offset, length, cancellationToken);

            if (got > 0)
            {
                return(got);
            }

            _inputBuffer.Seek(0, SeekOrigin.Begin);
            _inputBuffer.SetLength(_inputBuffer.Capacity);

            ArraySegment <byte> bufSegment;

            _inputBuffer.TryGetBuffer(out bufSegment);

            // investigate
            var filled = await _transport.ReadAsync(bufSegment.Array, 0, (int)_inputBuffer.Length, cancellationToken);

            _inputBuffer.SetLength(filled);

            if (filled == 0)
            {
                return(0);
            }

            return(await ReadAsync(buffer, offset, length, cancellationToken));
        }