@@ -198,25 +198,25 @@ IReadOnlyList<byte> errorHandler(IList<byte> data, int start, int end) {
198198 }
199199 private static byte [ ] _replacementMarker ;
200200
201- public static PythonTuple /*!*/ escape_encode ( [ BytesConversion ] IList < byte > text , string errors = "strict" ) {
202- StringBuilder res = new StringBuilder ( ) ;
203- for ( int i = 0 ; i < text . Count ; i ++ ) {
204- switch ( text [ i ] ) {
205- case ( byte ) '\n ' : res . Append ( " \\ n" ) ; break ;
206- case ( byte ) '\r ' : res . Append ( " \\ r" ) ; break ;
207- case ( byte ) '\t ' : res . Append ( " \\ t" ) ; break ;
208- case ( byte ) '\\ ' : res . Append ( " \\ \\ " ) ; break ;
209- case ( byte ) '\' ' : res . Append ( " \\ '" ) ; break ;
201+ public static PythonTuple /*!*/ escape_encode ( [ BytesConversion ] IList < byte > data , string errors = "strict" ) {
202+ List < byte > buf = new List < byte > ( data . Count ) ;
203+ foreach ( byte b in data ) {
204+ switch ( b ) {
205+ case ( byte ) '\n ' : buf . Add ( ( byte ) ' \\ ' ) ; buf . Add ( ( byte ) 'n' ) ; break ;
206+ case ( byte ) '\r ' : buf . Add ( ( byte ) ' \\ ' ) ; buf . Add ( ( byte ) 'r' ) ; break ;
207+ case ( byte ) '\t ' : buf . Add ( ( byte ) ' \\ ' ) ; buf . Add ( ( byte ) 't' ) ; break ;
208+ case ( byte ) '\\ ' : buf . Add ( ( byte ) ' \\ ' ) ; buf . Add ( ( byte ) ' \\ ' ) ; break ;
209+ case ( byte ) '\' ' : buf . Add ( ( byte ) ' \\ ') ; buf . Add ( ( byte ) ' \' ' ) ; break ;
210210 default :
211- if ( text [ i ] < 0x20 || text [ i ] >= 0x7f ) {
212- res . AppendFormat ( "\\ x{0 :x2}" , text [ i ] ) ;
211+ if ( b < 0x20 || b >= 0x7f ) {
212+ buf . AddRange ( $ "\\ x{ b : x2} ". Select ( c => ( byte ) c ) ) ;
213213 } else {
214- res . Append ( ( char ) text [ i ] ) ;
214+ buf . Add ( b ) ;
215215 }
216216 break ;
217217 }
218218 }
219- return PythonTuple . MakeTuple ( Bytes . Make ( res . ToString ( ) . MakeByteArray ( ) ) , text . Count ) ;
219+ return PythonTuple . MakeTuple ( Bytes . Make ( buf . ToArray ( ) ) , data . Count ) ;
220220 }
221221
222222 #endregion
0 commit comments