Skip to content

Commit 82fe8dd

Browse files
Remove temporary allocations in Session and Identity (#41671)
1 parent 2c2074b commit 82fe8dd

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

src/Identity/Extensions.Core/src/Base32.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,20 +43,20 @@ public static byte[] FromBase32(string input)
4343
{
4444
throw new ArgumentNullException(nameof(input));
4545
}
46-
input = input.TrimEnd('=').ToUpperInvariant();
47-
if (input.Length == 0)
46+
var trimmedInput = input.AsSpan().TrimEnd('=');
47+
if (trimmedInput.Length == 0)
4848
{
4949
return Array.Empty<byte>();
5050
}
5151

52-
var output = new byte[input.Length * 5 / 8];
52+
var output = new byte[trimmedInput.Length * 5 / 8];
5353
var bitIndex = 0;
5454
var inputIndex = 0;
5555
var outputBits = 0;
5656
var outputIndex = 0;
5757
while (outputIndex < output.Length)
5858
{
59-
var byteIndex = _base32Chars.IndexOf(input[inputIndex]);
59+
var byteIndex = _base32Chars.IndexOf(char.ToUpperInvariant(trimmedInput[inputIndex]));
6060
if (byteIndex < 0)
6161
{
6262
throw new FormatException();

src/Middleware/Session/src/SessionMiddleware.cs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,15 @@ public async Task Invoke(HttpContext context)
8585
if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
8686
{
8787
// No valid cookie, new session.
88-
var guidBytes = new byte[16];
89-
RandomNumberGenerator.Fill(guidBytes);
90-
sessionKey = new Guid(guidBytes).ToString();
88+
sessionKey = GetSessionKey();
89+
90+
static string GetSessionKey()
91+
{
92+
Span<byte> guidBytes = stackalloc byte[16];
93+
RandomNumberGenerator.Fill(guidBytes);
94+
return new Guid(guidBytes).ToString();
95+
}
96+
9197
cookieValue = CookieProtection.Protect(_dataProtector, sessionKey);
9298
var establisher = new SessionEstablisher(context, cookieValue, _options);
9399
tryEstablishSession = establisher.TryEstablishSession;

0 commit comments

Comments
 (0)