22// Licensed under the MIT License.
33
44using System ;
5+ using System . Buffers ;
56using System . IO ;
67using System . Text ;
78using System . Threading ;
@@ -11,39 +12,50 @@ namespace Azure.Core
1112{
1213 internal class StringRequestContent : RequestContent
1314 {
14- private readonly byte [ ] _bytes ;
15+ private readonly byte [ ] _buffer ;
16+ private readonly int _actualByteCount ;
1517
1618 public StringRequestContent ( string value )
1719 {
18- _bytes = Encoding . UTF8 . GetBytes ( value ) ;
20+ #if NET6_0_OR_GREATER
21+ var byteCount = Encoding . UTF8 . GetMaxByteCount ( value . Length ) ;
22+ _buffer = ArrayPool < byte > . Shared . Rent ( byteCount ) ;
23+ _actualByteCount = Encoding . UTF8 . GetBytes ( value , _buffer ) ;
24+ #else
25+ _buffer = Encoding . UTF8 . GetBytes ( value ) ;
26+ _actualByteCount = _buffer . Length ;
27+ #endif
1928 }
2029
2130 public override async Task WriteToAsync ( Stream stream , CancellationToken cancellation )
2231 {
2332#if NET6_0_OR_GREATER
24- await stream . WriteAsync ( _bytes . AsMemory ( ) , cancellation ) . ConfigureAwait ( false ) ;
33+ await stream . WriteAsync ( _buffer . AsMemory ( 0 , _actualByteCount ) , cancellation ) . ConfigureAwait ( false ) ;
2534#else
26- await stream . WriteAsync ( _bytes , 0 , _bytes . Length , cancellation ) . ConfigureAwait ( false ) ;
35+ await stream . WriteAsync ( _buffer , 0 , _actualByteCount , cancellation ) . ConfigureAwait ( false ) ;
2736#endif
2837 }
2938
3039 public override void WriteTo ( Stream stream , CancellationToken cancellation )
3140 {
3241#if NET6_0_OR_GREATER
33- stream . Write ( _bytes . AsSpan ( ) ) ;
42+ stream . Write ( _buffer . AsSpan ( 0 , _actualByteCount ) ) ;
3443#else
35- stream . Write ( _bytes , 0 , _bytes . Length ) ;
44+ stream . Write ( _buffer , 0 , _actualByteCount ) ;
3645#endif
3746 }
3847
3948 public override bool TryComputeLength ( out long length )
4049 {
41- length = _bytes . Length ;
50+ length = _actualByteCount ;
4251 return true ;
4352 }
4453
4554 public override void Dispose ( )
4655 {
56+ #if NET6_0_OR_GREATER
57+ ArrayPool < byte > . Shared . Return ( _buffer , clearArray : true ) ;
58+ #endif
4759 }
4860 }
4961}
0 commit comments