@@ -511,43 +511,40 @@ private static (int newLineIndex, int newLineChars) FindNewlineIndex (
511511 int available ,
512512 bool allowStandaloneCr )
513513 {
514- var end = start + available ;
514+ var span = buffer . AsSpan ( start , available ) ;
515515
516- for ( var i = start ; i < end ; i ++ )
516+ //Vectorized Search for \n
517+ var lfIndex = span . IndexOf ( '\n ' ) ;
518+ if ( lfIndex != - 1 )
517519 {
518- var current = buffer [ i ] ;
519-
520- if ( current == '\n ' )
520+ // Found \n - check if preceded by \r
521+ if ( lfIndex > 0 && span [ lfIndex - 1 ] == '\r ' )
521522 {
522- // Check if preceded by \r for \r\n
523- if ( i > start && buffer [ i - 1 ] == '\r ' )
524- {
525- return ( newLineIndex : i - 1 , newLineChars : 2 ) ;
526- }
527- return ( newLineIndex : i , newLineChars : 1 ) ;
523+ return ( newLineIndex : start + lfIndex - 1 , newLineChars : 2 ) ;
528524 }
529525
530- if ( current == '\r ' )
526+ return ( newLineIndex : start + lfIndex , newLineChars : 1 ) ;
527+ }
528+
529+ //Vectorized search for \r
530+ var crIndex = span . IndexOf ( '\r ' ) ;
531+ if ( crIndex != - 1 )
532+ {
533+ // Check if at end of buffer
534+ if ( crIndex + 1 >= span . Length )
531535 {
532- // Check if at end of buffer
533- if ( i + 1 >= end )
536+ if ( allowStandaloneCr )
534537 {
535- // If this is the final buffer, treat as standalone \r
536- if ( allowStandaloneCr )
537- {
538- return ( newLineIndex : i , newLineChars : 1 ) ;
539- }
540- // Otherwise wait for more data to determine if it's \r\n
541- break ;
538+ return ( newLineIndex : start + crIndex , newLineChars : 1 ) ;
542539 }
543540
544- // Check next char
545- if ( buffer [ i + 1 ] != ' \n ' )
546- {
547- // Standalone \r
548- return ( newLineIndex : i , newLineChars : 1 ) ;
549- }
550- // Will be handled as \r\n when we reach the \n
541+ return ( newLineIndex : - 1 , newLineChars : 0 ) ;
542+ }
543+
544+ // Check next char
545+ if ( span [ crIndex + 1 ] != ' \n ' )
546+ {
547+ return ( newLineIndex : start + crIndex , newLineChars : 1 ) ;
551548 }
552549 }
553550
0 commit comments