1313// BSD 3-Clause "New" or "Revised" License, see included LICENSE.md file.
1414//-----------------------------------------------------------------------------
1515
16+ using System ;
1617using System . Text ;
1718
1819namespace SIPSorcery . Sys
@@ -30,50 +31,48 @@ public class BufferUtils
3031 /// <returns>The start position in the buffer of the requested string or -1 if not found.</returns>
3132 public static int GetStringPosition ( byte [ ] buffer , int startPosition , int endPosition , string find , string end )
3233 {
33- if ( buffer == null || buffer . Length == 0 || find == null )
34+ if ( buffer == null || buffer . Length == 0 || find == null || find . Length == 0 )
3435 {
3536 return - 1 ;
3637 }
37- else
38- {
39- byte [ ] findArray = Encoding . UTF8 . GetBytes ( find ) ;
40- byte [ ] endArray = ( end != null ) ? Encoding . UTF8 . GetBytes ( end ) : null ;
4138
42- int findPosn = 0 ;
43- int endPosn = 0 ;
39+ byte [ ] findArray = Encoding . UTF8 . GetBytes ( find ) ;
40+ byte [ ] endArray = ( end != null ) ? Encoding . UTF8 . GetBytes ( end ) : null ;
4441
45- for ( int index = startPosition ; index < endPosition && index < buffer . Length ; index ++ )
46- {
47- if ( buffer [ index ] == findArray [ findPosn ] )
48- {
49- findPosn ++ ;
50- }
51- else
52- {
53- findPosn = 0 ;
54- }
42+ int findPosn = 0 ;
43+ int endPosn = 0 ;
5544
56- if ( endArray != null && buffer [ index ] == endArray [ endPosn ] )
57- {
58- endPosn ++ ;
59- }
60- else
61- {
62- endPosn = 0 ;
63- }
45+ for ( int index = startPosition ; index < endPosition && index < buffer . Length ; index ++ )
46+ {
47+ if ( buffer [ index ] == findArray [ findPosn ] )
48+ {
49+ findPosn ++ ;
50+ }
51+ else
52+ {
53+ findPosn = 0 ;
54+ }
6455
65- if ( findPosn == findArray . Length )
66- {
67- return index - findArray . Length + 1 ;
68- }
69- else if ( endArray != null && endPosn == endArray . Length )
70- {
71- return - 1 ;
72- }
56+ if ( endArray != null && buffer [ index ] == endArray [ endPosn ] )
57+ {
58+ endPosn ++ ;
59+ }
60+ else
61+ {
62+ endPosn = 0 ;
7363 }
7464
75- return - 1 ;
65+ if ( findPosn == findArray . Length )
66+ {
67+ return index - findArray . Length + 1 ;
68+ }
69+ else if ( endArray != null && endPosn == endArray . Length )
70+ {
71+ return - 1 ;
72+ }
7673 }
74+
75+ return - 1 ;
7776 }
7877
7978 public static bool HasString ( byte [ ] buffer , int startPosition , int endPosition , string find , string end )
0 commit comments