@@ -199,10 +199,7 @@ internal static InboundFrame ReadFrom(Stream reader, byte[] frameHeaderBuffer)
199199 {
200200 try
201201 {
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 ) ;
206203 }
207204 catch ( IOException ioe )
208205 {
@@ -234,19 +231,15 @@ internal static InboundFrame ReadFrom(Stream reader, byte[] frameHeaderBuffer)
234231 // Is returned by InboundFrame.ReturnPayload in Connection.MainLoopIteration
235232 int readSize = payloadSize + EndMarkerLength ;
236233 byte [ ] payloadBytes = ArrayPool < byte > . Shared . Rent ( readSize ) ;
237- int bytesRead = 0 ;
238234 try
239235 {
240- while ( bytesRead < readSize )
241- {
242- bytesRead += reader . Read ( payloadBytes , bytesRead , readSize - bytesRead ) ;
243- }
236+ ReadFromStream ( reader , payloadBytes , readSize ) ;
244237 }
245238 catch ( Exception )
246239 {
247240 // Early EOF.
248241 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") ;
250243 }
251244
252245 if ( payloadBytes [ payloadSize ] != Constants . FrameEnd )
@@ -258,6 +251,27 @@ internal static InboundFrame ReadFrom(Stream reader, byte[] frameHeaderBuffer)
258251 return new InboundFrame ( type , channel , new Memory < byte > ( payloadBytes , 0 , payloadSize ) , payloadBytes ) ;
259252 }
260253
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+
261275 public byte [ ] TakeoverPayload ( )
262276 {
263277 return _rentedArray ;
0 commit comments