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)); }