@@ -26,23 +26,49 @@ private static InvalidOperationException Unreachable([CallerFilePath] string? pa
2626 protected static string ReadString ( Stream stream )
2727 {
2828 int length = ReadInt ( stream ) ;
29- byte [ ] bytes = new byte [ length ] ;
30- ReadExactly ( stream , bytes , 0 , length ) ;
31- return Encoding . UTF8 . GetString ( bytes , 0 , length ) ;
29+ return ReadStringValue ( stream , length ) ;
3230 }
3331
3432 protected static string ReadStringValue ( Stream stream , int size )
3533 {
34+ #if NETCOREAPP
35+ byte [ ] rentedBytes = System . Buffers . ArrayPool < byte > . Shared . Rent ( size ) ;
36+ try
37+ {
38+ ReadExactly ( stream , rentedBytes , 0 , size ) ;
39+ return Encoding . UTF8 . GetString ( rentedBytes , 0 , size ) ;
40+ }
41+ finally
42+ {
43+ System . Buffers . ArrayPool < byte > . Shared . Return ( rentedBytes ) ;
44+ }
45+ #else
3646 byte [ ] bytes = new byte [ size ] ;
3747 ReadExactly ( stream , bytes , 0 , size ) ;
3848 return Encoding . UTF8 . GetString ( bytes , 0 , size ) ;
49+ #endif
3950 }
4051
4152 protected static void WriteString ( Stream stream , string str )
4253 {
54+ #if NETCOREAPP
55+ int byteCount = Encoding . UTF8 . GetByteCount ( str ) ;
56+ byte [ ] rentedBytes = System . Buffers . ArrayPool < byte > . Shared . Rent ( byteCount ) ;
57+ try
58+ {
59+ Encoding . UTF8 . GetBytes ( str , rentedBytes ) ;
60+ WriteInt ( stream , byteCount ) ;
61+ stream . Write ( rentedBytes , 0 , byteCount ) ;
62+ }
63+ finally
64+ {
65+ System . Buffers . ArrayPool < byte > . Shared . Return ( rentedBytes ) ;
66+ }
67+ #else
4368 byte [ ] bytes = Encoding . UTF8 . GetBytes ( str ) ;
4469 WriteInt ( stream , bytes . Length ) ;
4570 stream . Write ( bytes , 0 , bytes . Length ) ;
71+ #endif
4672 }
4773
4874 protected static void WriteSize < T > ( Stream stream )
0 commit comments