Skip to content

Commit a046b3f

Browse files
committed
standartize API + use stackalloc for small arrays
1 parent 4b5ca1a commit a046b3f

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

src/DataProtection/DataProtection/src/KeyManagement/KeyRingBasedDataProtector.cs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,8 @@ internal static byte[] BuildAadTemplateBytes(string[] purposes)
367367
var keySize = sizeof(Guid);
368368
int totalPurposeLen = 4 + keySize + 4;
369369

370-
var purposeLengthsPool = ArrayPool<int>.Shared.Rent(purposes.Length);
370+
int[]? lease = null;
371+
Span<int> purposeLengthsPool = purposes.Length <= 32 ? stackalloc int[purposes.Length] : (lease = ArrayPool<int>.Shared.Rent(purposes.Length)).AsSpan(0, purposes.Length);
371372
for (int i = 0; i < purposes.Length; i++)
372373
{
373374
string purpose = purposes[i];
@@ -393,18 +394,18 @@ internal static byte[] BuildAadTemplateBytes(string[] purposes)
393394
{
394395
string purpose = purposes[i];
395396

396-
// writing `utf8ByteCount (7-bit encoded integer) || utf8Text`
397+
// writing `utf8ByteCount (7-bit encoded integer)`
397398
// we have already calculated the lengths of the purpose strings, so just get it from the pool
398399
index += targetSpan.Slice(index).Write7BitEncodedInt(purposeLengthsPool[i]);
399400

400-
#if NET10_0_OR_GREATER
401-
index += EncodingUtil.SecureUtf8Encoding.GetBytes(purpose.AsSpan(), targetSpan.Slice(index));
402-
#else
401+
// write the utf8text for the purpose
403402
index += EncodingUtil.SecureUtf8Encoding.GetBytes(purpose, charIndex: 0, charCount: purpose.Length, bytes: targetArr, byteIndex: index);
404-
#endif
405403
}
406404

407-
ArrayPool<int>.Shared.Return(purposeLengthsPool);
405+
if (lease is not null)
406+
{
407+
ArrayPool<int>.Shared.Return(lease);
408+
}
408409
Debug.Assert(index == targetArr.Length);
409410

410411
return targetArr;

0 commit comments

Comments
 (0)