@@ -114,12 +114,12 @@ private static string ComputeFinalKey(byte[] preKey, ComponentState componentSta
114114 Span < byte > keyBuffer = stackalloc byte [ 1024 ] ;
115115 var currentBuffer = keyBuffer ;
116116 preKey . CopyTo ( keyBuffer ) ;
117- currentBuffer = currentBuffer [ preKey . Length ..] ;
118117 if ( key is IUtf8SpanFormattable spanFormattable )
119118 {
120119 var wroteKey = false ;
121120 while ( ! wroteKey )
122121 {
122+ currentBuffer = keyBuffer [ preKey . Length ..] ;
123123 wroteKey = spanFormattable . TryFormat ( currentBuffer , out var written , "" , CultureInfo . InvariantCulture ) ;
124124 if ( ! wroteKey )
125125 {
@@ -139,12 +139,15 @@ private static string ComputeFinalKey(byte[] preKey, ComponentState componentSta
139139 var wroteKey = false ;
140140 while ( ! wroteKey )
141141 {
142+ currentBuffer = keyBuffer [ preKey . Length ..] ;
142143 wroteKey = Encoding . UTF8 . TryGetBytes ( keySpan , currentBuffer , out var written ) ;
143144 if ( ! wroteKey )
144145 {
145146 // It is really unlikely that we will enter here, but we need to handle this case
146147 Debug . Assert ( written == 0 ) ;
147- GrowBuffer ( ref pool , ref keyBuffer ) ;
148+ // Since this is utf-8, grab a buffer the size of the key * 4 + the preKey size
149+ // this guarantees we have enough space to encode the key
150+ GrowBuffer ( ref pool , ref keyBuffer , keySpan . Length * 4 + preKey . Length ) ;
148151 }
149152 else
150153 {
@@ -153,7 +156,7 @@ private static string ComputeFinalKey(byte[] preKey, ComponentState componentSta
153156 }
154157 }
155158
156- keyBuffer = keyBuffer [ ..( keyBuffer . Length - currentBuffer . Length ) ] ;
159+ keyBuffer = keyBuffer [ ..( preKey . Length + currentBuffer . Length ) ] ;
157160
158161 var hashSucceeded = SHA256 . TryHashData ( keyBuffer , keyHash , out _ ) ;
159162 Debug . Assert ( hashSucceeded ) ;
@@ -183,9 +186,9 @@ private static ReadOnlySpan<char> ResolveKeySpan(object? key)
183186 return default ;
184187 }
185188
186- private static void GrowBuffer ( ref byte [ ] ? pool , ref Span < byte > keyBuffer )
189+ private static void GrowBuffer ( ref byte [ ] ? pool , ref Span < byte > keyBuffer , int ? size = null )
187190 {
188- var newPool = pool == null ? ArrayPool < byte > . Shared . Rent ( 2048 ) : ArrayPool < byte > . Shared . Rent ( pool . Length * 2 ) ;
191+ var newPool = pool == null ? ArrayPool < byte > . Shared . Rent ( size ?? 2048 ) : ArrayPool < byte > . Shared . Rent ( pool . Length * 2 ) ;
189192 keyBuffer . CopyTo ( newPool ) ;
190193 keyBuffer = newPool ;
191194 if ( pool != null )
0 commit comments