@@ -199,10 +199,7 @@ internal static InboundFrame ReadFrom(Stream reader, byte[] frameHeaderBuffer)
199
199
{
200
200
try
201
201
{
202
- if ( reader . Read ( frameHeaderBuffer , 0 , frameHeaderBuffer . Length ) == 0 )
203
- {
204
- throw new EndOfStreamException ( "Reached the end of the stream. Possible authentication failure." ) ;
205
- }
202
+ ReadFromStream ( reader , frameHeaderBuffer , frameHeaderBuffer . Length ) ;
206
203
}
207
204
catch ( IOException ioe )
208
205
{
@@ -234,19 +231,15 @@ internal static InboundFrame ReadFrom(Stream reader, byte[] frameHeaderBuffer)
234
231
// Is returned by InboundFrame.ReturnPayload in Connection.MainLoopIteration
235
232
int readSize = payloadSize + EndMarkerLength ;
236
233
byte [ ] payloadBytes = ArrayPool < byte > . Shared . Rent ( readSize ) ;
237
- int bytesRead = 0 ;
238
234
try
239
235
{
240
- while ( bytesRead < readSize )
241
- {
242
- bytesRead += reader . Read ( payloadBytes , bytesRead , readSize - bytesRead ) ;
243
- }
236
+ ReadFromStream ( reader , payloadBytes , readSize ) ;
244
237
}
245
238
catch ( Exception )
246
239
{
247
240
// Early EOF.
248
241
ArrayPool < byte > . Shared . Return ( payloadBytes ) ;
249
- throw new MalformedFrameException ( $ "Short frame - expected to read { readSize } bytes, only got { bytesRead } bytes ") ;
242
+ throw new MalformedFrameException ( $ "Short frame - expected to read { readSize } bytes") ;
250
243
}
251
244
252
245
if ( payloadBytes [ payloadSize ] != Constants . FrameEnd )
@@ -258,6 +251,27 @@ internal static InboundFrame ReadFrom(Stream reader, byte[] frameHeaderBuffer)
258
251
return new InboundFrame ( type , channel , new Memory < byte > ( payloadBytes , 0 , payloadSize ) , payloadBytes ) ;
259
252
}
260
253
254
+ [ MethodImpl ( MethodImplOptions . AggressiveInlining ) ]
255
+ private static void ReadFromStream ( Stream reader , byte [ ] buffer , int toRead )
256
+ {
257
+ int bytesRead = 0 ;
258
+ do
259
+ {
260
+ int read = reader . Read ( buffer , bytesRead , toRead - bytesRead ) ;
261
+ if ( read == 0 )
262
+ {
263
+ ThrowEndOfStream ( ) ;
264
+ }
265
+
266
+ bytesRead += read ;
267
+ } while ( bytesRead != toRead ) ;
268
+
269
+ static void ThrowEndOfStream ( )
270
+ {
271
+ throw new EndOfStreamException ( "Reached the end of the stream. Possible authentication failure." ) ;
272
+ }
273
+ }
274
+
261
275
public byte [ ] TakeoverPayload ( )
262
276
{
263
277
return _rentedArray ;
0 commit comments