@@ -6,58 +6,39 @@ namespace Ramstack.Parsing.Utilities;
66internal static class TextHelper
77{
88 /// <summary>
9- /// Returns the line number for the specified index in the given source string .
9+ /// Calculates the line and column numbers for the specified index in the specified character span .
1010 /// </summary>
11- /// <param name="source">The source string .</param>
12- /// <param name="index">The index in the source string for which to determine the line number .</param>
11+ /// <param name="source">The character span representing the text content .</param>
12+ /// <param name="index">The index within the span for which to determine the line and column numbers .</param>
1313 /// <returns>
14- /// The line number corresponding to the specified index.
14+ /// A tuple containing the line and column numbers corresponding to the specified index.
1515 /// </returns>
16- public static int GetLine ( ReadOnlySpan < char > source , int index )
16+ public static ( int Line , int Column ) GetLineColumn ( ReadOnlySpan < char > source , int index )
1717 {
1818 var line = 1 ;
19+ var column = 1 ;
1920
20- if ( index >= source . Length )
21- index = source . Length - 1 ;
21+ if ( ( uint ) index < ( uint ) source . Length )
22+ source = source [ .. index ] ;
2223
23- while ( true )
24+ for ( var i = 0 ; i < source . Length ; i ++ )
2425 {
25- if ( ( uint ) index >= ( uint ) source . Length )
26- break ;
26+ column ++ ;
2727
28- if ( source [ index ] == '\n ' )
28+ if ( source [ i ] == '\n ' )
29+ {
2930 line ++ ;
31+ column = 1 ;
32+ }
33+ else if ( source [ i ] == '\r ' && i + 1 < source . Length && source [ i + 1 ] == '\n ' )
34+ {
35+ i ++ ;
3036
31- index -- ;
32- }
33-
34- return line ;
35- }
36-
37- /// <summary>
38- /// Returns the column number for the specified index in the given source string.
39- /// </summary>
40- /// <param name="source">The source string.</param>
41- /// <param name="index">The index in the source string for which to determine the column number.</param>
42- /// <returns>
43- /// The column number corresponding to the specified index.
44- /// </returns>
45- public static int GetColumn ( ReadOnlySpan < char > source , int index )
46- {
47- var column = 1 ;
48- index -- ;
49-
50- if ( index >= source . Length )
51- index = source . Length - 1 ;
52-
53- while ( ( uint ) index < ( uint ) source . Length
54- && source [ index ] != '\n '
55- && source [ index ] != '\r ' )
56- {
57- column ++ ;
58- index -- ;
37+ line ++ ;
38+ column = 1 ;
39+ }
5940 }
6041
61- return column ;
42+ return ( line , column ) ;
6243 }
6344}
0 commit comments